protected virtual string GetOptionalParameter(JobDataMap data, string propertyName)
        {
            string value = data.GetString(propertyName);

            if (string.IsNullOrEmpty(value))
            {
                return null;
            }

            return value;
        }
 protected virtual string GetRequiredParameter(JobDataMap data, string propertyName)
 {
     string value = data.GetString(propertyName);
     if (string.IsNullOrEmpty(value))
     {
         throw new ArgumentException(propertyName + " not specified.");
     }
     return value;
 }
 public ThresholdCalculationEmailSubsystem(JobDataMap jobDataMap)
     : this(GetEmailTemplateEngine(jobDataMap), GetEmailSender(), jobDataMap.GetString<SendEmailJobDataMap>(dataMap => dataMap.Name)) {
     _jobDataMap = jobDataMap;
 }
 static EmailTemplateEngine.EmailTemplateEngine GetEmailTemplateEngine(JobDataMap jobDataMap) {
     return new EmailTemplateEngine.EmailTemplateEngine(new StreamEmailTemplateContentReader(jobDataMap.GetString<SendEmailJobDataMap>(map => map.EmailTemplate)));
 }
        /// <summary>
        /// Purges the exception log.
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void PurgeExceptionLog( JobDataMap dataMap )
        {
            int? exceptionExpireDays = dataMap.GetString( "DaysKeepExceptions" ).AsIntegerOrNull();
            if ( exceptionExpireDays.HasValue )
            {
                var exceptionLogRockContext = new Rock.Data.RockContext();
                DateTime exceptionExpireDate = RockDateTime.Now.Add( new TimeSpan( exceptionExpireDays.Value * -1, 0, 0, 0 ) );

                // delete in chunks (see http://dba.stackexchange.com/questions/1750/methods-of-speeding-up-a-huge-delete-from-table-with-no-clauses)
                bool keepDeleting = true;
                while ( keepDeleting )
                {
                    var dbTransaction = exceptionLogRockContext.Database.BeginTransaction();
                    try
                    {
                        int rowsDeleted = exceptionLogRockContext.Database.ExecuteSqlCommand( @"DELETE TOP (1000) FROM [ExceptionLog] WHERE [CreatedDateTime] < @createdDateTime", new SqlParameter( "createdDateTime", exceptionExpireDate ) );
                        keepDeleting = rowsDeleted > 0;
                    }
                    finally
                    {
                        dbTransaction.Commit();
                    }
                }
            }
        }
        /// <summary>
        /// Cleanups the unconfirmed user logins that have not been confirmed in X hours
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void CleanupUnconfirmedUserLogins( JobDataMap dataMap )
        {
            int? userExpireHours = dataMap.GetString( "HoursKeepUnconfirmedAccounts" ).AsIntegerOrNull();
            if ( userExpireHours.HasValue )
            {
                var userLoginRockContext = new Rock.Data.RockContext();
                DateTime userAccountExpireDate = RockDateTime.Now.Add( new TimeSpan( userExpireHours.Value * -1, 0, 0 ) );

                // delete in chunks (see http://dba.stackexchange.com/questions/1750/methods-of-speeding-up-a-huge-delete-from-table-with-no-clauses)
                bool keepDeleting = true;
                while ( keepDeleting )
                {
                    var dbTransaction = userLoginRockContext.Database.BeginTransaction();
                    try
                    {
                        int rowsDeleted = userLoginRockContext.Database.ExecuteSqlCommand( @"DELETE TOP (1000) FROM [UserLogin] WHERE [IsConfirmed] = 0 AND ([CreatedDateTime] is null OR [CreatedDateTime] < @createdDateTime )", new SqlParameter( "createdDateTime", userAccountExpireDate ) );
                        keepDeleting = rowsDeleted > 0;
                    }
                    finally
                    {
                        dbTransaction.Commit();
                    }
                }
            }
        }
        /// <summary>
        /// Purges the audit log.
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void PurgeAuditLog( JobDataMap dataMap )
        {
            // purge audit log
            int? auditExpireDays = dataMap.GetString( "AuditLogExpirationDays" ).AsIntegerOrNull();
            if ( auditExpireDays.HasValue )
            {
                var auditLogRockContext = new Rock.Data.RockContext();
                DateTime auditExpireDate = RockDateTime.Now.Add( new TimeSpan( auditExpireDays.Value * -1, 0, 0, 0 ) );

                // delete in chunks (see http://dba.stackexchange.com/questions/1750/methods-of-speeding-up-a-huge-delete-from-table-with-no-clauses)
                bool keepDeleting = true;
                while ( keepDeleting )
                {
                    var dbTransaction = auditLogRockContext.Database.BeginTransaction();
                    try
                    {
                        int rowsDeleted = auditLogRockContext.Database.ExecuteSqlCommand( @"DELETE TOP (1000) FROM [Audit] WHERE [DateTime] < @auditExpireDate", new SqlParameter( "auditExpireDate", auditExpireDate ) );
                        keepDeleting = rowsDeleted > 0;
                    }
                    finally
                    {
                        dbTransaction.Commit();
                    }
                }

                auditLogRockContext.SaveChanges();
            }
        }
        /// <summary>
        /// Cleans the cached file directory.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="dataMap">The data map.</param>
        private void CleanCachedFileDirectory( IJobExecutionContext context, JobDataMap dataMap )
        {
            string cacheDirectoryPath = dataMap.GetString( "BaseCacheDirectory" );
            int? cacheExpirationDays = dataMap.GetString( "DaysKeepCachedFiles" ).AsIntegerOrNull();
            if ( cacheExpirationDays.HasValue )
            {
                DateTime cacheExpirationDate = RockDateTime.Now.Add( new TimeSpan( cacheExpirationDays.Value * -1, 0, 0, 0 ) );

                // if job is being run by the IIS scheduler and path is not null
                if ( context.Scheduler.SchedulerName == "RockSchedulerIIS" && !string.IsNullOrEmpty( cacheDirectoryPath ) )
                {
                    // get the physical path of the cache directory
                    cacheDirectoryPath = System.Web.Hosting.HostingEnvironment.MapPath( cacheDirectoryPath );
                }

                // if directory is not blank and cache expiration date not in the future
                if ( !string.IsNullOrEmpty( cacheDirectoryPath ) && cacheExpirationDate <= RockDateTime.Now )
                {
                    // Clean cache directory
                    CleanCacheDirectory( cacheDirectoryPath, cacheExpirationDate );
                }
            }
        }
        /// <summary>
        /// Does cleanup of Person Aliases and Metaphones
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void PersonCleanup( JobDataMap dataMap )
        {
            // Add any missing person aliases
            var personRockContext = new Rock.Data.RockContext();
            PersonService personService = new PersonService( personRockContext );
            foreach ( var person in personService.Queryable( "Aliases" )
                .Where( p => !p.Aliases.Any() )
                .Take( 300 ) )
            {
                person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } );
            }

            personRockContext.SaveChanges();

            // Add any missing metaphones
            int namesToProcess = dataMap.GetString( "MaxMetaphoneNames" ).AsInteger();
            if ( namesToProcess > 0 )
            {
                var firstNameQry = personService.Queryable().Select( p => p.FirstName ).Where( p => p != null );
                var nickNameQry = personService.Queryable().Select( p => p.NickName ).Where( p => p != null );
                var lastNameQry = personService.Queryable().Select( p => p.LastName ).Where( p => p != null );
                var nameQry = firstNameQry.Union( nickNameQry.Union( lastNameQry ) );

                var metaphones = personRockContext.Metaphones;
                var existingNames = metaphones.Select( m => m.Name ).Distinct();

                // Get the names that have not yet been processed
                var namesToUpdate = nameQry
                    .Where( n => !existingNames.Contains( n ) )
                    .Take( namesToProcess )
                    .ToList();

                foreach ( string name in namesToUpdate )
                {
                    string mp1 = string.Empty;
                    string mp2 = string.Empty;
                    Rock.Utility.DoubleMetaphone.doubleMetaphone( name, ref mp1, ref mp2 );

                    var metaphone = new Metaphone();
                    metaphone.Name = name;
                    metaphone.Metaphone1 = mp1;
                    metaphone.Metaphone2 = mp2;

                    metaphones.Add( metaphone );
                }

                personRockContext.SaveChanges();
            }
        }
 protected virtual string GetRequiredParameter(JobDataMap data, string propertyName, string jobName)
 {
     string value = data.GetString(propertyName);
     if (string.IsNullOrEmpty(value))
     {
         Logger.ErrorFormat("Error in RDirectoryScanJob ({0}): {1} not specified.", jobName, propertyName);
         throw new JobExecutionException(string.Format("{0} not specified.", propertyName));
     }
     return value;
 }
 static EmailTemplateEngine.EmailTemplateEngine GetEmailTemplateEngine(JobDataMap jobDataMap){
     var bodyTemplate = jobDataMap.GetString<SendEmailJobDataMap>(map => map.EmailTemplate);
     var subjectTemplate = jobDataMap.GetString<SendEmailJobDataMap>(emailJobDataMap => emailJobDataMap.SubjectTemplate);
     return new EmailTemplateEngine.EmailTemplateEngine(subjectTemplate,bodyTemplate);
 }