public SqlDataMap(Database db, Item importItem, Logging logging)
     : base(db, importItem, logging)
 {
     if (string.IsNullOrEmpty(Query))
     {
         LogBuilder.Log("Error", "the 'Query' field was not set");
     }
 }
 public CSVDataMap(Database db, Item importItem, Logging logging, string data)
     : base(db, importItem, logging)
 {
     Data = data;
     HeaderColumns = new Dictionary<string, int>();
     ImportData = new List<object>();
     InitializeColumnDelimiterCharacter(importItem);
 }
        public static void SendLogReport(ref Logging log, string identifier, Item userSyncItem)
        {
            var recipient = userSyncItem["Mail Recipients"];
            if (String.IsNullOrEmpty(recipient))
            {
                log.Log("Error", "The 'Mail Recipients' field must be defined. Please provide a recipient address for the mail.");
            }
            else
            {
                var replyTo = userSyncItem["Mail Reply To"];
                if (String.IsNullOrEmpty(replyTo))
                {
                    replyTo = "*****@*****.**";
                    log.Log("Error", "The 'Mail Reply To' field must be defined. Please provide a replyTo address for the mail.");
                }
                var subject = userSyncItem["Mail Subject"];
                if (String.IsNullOrEmpty(subject))
                {
                    subject = "Status report mail from UserSync task - {0} - Result: {1}.";
                }

                var logString = log.LogBuilder.ToString();
                var result = string.Empty;
                if (String.IsNullOrEmpty(logString))
                {
                    result = Success;
                    logString += "The import completed successfully.\r\n\r\nStatus:\r\n" + log.GetStatusText();
                }
                else
                {
                    logString = "The import failed.\r\n\r\nStatus:\r\n" + log.GetStatusText() + "\r\n\r\n" + logString;
                    result = Failure;
                }
                try
                {
                    subject = String.Format(subject, identifier, result);
                }
                catch (Exception exception)
                {
                    log.Log("Error", "SendLogReport had an exception trying to format the subject of the mail." + exception.Message);
                }
                var doNotSendMailOnSuccess = userSyncItem["Do Not Send Mail On Success"] == "1";
                if((doNotSendMailOnSuccess && result == Failure) || !doNotSendMailOnSuccess)
                {
                    try{
                        if (SendMail.SendMailWithoutAttachment(recipient, replyTo, subject, logString) == "Failure")
                        {
                            log.Log("Error", "The SendMailWithoutAttachment failed.");
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Log("Error", "The SendMailWithoutAttachment failed with an exception: " + ex.Message + " " + ex.StackTrace);
                    }
                }
            }
        }
        public Logging RunUserSyncJob(Item userSyncItem, ref Logging LogBuilder)
        {
            string errorMessage = String.Empty;

            var map = InstantiateDataMap(userSyncItem, ref errorMessage);
            if (!String.IsNullOrEmpty(errorMessage))
            {
                LogBuilder.Log("Error", errorMessage);
            }
            if (map != null)
            {
                map.Process();
            }
            return LogBuilder;
        }
        public BaseDataMap InstantiateDataMap(Item userSyncItem, ref string errorMessage)
        {
            Database currentDB = Configuration.Factory.GetDatabase("master");

            string handlerAssembly = userSyncItem["Handler Assembly"];
            string handlerClass = userSyncItem["Handler Class"];
            var logBuilder = new Logging();

            if (!String.IsNullOrEmpty(handlerAssembly))
            {
                if (!String.IsNullOrEmpty(handlerClass))
                {
                    BaseDataMap map = null;
                    try
                    {
                        map = (BaseDataMap)Reflection.ReflectionUtil.CreateObject(handlerAssembly, handlerClass, new object[] { currentDB, userSyncItem, logBuilder });
                    }
                    catch (FileNotFoundException fnfe)
                    {
                        errorMessage += "The binary specified could not be found" + fnfe.Message;
                    }
                    if (map != null)
                    {
                        return map;
                    }
                    errorMessage += String.Format("The data map provided could not be instantiated. Assembly:'{0}' Class:'{1}'", handlerAssembly, handlerClass);
                }
                else
                {
                    errorMessage += "Import handler class is not defined";
                }
            }
            else
            {
                errorMessage += "import handler assembly is not defined";
            }
            return null;
        }
 public void RunJob(Item[] itemArray, CommandItem commandItem, ScheduleItem scheduledItem)
 {
     try
     {
         if (scheduledItem != null)
         {
             var itemIds = scheduledItem["Items"];
             if (!String.IsNullOrEmpty(itemIds))
             {
                 var idList = itemIds.Split('|');
                 if (idList.Any())
                 {
                     foreach (var id in idList)
                     {
                         if (ID.IsID(id))
                         {
                             var userSyncItem = scheduledItem.Database.GetItem(new ID(id));
                             try
                             {
                                 if (userSyncItem != null)
                                 {
                                     var startedAt = DateTime.Now.ToLongDateString();
                                     Logging logBuilder = new Logging();
                                     var userSyncManager = new UserSyncManager();
                                     userSyncManager.RunUserSyncJob(userSyncItem, ref logBuilder);
                                     var finishededAt = DateTime.Now.ToLongDateString();
                                     if (logBuilder != null)
                                     {
                                         try
                                         {
                                             MailManager.SendLogReport(ref logBuilder,
                                                                       GetUserSyncIdentifier(userSyncItem),
                                                                       userSyncItem);
                                         }
                                         catch (Exception exception)
                                         {
                                             Diagnostics.Log.Error(
                                                 GetIdentifierText(userSyncItem, 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));
                                         }
                                         if (logBuilder.LogBuilder != null)
                                         {
                                             if (!String.IsNullOrEmpty(logBuilder.LogBuilder.ToString()))
                                             {
                                                 Diagnostics.Log.Error(
                                                     GetIdentifierText(userSyncItem, startedAt, finishededAt) +
                                                     " failed. " +
                                                     logBuilder.LogBuilder + "\r\nStatus:\r\n" +
                                                     logBuilder.GetStatusText(),
                                                     typeof(UserSyncTask));
                                             }
                                             else
                                             {
                                                 Diagnostics.Log.Debug(
                                                     GetIdentifierText(userSyncItem, startedAt, finishededAt) +
                                                     " completed with success.\r\nStatus:\r\n" +
                                                     logBuilder.GetStatusText(),
                                                     typeof(UserSyncTask));
                                             }
                                         }
                                         else
                                         {
                                             Diagnostics.Log.Error(
                                                    GetIdentifierText(userSyncItem, startedAt, finishededAt) +
                                                    " failed. The Logging.LogBuilder object was null. " +
                                                    logBuilder + "\r\nStatus:\r\n" +
                                                    logBuilder.GetStatusText(),
                                                    typeof(UserSyncTask));
                                         }
                                     }
                                     else
                                     {
                                         Diagnostics.Log.Error(
                                             GetIdentifierText(userSyncItem, startedAt, finishededAt) +
                                             " - The Log object was null. This should not happen.",
                                             typeof(UserSyncTask));
                                     }
                                 }
                                 else
                                 {
                                     Diagnostics.Log.Error(
                                         " - The Task item had Items defined in Items[] that was null. This should not happen.",
                                         typeof(UserSyncTask));
                                 }
                             }
                             catch (Exception exception)
                             {
                                 var itemId = userSyncItem != null ? userSyncItem.ID.ToString() : string.Empty;
                                 Diagnostics.Log.Error(
                                     Identifier +
                                     String.Format(
                                         " - An exception occured in the execution of the task in the foreach (Item UserSyncItem in itemArray) of the UserSync item: {0}. This UserSync job wasn't completed. Exception: {1}",
                                         itemId, exception.Message), typeof(UserSyncTask));
                             }
                         }
                         else
                         {
                             Diagnostics.Log.Error(
                             Identifier +
                             " - The provided value wasn't a correct Sitecore id. Please add at least one id to 'Items' field of the ScheduledItem. You can also use | to seperate ids. Therefore nothing was done.",
                             typeof(UserSyncTask));
                         }
                     }
                 }
                 else
                 {
                     Diagnostics.Log.Error(
                         Identifier +
                         " - There wasn't defined any UserSync items to run. Please add at least one id to 'Items' field of the ScheduledItem. You can also use | to seperate ids. Therefore nothing was done.",
                         typeof(UserSyncTask));
                 }
             }
             else
             {
                 Diagnostics.Log.Error(
                     Identifier + " - There wasn't defined any UserSync items to run. Therefore nothing was done.",
                     typeof(UserSyncTask));
             }
         }
         else
         {
             Diagnostics.Log.Error(
                     Identifier + " - The ScheduledItem was null. Therefore nothing was done.",
                     typeof(UserSyncTask));
         }
     }
     catch (Exception exception)
     {
         Diagnostics.Log.Error(Identifier + " - An exception occured in the execution of the task.", exception);
     }
 }
 private string GetStatusText(Item userSyncItem, Logging logBuilder, string startedAt, string finishedAt)
 {
     if (logBuilder != null)
     {
         if (logBuilder.LogBuilder != null)
         {
             var logString = logBuilder.LogBuilder.ToString();
             if (String.IsNullOrEmpty(logString))
             {
                 logString += "The import completed successfully.\r\n\r\nStatus:\r\n" +
                              logBuilder.GetStatusText();
             }
             else
             {
                 logString = "The import failed.\r\n\r\nStatus:\r\n" + logBuilder.GetStatusText() + "\r\n\r\n" +
                             logString;
             }
             return logString;
         }
         return GetIdentifierText(userSyncItem, startedAt, finishedAt) + " failed. The Logging.LogBuilder object was null. " + logBuilder + "\r\nStatus:\r\n" + logBuilder.GetStatusText();
     }
     return GetIdentifierText(userSyncItem, startedAt, finishedAt) + " - The Log object was null. This should not happen.";
 }
        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 CSVFileDataMap(Database db, Item importItem, Logging logging)
     : base(db, importItem, logging)
 {
     Data = CsvFileData;
 }
        protected BaseDataMap(Database db, Item importItem, Logging logging)
        {
            ImportItem = importItem;
            LogBuilder = logging;

            //setup import details
            SitecoreDB = db;
            // Defines the data and datasource for the import
            DataSourceString = importItem["Data Source"];
            Query = importItem["Query"];

            Int32.TryParse(importItem["Minimum Number Of Rows Required To Run The Import"],
                           out _MinimumNumberOfRowsRequiredToRunTheImport);
            if (MinimumNumberOfRowsRequiredToRunTheImport < 0)
            {
                MinimumNumberOfRowsRequiredToRunTheImport = 0;
            }
            IsValidateImportDataBeforeProcessing = importItem["Validate Import Data Before Processing"] == "1";
            IsInValidationAllowDuplicatesInKey = importItem["In Validation Allow Duplicates In Key"] == "1";

            int limitNumberOfImportRowsToWhatNumber;
            if (Int32.TryParse(importItem["Limit Number Of ImportRows To What Number"],
                               out limitNumberOfImportRowsToWhatNumber))
            {
                LimitNumberOfImportRowsToWhatNumber = limitNumberOfImportRowsToWhatNumber;
            }
            else
            {
                LimitNumberOfImportRowsToWhatNumber = 0;
            }
            if (LimitNumberOfImportRowsToWhatNumber < 0)
            {
                LimitNumberOfImportRowsToWhatNumber = 0;
            }

            int startOnWhatImportRowIndex;
            if (Int32.TryParse(importItem["Start On What ImportRow Index"],
                               out startOnWhatImportRowIndex))
            {
                StartOnWhatImportRowIndex = startOnWhatImportRowIndex;
            }
            else
            {
                StartOnWhatImportRowIndex = 0;
            }
            if (StartOnWhatImportRowIndex < 0)
            {
                StartOnWhatImportRowIndex = 0;
            }

            //more properties
            GetUsernameFromWhatField = importItem.Fields["Get Username From What Field"].Value;
            if (String.IsNullOrEmpty(GetUsernameFromWhatField))
            {
                LogBuilder.Log("Error",
                               String.Format(
                                   "The field '{0}' must contain a value that indicates which field to retrieve the username from.",
                                   "Get Username From What Field"));
            }

            InitializeIdentifyUserUniqueByFieldDefinition(importItem);

            InitializeUserKeyHandler();

            var createUserInWhatSecurityDomainString = importItem.Fields[FieldCreateUserInWhatSecurityDomain].Value;
            if (!String.IsNullOrEmpty(createUserInWhatSecurityDomainString))
            {
                if (DomainManager.DomainExists(createUserInWhatSecurityDomainString))
                {
                    var createUserInWhatSecurityDomain = DomainManager.GetDomain(createUserInWhatSecurityDomainString);
                    if (createUserInWhatSecurityDomain != null)
                    {
                        CreateUserInWhatSecurityDomain = createUserInWhatSecurityDomain;
                    }
                    else
                    {
                        LogBuilder.Log("Error",
                                       String.Format(
                                           "The initialization of the property CreateUserInWhatSecurityDomain failed. The security domain created was null. The field: '{0}' contains the value  '{1}'.",
                                           FieldCreateUserInWhatSecurityDomain, createUserInWhatSecurityDomainString));
                    }
                }
                else
                {
                    LogBuilder.Log("Error",
                                   String.Format(
                                       "The initialization of the property CreateUserInWhatSecurityDomain failed. The security domain provided does not exist. The field: '{0}' contains the value '{1}'.",
                                       FieldCreateUserInWhatSecurityDomain, createUserInWhatSecurityDomainString));
                }
            }
            else
            {
                LogBuilder.Log("Error",
                               String.Format(
                                   "The initialization of the property CreateUserInWhatSecurityDomain failed. The value provided in the field: '{0}' was null or empty. Value: '{1}'.",
                                   FieldCreateUserInWhatSecurityDomain, createUserInWhatSecurityDomainString));
            }

            string addUserToWhatStandardRoles = importItem.Fields[FieldAddUserToWhatStandardRoles].Value;
            string errorMessage;
            AddUserToWhatStandardRoles = InitializeRolesListFromPipeseperatedString(FieldAddUserToWhatStandardRoles,
                                                                                    addUserToWhatStandardRoles,
                                                                                    out errorMessage);
            if (!String.IsNullOrEmpty(errorMessage))
            {
                LogBuilder.Log("Error", errorMessage);
            }

            GetPasswordFromWhatField = importItem.Fields["Get Password From What Field"].Value;
            AutogeneratePasswordWithLength = 7;
            var autogeneratePasswordWithLength = importItem.Fields["Autogenerate Password With Length"].Value;
            if (!String.IsNullOrEmpty(autogeneratePasswordWithLength))
            {
                int length;
                if (!Int32.TryParse(autogeneratePasswordWithLength, out length))
                {
                    LogBuilder.Log("Error",
                                   String.Format(
                                       "The field '{0}' must contain a integer that states the length of the password. Value: {1}.",
                                       "Autogenerate Password With Length", autogeneratePasswordWithLength));
                }
                else
                {
                    AutogeneratePasswordWithLength = length;
                }
            }

            // Users Present In Import
            string onPresentInImportAddUserToRoles = importItem.Fields[FieldOnPresentInImportAddToRoles].Value;
            OnPresentInImportAddToRoles = InitializeRolesListFromPipeseperatedString(FieldOnPresentInImportAddToRoles,
                                                                                     onPresentInImportAddUserToRoles,
                                                                                     out errorMessage, true);
            if (!String.IsNullOrEmpty(errorMessage))
            {
                LogBuilder.Log("Error", errorMessage);
            }

            string onPresentInImportRemoveUserFromRoles = importItem.Fields[FieldOnPresentInImportRemoveFromRoles].Value;
            OnPresentInImportRemoveFromRoles =
                InitializeRolesListFromPipeseperatedString(FieldOnPresentInImportRemoveFromRoles,
                                                           onPresentInImportRemoveUserFromRoles, out errorMessage);
            if (!String.IsNullOrEmpty(errorMessage))
            {
                LogBuilder.Log("Error", errorMessage);
            }

            // Users Not Present In Import
            IsProcessUsersNotPresentInImport = importItem["Process Users Not Present In Import"] == "1";

            string onNotPresentInImportAddToRoles = importItem.Fields[FieldOnNotPresentInImportAddToRoles].Value;
            OnNotPresentInImportAddToRoles =
                InitializeRolesListFromPipeseperatedString(FieldOnNotPresentInImportAddToRoles,
                                                           onNotPresentInImportAddToRoles, out errorMessage);
            if (!String.IsNullOrEmpty(errorMessage))
            {
                LogBuilder.Log("Error", errorMessage);
            }

            string onNotPresentInImportRemoveFromRoles =
                importItem.Fields[FieldOnNotPresentInImportRemoveFromRoles].Value;
            OnNotPresentInImportRemoveFromRoles =
                InitializeRolesListFromPipeseperatedString(FieldOnNotPresentInImportRemoveFromRoles,
                                                           onNotPresentInImportRemoveFromRoles, out errorMessage);
            if (!String.IsNullOrEmpty(errorMessage))
            {
                LogBuilder.Log("Error", errorMessage);
            }

            IsDoNotLogProgressStatusMessagesInSitecoreLog =
                importItem["Do Not Log Progress Status Messages In Sitecore Log"] == "1";

            SetProfileItemOnUser = importItem["Set ProfileItem On User"] == "1";
            UseWhatProfileItemId = importItem.Fields["Use What ProfileItemId"].Value;
            CheckThatCustomPropertyExistOnUserProfile = importItem["Check That Property Exist On User Profile"] == "1";

            IsDeleteUsersWithMembershipInStandardRolesOnly =
                importItem["Delete Users With Membership In Standard Roles Only"] == "1";

            //start handling fields
            Item fieldsRootItem = GetItemByTemplate(importItem, Utility.Constants.FieldsFolderID);
            if (fieldsRootItem.IsNotNull())
            {
                ChildList c = fieldsRootItem.GetChildren();
                if (c.Any())
                {
                    foreach (Item child in c)
                    {
                        var fieldDefinition = CreateFieldDefinition(child);
                        if (fieldDefinition != null)
                        {
                            FieldDefinitions.Add(fieldDefinition);
                        }
                    }
                }
                else
                {
                    LogBuilder.Log("Warn", "There are no fields to import");
                }
            }
            else
            {
                LogBuilder.Log("Warn", "There is no 'Fields' folder");
            }
        }