public override string FillField(BaseDataMap map, object importRow,
            ref User user,
            string importValue,
            out bool updatedField)
        {
            updatedField = false;
            var errorMessage = String.Empty;
            var shouldBeMemberOfRole = !String.IsNullOrEmpty(importValue) &&
                                       importValue.Trim() == TrueValue;
            var role = InitializeRoleFromString(RoleName, ref errorMessage);
            if (role != null)
            {
                if (!user.IsInRole(role) && shouldBeMemberOfRole)
                {
                    user.Roles.Add(role);
                    updatedField = true;
                }
                else if (user.IsInRole(role) && !shouldBeMemberOfRole)
                {
                    user.Roles.Remove(role);
                    updatedField = true;

                }
            }
            return errorMessage;
        }
 public override IEnumerable<Item> GetMatchingChildItem(BaseDataMap map, Item listParent, string importValue)
 {
     IEnumerable<Item> t = (from Item c in listParent.GetChildren()
                            where c[MatchOnFieldName].ToLower().Equals(importValue.ToLower())
                            select c).ToList();
     return t;
 }
 public virtual IEnumerable<Item> GetMatchingChildItem(BaseDataMap map, Item listParent, string importValue)
 {
     IEnumerable<Item> t = (from Item c in listParent.GetChildren()
                            where c.DisplayName.ToLower().Equals(StringUtility.GetNewItemName(importValue, 60))
                            select c).ToList();
     return t;
 }
 public ToTextField(BaseDataMap map, Item fieldItem)
     : base(map, fieldItem)
 {
     //store fields
     ExistingDataNames = fieldItem.Fields["From What Fields"].Value.Split(comSplitr, StringSplitOptions.RemoveEmptyEntries);
     Delimiter = fieldItem.Fields["Delimiter"].Value;
 }
        private void InitializeMinimumAndMaximumValues(BaseDataMap map, Item i)
        {
            const string mustBeEqualToOrHigherThanFieldName = "Must Be Equal To or Higher Than";
            const string mustBeEqualToOrLowerThanFieldName = "Must Be Equal To or Lower Than";
            if (!string.IsNullOrEmpty(i[mustBeEqualToOrHigherThanFieldName]))
            {
                int mustBeEqualToOrHigherThan;
                if (int.TryParse(i[mustBeEqualToOrHigherThanFieldName], out mustBeEqualToOrHigherThan))
                {
                    MustBeEqualToOrHigherThan = mustBeEqualToOrHigherThan;
                }
                else
                {
                    map.LogBuilder.Log("Error", String.Format("The value for 'Must Be Equal To or Higher Than' could not be parsed. value:{0}", mustBeEqualToOrHigherThan));
                }

            }
            if (!string.IsNullOrEmpty(i[mustBeEqualToOrLowerThanFieldName]))
            {
                int mustBeEqualToOrLowerThan;
                if (int.TryParse(i[mustBeEqualToOrLowerThanFieldName], out mustBeEqualToOrLowerThan))
                {
                    MustBeEqualToOrLowerThan = mustBeEqualToOrLowerThan;
                }
                else
                {
                    map.LogBuilder.Log("Error", String.Format("The value for 'Must Be Equal To or Lower Than' could not be parsed. value:{0}", mustBeEqualToOrLowerThan));
                }

            }
        }
 public ToGuidFromListValueMatchOnFieldNameFieldField(BaseDataMap map, Item fieldItem)
     : base(map, fieldItem)
 {
     // Stores the Match On FieldName
     MatchOnFieldName = fieldItem.Fields["Match On FieldName"].Value;
     if (String.IsNullOrEmpty(MatchOnFieldName))
     {
         throw new InvalidValueException(String.Format("The 'MatchOnFieldName' was not provided. Therefor it wasn't possible to match the importValue with a sourcelist. ItemId: {0}.", fieldItem.ID));
     }
 }
 public ToGuidFromListValueMatchOnDisplayNameField(BaseDataMap map, Item fieldItem)
     : base(map, fieldItem)
 {
     //stores the source list value
     SourceList = fieldItem.Fields["Source List"].Value;
     if (String.IsNullOrEmpty(SourceList))
     {
         throw new InvalidValueException(String.Format("The 'Source List' was not provided. Therefore it wasn't possible to match the importValue with a sourcelist. ItemId: {0}.", fieldItem.ID));
     }
     DoNotRequireValueMatch = fieldItem.Fields["Do Not Require Value Match"].Value == "1";
 }
 private void InitializeEmailValidationRegex(BaseDataMap map, Item i)
 {
     try
     {
         var emailValidationRegex = i.Fields["Email Validation Regex"].Value;
         EmailValidationRegex = emailValidationRegex;
     }
     catch (Exception ex)
     {
         map.LogBuilder.Log("Error",String.Format("The value for email validation regex was not provided or the value could not be parsed. Exception:{0}",map.GetExceptionDebugInfo(ex)));
         EmailValidationRegex = @"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,4})$";
     }
 }
        public BaseMapping(BaseDataMap map, Item fieldItem)
        {
            Map = map;
            FieldItem = fieldItem;
            NewItemField = fieldItem.Fields["To What Field"].Value;

            HandlerClass = fieldItem.Fields["Handler Class"].Value;
            HandlerAssembly = fieldItem.Fields["Handler Assembly"].Value;
            IsRequiredOnImportRow = fieldItem.Fields["Is Required On ImportRow"].Value == "1";
            IsRequiredOnUser = fieldItem.Fields["Is Required On User"].Value == "1";

            InitializeFieldStorageHandlerField(map, fieldItem);
        }
 private bool IsValidNumber(string importValue, BaseDataMap map)
 {
     int importValueAsInteger;
     if (!int.TryParse(importValue, out importValueAsInteger))
     {
         map.LogBuilder.Log("Error", String.Format("The value '{0}' could not be parsed as an integer.", importValue));
         return false;
     }
     if (importValueAsInteger >= MustBeEqualToOrHigherThan &&
         importValueAsInteger <= MustBeEqualToOrLowerThan)
     {
         return true;
     }
     map.LogBuilder.Log("Error", String.Format("The value '{0}' was either higher than or lower than the allowed range min:'{1}' max:{2} .", importValue, MustBeEqualToOrHigherThan, MustBeEqualToOrHigherThan));
     return false;
 }
 public ToDateField(BaseDataMap map, Item fieldItem)
     : base(map, fieldItem)
 {
     FromWhatDateTimeFormat = fieldItem.Fields[FieldNameFromWhatDateTimeFormat].Value;
     if (String.IsNullOrEmpty(FromWhatDateTimeFormat))
     {
         map.LogBuilder.Log("Error",
                               String.Format("The field '{0}' didn't contain any value. A string value must be provided for the DateTime format to parse the given date from. " +
                                             "FieldValue: {1}. The fieldItem: {2}.", FieldNameFromWhatDateTimeFormat, FromWhatDateTimeFormat, map.GetItemDebugInfo(fieldItem)));
     }
     ToWhatDateTimeFormat = fieldItem.Fields[FieldNameToWhatDateTimeFormat].Value;
     if (String.IsNullOrEmpty(ToWhatDateTimeFormat))
     {
         map.LogBuilder.Log("Error",
                               String.Format("The field '{0}' didn't contain any value. A string value must be provided for the DateTime format to parse the given date from. " +
                                             "FieldValue: {1}. The fieldItem: {2}.", FieldNameToWhatDateTimeFormat, ToWhatDateTimeFormat, map.GetItemDebugInfo(fieldItem)));
     }
 }
        public override string FillField(BaseDataMap map, object importRow, ref User user, string fieldName, string importValue, bool isRequiredOnUser,
            out bool updatedField)
        {
            updatedField = false;

            string errorMessage = String.Empty;
            var users = UserKeyStorage.GetUsersFromKey(fieldName, importValue, ref errorMessage);
            if (!String.IsNullOrEmpty(errorMessage))
            {
                return String.Format(
                                    "An error occured in the GetUsersFromKey method in the FillField method in trying to retrieve the users from key. ErrorMessage: {1}. " +
                                    "User '{2}'. FieldName: {0}. ImportValue: {3}.",
                                    fieldName, errorMessage, map.GetUserDebugInfo(user), importValue);
            }
            if (users.Count > 1)
            {
                return String.Format(
                                    "Duplicate values where found in the column '{0}' in the Users table in the .NET membership database. The value must be unique. ErrorMessage: {1}. " +
                                    "User '{2}'. FieldName: {0}. ImportValue: {3}.",
                                    fieldName, errorMessage, map.GetUserDebugInfo(user), importValue);
            }
            if (users.Count == 1)
            {
                if (users.First().LocalName != user.LocalName)
                {
                    return String.Format(
                                    "A key with the same value in column '{0}' was found on another user in the Users table in the .NET membership database. The value must be unique. " +
                                    "ErrorMessage: {1}. Found on user: {2}. Current user '{3}'. FieldName: {0}. ImportValue: {4}.",
                                    fieldName, errorMessage, map.GetUserDebugInfo(users.First()), map.GetUserDebugInfo(user), importValue);
                }
            }

            var result = UserKeyStorage.UpdateKeyValueToDotnetMemberShipProviderDatabase(fieldName, importValue, user.Domain.GetFullName(user.LocalName), ref errorMessage);
            if (!String.IsNullOrEmpty(errorMessage))
            {
                return String.Format(
                                    "The update of column '{0}' in the Users table in the .NET membership database failed of the following reason: {1}. " +
                                    "User '{2}'. FieldName: {0}. ImportValue: {3}.",
                                    fieldName, errorMessage, map.GetUserDebugInfo(user), importValue);
            }
            updatedField = result == 1;
            return string.Empty;
        }
        public override string FillField(BaseDataMap map, object importRow, ref User user, string fieldName, string importValue, bool isRequiredOnUser,
            out bool updatedField)
        {
            updatedField = false;

            var profile = user.Profile;
            if (profile != null)
            {
                var propertyInfo = Sitecore.Reflection.ReflectionUtil.GetPropertyInfo(profile, fieldName);
                if (propertyInfo != null)
                {
                    if (propertyInfo.PropertyType == typeof (string) || propertyInfo.PropertyType == typeof (String))
                    {
                        var existingValue = propertyInfo.GetValue(profile, null) as string;
                        if (existingValue != importValue)
                        {
                            Sitecore.Reflection.ReflectionUtil.SetProperty(profile, propertyInfo, importValue);
                            updatedField = true;
                        }
                    }
                    else
                    {
                        return String.Format("The property on the User.Profile was not of type string. Therefore the field could not be filled. PropertyType: {0}. User '{1}'. FieldName: {2}. ImportValue: {3}.", propertyInfo.PropertyType, map.GetUserDebugInfo(user), fieldName, importValue);
                    }
                }
                else
                {
                    if (CheckThatPropertyExist)
                    {
                        return
                            String.Format(
                                "The profile did not contain a property as defined in fieldName. This field must be found on the user because the 'isRequired' value is set. User '{0}'. FieldName: {1}. ImportValue: {2}.",
                                map.GetUserDebugInfo(user), fieldName, importValue);
                    }
                }
            }
            else
            {
                return String.Format("The profile was null on the user '{0}' while processing the fieldName: {1}, with importValue: {2}.", map.GetUserDebugInfo(user), fieldName, importValue);
            }
            return string.Empty;
        }
        public ToBooleanField(BaseDataMap map, Item fieldItem)
            : base(map, fieldItem)
        {
            WhatStringToIdentifyTrueBoolValue = fieldItem.Fields[FieldNameWhatStringToIdentifyTrueBoolValue].Value;
            if (String.IsNullOrEmpty(WhatStringToIdentifyTrueBoolValue))
            {
                map.LogBuilder.Log("Error",
                                      string.Format("The field '{0}' didn't contain any value. A string value must be provided to identify the bool value. " +
                                                    "FieldValue: {1}. The fieldItem: {2}.", FieldNameWhatStringToIdentifyTrueBoolValue, WhatStringToIdentifyTrueBoolValue, map.GetItemDebugInfo(fieldItem)));

            }
            WhatStringToIdentifyFalseBoolValue = fieldItem.Fields[FieldNameWhatStringToIdentifyFalseBoolValue].Value;
            if (String.IsNullOrEmpty(WhatStringToIdentifyFalseBoolValue))
            {
                map.LogBuilder.Log("Error",
                                      string.Format("The field '{0}' didn't contain any value. A string value must be provided to identify the bool value. " +
                                                    "FieldValue: {1}. The fieldItem: {2}.", FieldNameWhatStringToIdentifyFalseBoolValue, WhatStringToIdentifyFalseBoolValue, map.GetItemDebugInfo(fieldItem)));

            }
        }
 public override string FillField(BaseDataMap map, object importRow, ref User user, string fieldName, string importValue, bool isRequiredOnUser,
     out bool updatedField)
 {
     updatedField = false;
     var profile = user.Profile;
     if (profile != null)
     {
         if (CheckThatPropertyExist)
         {
             var customPropertiesNames = profile.GetCustomPropertyNames();
             if (customPropertiesNames != null)
             {
                 if (!customPropertiesNames.Contains(fieldName))
                 {
                     return String.Format(
                             "The profile does not contain a Custom Property as defined in fieldName. " +
                             "User '{0}'. FieldName: {1}. ImportValue: {2}.",
                             map.GetUserDebugInfo(user), fieldName, importValue);
                 }
             }
             else
             {
                 return String.Format("The profile.GetCustomPropertyNames() returned null. Therefore the custom property could not be verified if it exists. User '{0}'. FieldName: {1}. ImportValue: {2}.", map.GetUserDebugInfo(user), fieldName, importValue);
             }
         }
         var existingValue = profile.GetCustomProperty(fieldName);
         if (existingValue != importValue)
         {
             profile.SetCustomProperty(fieldName, importValue);
             updatedField = true;
         }
     }
     else
     {
         return String.Format("The profile was null on the user '{0}' while processing the fieldName: {1}, with importValue: {2}.", map.GetUserDebugInfo(user), fieldName, importValue);
     }
     return string.Empty;
 }
 public override string FillField(BaseDataMap map, object importRow, ref Security.Accounts.User user, string importValue, out bool updatedField)
 {
     updatedField = false;
     if (!String.IsNullOrEmpty(importValue) || IsRequiredOnImportRow)
     {
         if (IsValidEmail(importValue))
         {
             var statusMessage = base.FillField(map, importRow, ref user, importValue, out updatedField);
             if (!String.IsNullOrEmpty(statusMessage))
             {
                 return
                     String.Format(
                         "An error occured trying to fill the field with a value. The field was not updated. See error log: '{0}'.",
                         statusMessage);
             }
         }
         else
         {
             return String.Format("The value '{0}' is not a valid email. This is required since the 'Is Required On ImportRow' was true for this field. The field was not updated.", importValue);
         }
     }
     return String.Empty;
 }
        private BaseFieldStorageHandler CreateFieldStorageHandler(BaseDataMap map, Item fieldStorageHandlerItem, out string errorMessage)
        {
            errorMessage = string.Empty;
            if (fieldStorageHandlerItem!=null)
            {
                var handlerClass = fieldStorageHandlerItem.Fields["Handler Class"].Value;
                var handlerAssembly = fieldStorageHandlerItem.Fields["Handler Assembly"].Value;

                if (!string.IsNullOrEmpty(handlerClass))
                {
                    //create the object from the class and cast as IFieldStorageHandler
                    try
                    {
                        var storageHandler = (BaseFieldStorageHandler)Reflection.ReflectionUtil.CreateObject(handlerAssembly, handlerClass, new object[] { map.CheckThatCustomPropertyExistOnUserProfile });
                        if (storageHandler != null)
                        {
                            return storageHandler;
                        }
                        errorMessage += string.Format("The field: '{0}' class type '{1}' could not be instantiated",
                                            fieldStorageHandlerItem.Name, handlerClass);
                    }
                    catch (FileNotFoundException fnfe)
                    {
                        errorMessage += string.Format("The field: {0} binary '{1}' specified could not be found. Exception: {1}", fieldStorageHandlerItem.Name, handlerAssembly, fnfe.Message);
                    }
                }
                else
                {
                    errorMessage += String.Format("the field: '{0}' Handler Class {1} is not defined", fieldStorageHandlerItem.Name,
                                      handlerClass);
                }
            }
            else
            {
                errorMessage += String.Format("The fieldStorageHandlerItem is null. Therefore the FieldStorageHandler could not be instantiated.");
            }
            return null;
        }
 public MobileAliasUserKeyHandler(BaseDataMap map, IBaseField fieldDefinition)
     : base(map, fieldDefinition)
 {
     UserKeyStorage = new MobileAliasUserKeyStorage();
 }
 public MobileAliasUserKeyHandler(BaseDataMap map)
     : base(map)
 {
     UserKeyStorage = new MobileAliasUserKeyStorage();
 }
 public virtual string FillField(BaseDataMap map, object importRow, ref User user, string importValue, out bool updatedField)
 {
     updatedField = false;
     if (IsRequiredOnImportRow)
     {
         if (String.IsNullOrEmpty(importValue))
         {
             return String.Format("The imported value '{0}' was empty. This field must be provided when the field is marked as required on import row. " +
                                  "The field was not updated. User: {1}. ImportRow: {2}. FieldName: {3}.", importValue, map.GetUserDebugInfo(user), map.GetImportRowDebugInfo(importRow), NewItemField);
         }
     }
     if (FieldStorageHandler != null)
     {
         string errorMessage = String.Empty;
         var processedImportValue = ProcessImportedValue(importValue, ref errorMessage);
         if (!String.IsNullOrEmpty(errorMessage))
         {
             return String.Format("The processedImportValue '{0}' resulted in an error. The field was not updated. ErrorMessage: {1}. " +
                                  "User: {2}. ImportRow: {3}. FieldName: {4}. ImportValue: {5}.", processedImportValue, errorMessage, map.GetUserDebugInfo(user), map.GetImportRowDebugInfo(importRow), NewItemField, importValue);
         }
         if (IsRequiredOnUser)
         {
             if (String.IsNullOrEmpty(processedImportValue))
             {
                 return String.Format("The processedImportValue '{0}' was empty or null. This field cannot be empty or null when the field is marked as required on the user. " +
                                      "The field was not updated. User: {1}. ImportRow: {2}. FieldName: {3}. ImportValue: {4}.", processedImportValue, map.GetUserDebugInfo(user), map.GetImportRowDebugInfo(importRow), NewItemField, importValue);
             }
         }
         var statusMessage = FieldStorageHandler.FillField(map, importRow, ref user, NewItemField, processedImportValue, IsRequiredOnUser, out updatedField);
         if (!String.IsNullOrEmpty(statusMessage))
         {
             return String.Format("An error occured trying to fill the field with a value. The field was not updated. See error log: '{0}'.", statusMessage);
         }
     }
     else
     {
         return String.Format("The FillField failed because the FieldStorageHandler object was null. User: {0}. NewItemField: {1}. ImportValue: {2}.", map.GetUserDebugInfo(user), NewItemField, importValue);
     }
     return String.Empty;
 }
        protected void Run(BaseDataMap map, Logging logBuilder)
        {
            Context.Job.Status.State = JobState.Running;

            var startedAt = DateTime.Now.ToLongDateString();
            map.Process();
            var finishededAt = DateTime.Now.ToLongDateString();
            try
            {
                MailManager.SendLogReport(ref logBuilder,
                                          GetUserSyncIdentifier(map.ImportItem),
                                          map.ImportItem);
            }
            catch (Exception exception)
            {
                Log.Error(
                    GetIdentifierText(map.ImportItem, startedAt, finishededAt) +
                    " failed in sending out the mail. Please see the exception message for more details. Exception:" + exception.Message + ". Status:\r\n" +
                    logBuilder.GetStatusText(), typeof(UserSyncTask));
            }
            var logString = logBuilder.LogBuilder.ToString();
            if (!String.IsNullOrEmpty(logString))
            {
                Context.Job.Status.Failed = true;
            }
            else
            {
                Context.Job.Status.State = JobState.Finished;
            }
        }
 public ToEmailField(BaseDataMap map, Item fieldItem)
     : base(map, fieldItem)
 {
     InitializeSaveEmailAsLowerCase(map,fieldItem);
     InitializeEmailValidationRegex(map,fieldItem);
 }
 public ToRoleMembership(BaseDataMap map, Item fieldItem)
     : base(map, fieldItem)
 {
     RoleName = fieldItem["To What Field"];
     TrueValue = fieldItem["True Value"];
 }
 private void InitializeFieldStorageHandlerField(BaseDataMap map, Item fieldItem)
 {
     var fieldStorageHandlerId = fieldItem.Fields[FieldNameFieldStorageHandler].Value;
     if (!String.IsNullOrEmpty(fieldStorageHandlerId))
     {
         if (Data.ID.IsID(fieldStorageHandlerId))
         {
             Item fieldStorageHandlerItem = map.SitecoreDB.GetItem(fieldStorageHandlerId);
             string errorMessage;
             var storageHandler = CreateFieldStorageHandler(map, fieldStorageHandlerItem, out errorMessage);
             if (!String.IsNullOrEmpty(errorMessage))
             {
                 map.LogBuilder.Log("Error",
                                string.Format("The field '{0}' had a correct Sitecore ID, but the instantiation of the object failed. See the error log: {1}. " +
                                              "FieldValue: {2}. The fieldItem: {3}.", FieldNameFieldStorageHandler, errorMessage, fieldStorageHandlerId, map.GetItemDebugInfo(fieldItem)));
             }
             if (storageHandler != null)
             {
                 FieldStorageHandler = storageHandler;
             }
             else
             {
                 map.LogBuilder.Log("Error",
                                string.Format("The field '{0}' had a correct Sitecore ID, but the object was null." +
                                              "FieldValue: {1}. The fieldItem: {2}.", FieldNameFieldStorageHandler, fieldStorageHandlerId, map.GetItemDebugInfo(fieldItem)));
             }
         }
         else
         {
             map.LogBuilder.Log("Error",
                                string.Format("The field '{0}' had a value, but it was not a correct Sitecore ID. Please provide a correct Sitecore ID for the field to define which FieldStorageHandler should handle the saving of the field to user in the Sitecore Membership Database. " +
                                              "FieldValue: {1}. The fieldItem: {2}.", FieldNameFieldStorageHandler, fieldStorageHandlerId, map.GetItemDebugInfo(fieldItem)));
         }
     }
     else
     {
         map.LogBuilder.Log("Error",
                            string.Format("The field '{0}' was null or empty. Please provide a value for the field to define which FieldStorageHandler should handle the saving of the field to user in the Sitecore Membership Database. " +
                                          "The fieldItem: {1}.", FieldNameFieldStorageHandler, map.GetItemDebugInfo(fieldItem)));
     }
 }
 public UserNameAsKeyHandler(BaseDataMap map)
     : base(map)
 {
 }
 protected BaseUserKeyHandler(BaseDataMap map, IBaseField fieldDefinition)
 {
     Map = map;
     FieldDefinition = fieldDefinition;
 }
 public abstract string FillField(BaseDataMap map, object importRow, ref User user, string fieldName,
     string importValue, bool isRequired,
     out bool updatedField);
 public ToNumberField(BaseDataMap map, Item fieldItem)
     : base(map, fieldItem)
 {
     InitializeMinimumAndMaximumValues(map,fieldItem);
 }
 protected BaseUserKeyHandler(BaseDataMap map)
 {
     Map = map;
 }