protected override void OnStart( string[] args ) { ISchedulerFactory sf; // create scheduler sf = new StdSchedulerFactory(); sched = sf.GetScheduler(); // get list of active jobs ServiceJobService jobService = new ServiceJobService(); foreach ( ServiceJob job in jobService.GetActiveJobs().ToList() ) { try { IJobDetail jobDetail = jobService.BuildQuartzJob( job ); ITrigger jobTrigger = jobService.BuildQuartzTrigger( job ); sched.ScheduleJob( jobDetail, jobTrigger ); } catch ( Exception ex ) { // get path to the services directory String path = System.Reflection.Assembly.GetExecutingAssembly().Location; path = System.IO.Path.GetDirectoryName(path); // create a friendly error message string message = string.Format("Error loading the job: {0}. Ensure that the correct version of the job's assembly ({1}.dll) in the services directory ({2}) of your server.", job.Name, job.Assembly, path); message = message + "\n\n\n\n" + ex.Message; //throw new JobLoadFailedException( message ); job.LastStatusMessage = message; job.LastStatus = "Error Loading Job"; jobService.Save( job, null ); } } // set up the listener to report back from jobs as they complete sched.ListenerManager.AddJobListener( new RockJobListener(), EverythingMatcher<JobKey>.AllJobs() ); // start the scheduler sched.Start(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { ServiceJob job; ServiceJobService jobService = new ServiceJobService(); int jobId = int.Parse( hfId.Value ); if ( jobId == 0 ) { job = new ServiceJob(); jobService.Add( job, CurrentPersonId ); } else { job = jobService.Get( jobId ); } job.Name = tbName.Text; job.Description = tbDescription.Text; job.IsActive = cbActive.Checked; job.Assembly = tbAssembly.Text; job.Class = tbClass.Text; job.NotificationEmails = tbNotificationEmails.Text; job.NotificationStatus = (JobNotificationStatus)int.Parse( drpNotificationStatus.SelectedValue ); job.CronExpression = tbCronExpression.Text; if ( !job.IsValid ) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction( () => { jobService.Save( job, CurrentPersonId ); } ); BindGrid(); pnlDetails.Visible = false; pnlGrid.Visible = true; }
/// <summary> /// Handles the Start event of the Application control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void Application_Start( object sender, EventArgs e ) { if ( System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment ) { System.Diagnostics.Debug.WriteLine( string.Format( "Application_Start: {0}", DateTime.Now.ToString("hh:mm:ss.FFF" ) )); } // Check if database should be auto-migrated for the core and plugins bool autoMigrate = true; if ( !Boolean.TryParse( ConfigurationManager.AppSettings["AutoMigrateDatabase"], out autoMigrate ) ) { autoMigrate = true; } if ( autoMigrate ) { try { Database.SetInitializer( new MigrateDatabaseToLatestVersion<Rock.Data.RockContext, Rock.Migrations.Configuration>() ); // explictly check if the database exists, and force create it if doesn't exist Rock.Data.RockContext rockContext = new Rock.Data.RockContext(); if ( !rockContext.Database.Exists() ) { rockContext.Database.Initialize( true ); } else { var migrator = new System.Data.Entity.Migrations.DbMigrator( new Rock.Migrations.Configuration() ); migrator.Update(); } // Migrate any plugins that have pending migrations List<Type> configurationTypeList = Rock.Reflection.FindTypes( typeof( System.Data.Entity.Migrations.DbMigrationsConfiguration ) ).Select( a => a.Value ).ToList(); foreach ( var configType in configurationTypeList ) { if ( configType != typeof( Rock.Migrations.Configuration ) ) { var config = Activator.CreateInstance( configType ) as System.Data.Entity.Migrations.DbMigrationsConfiguration; System.Data.Entity.Migrations.DbMigrator pluginMigrator = Activator.CreateInstance( typeof( System.Data.Entity.Migrations.DbMigrator ), config ) as System.Data.Entity.Migrations.DbMigrator; pluginMigrator.Update(); } } } catch ( Exception ex ) { // if migrations fail, log error and attempt to continue LogError( ex, null ); } } else { // default Initializer is CreateDatabaseIfNotExists, but we don't want that to happen if automigrate is false, so set it to NULL so that nothing happens Database.SetInitializer<Rock.Data.RockContext>( null ); } if ( System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment ) { new AttributeService().Get( 0 ); System.Diagnostics.Debug.WriteLine( string.Format( "ConnectToDatabase - Connected: {0}", DateTime.Now.ToString( "hh:mm:ss.FFF" ) ) ); } // Preload the commonly used objects LoadCacheObjects(); if ( System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment ) { System.Diagnostics.Debug.WriteLine( string.Format( "LoadCacheObjects - Done: {0}", DateTime.Now.ToString( "hh:mm:ss.FFF" ) ) ); } // setup and launch the jobs infrastructure if running under IIS bool runJobsInContext = Convert.ToBoolean( ConfigurationManager.AppSettings["RunJobsInIISContext"] ); if ( runJobsInContext ) { ISchedulerFactory sf; // create scheduler sf = new StdSchedulerFactory(); sched = sf.GetScheduler(); // get list of active jobs ServiceJobService jobService = new ServiceJobService(); foreach ( ServiceJob job in jobService.GetActiveJobs().ToList() ) { try { IJobDetail jobDetail = jobService.BuildQuartzJob( job ); ITrigger jobTrigger = jobService.BuildQuartzTrigger( job ); sched.ScheduleJob( jobDetail, jobTrigger ); } catch ( Exception ex ) { // create a friendly error message string message = string.Format( "Error loading the job: {0}. Ensure that the correct version of the job's assembly ({1}.dll) in the websites App_Code directory. \n\n\n\n{2}", job.Name, job.Assembly, ex.Message ); job.LastStatusMessage = message; job.LastStatus = "Error Loading Job"; jobService.Save( job, null ); } } // set up the listener to report back from jobs as they complete sched.ListenerManager.AddJobListener( new RockJobListener(), EverythingMatcher<JobKey>.AllJobs() ); // start the scheduler sched.Start(); } // add call back to keep IIS process awake at night and to provide a timer for the queued transactions AddCallBack(); RegisterFilters( GlobalConfiguration.Configuration.Filters ); RegisterRoutes( RouteTable.Routes ); Rock.Security.Authorization.Load(); AddEventHandlers(); new EntityTypeService().RegisterEntityTypes( Server.MapPath( "~" ) ); new FieldTypeService().RegisterFieldTypes( Server.MapPath( "~" ) ); BundleConfig.RegisterBundles( BundleTable.Bundles ); }
/// <summary> /// Handles the Delete event of the grdScheduledJobs control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gScheduledJobs_Delete( object sender, RowEventArgs e ) { RockTransactionScope.WrapTransaction( () => { var jobService = new ServiceJobService(); ServiceJob job = jobService.Get( (int)e.RowKeyValue ); string errorMessage; if ( !jobService.CanDelete( job, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } jobService.Delete( job, CurrentPersonId ); jobService.Save( job, CurrentPersonId ); } ); BindGrid(); }
/// <summary> /// Handles the Start event of the Application control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void Application_Start( object sender, EventArgs e ) { // Check if database should be auto-migrated bool autoMigrate = true; if ( !Boolean.TryParse( ConfigurationManager.AppSettings["AutoMigrateDatabase"], out autoMigrate ) ) { autoMigrate = true; } if ( autoMigrate ) { Database.SetInitializer( new MigrateDatabaseToLatestVersion<Rock.Data.RockContext, Rock.Migrations.Configuration>() ); } // Preload the commonly used objects LoadCacheObjects(); // setup and launch the jobs infrastructure if running under IIS bool runJobsInContext = Convert.ToBoolean( ConfigurationManager.AppSettings["RunJobsInIISContext"] ); if ( runJobsInContext ) { ISchedulerFactory sf; // create scheduler sf = new StdSchedulerFactory(); sched = sf.GetScheduler(); // get list of active jobs ServiceJobService jobService = new ServiceJobService(); foreach ( ServiceJob job in jobService.GetActiveJobs().ToList() ) { try { IJobDetail jobDetail = jobService.BuildQuartzJob( job ); ITrigger jobTrigger = jobService.BuildQuartzTrigger( job ); sched.ScheduleJob( jobDetail, jobTrigger ); } catch ( Exception ex ) { // create a friendly error message string message = string.Format( "Error loading the job: {0}. Ensure that the correct version of the job's assembly ({1}.dll) in the websites App_Code directory. \n\n\n\n{2}", job.Name, job.Assembly, ex.Message ); job.LastStatusMessage = message; job.LastStatus = "Error Loading Job"; jobService.Save( job, null ); } } // set up the listener to report back from jobs as they complete sched.ListenerManager.AddJobListener( new RockJobListener(), EverythingMatcher<JobKey>.AllJobs() ); // start the scheduler sched.Start(); } // add call back to keep IIS process awake at night and to provide a timer for the queued transactions AddCallBack(); RegisterFilters( GlobalConfiguration.Configuration.Filters ); RegisterRoutes( RouteTable.Routes ); Rock.Security.Authorization.Load(); AddEventHandlers(); }
/// <summary> /// Called by the <see cref="IScheduler"/> after a <see cref="IJobDetail"/> /// has been executed, and before the associated <see cref="Quartz.Spi.IOperableTrigger"/>'s /// <see cref="Quartz.Spi.IOperableTrigger.Triggered"/> method has been called. /// </summary> /// <param name="context"></param> /// <param name="jobException"></param> public void JobWasExecuted( IJobExecutionContext context, JobExecutionException jobException ) { StringBuilder message = new StringBuilder(); bool sendMessage = false; // get job type id int jobId = Convert.ToInt16(context.JobDetail.Description); // load job ServiceJobService jobService = new ServiceJobService(); ServiceJob job = jobService.Get(jobId); // format the message message.Append( String.Format( "The job {0} ran for {1} seconds on {2}. Below is the results:<p>" , job.Name, context.JobRunTime.TotalSeconds, context.FireTimeUtc.Value.DateTime.ToLocalTime()) ); // if noticiation staus is all set flag to send message if ( job.NotificationStatus == JobNotificationStatus.All ) sendMessage = true; // set last run date job.LastRunDateTime = context.FireTimeUtc.Value.DateTime.ToLocalTime(); // set run time job.LastRunDurationSeconds = Convert.ToInt32(context.JobRunTime.TotalSeconds); // set the scheduler name job.LastRunSchedulerName = context.Scheduler.SchedulerName; // determine if an error occured if ( jobException == null ) { job.LastSuccessfulRunDateTime = job.LastRunDateTime; job.LastStatus = "Success"; job.LastStatusMessage = ""; message.Append( "Result: Success" ); // determine if message should be sent if ( job.NotificationStatus == JobNotificationStatus.Success ) sendMessage = true; } else { // put the exception into the status job.LastStatus = "Exception"; job.LastStatusMessage = jobException.Message; message.Append( "Result: Exception<p>Message:<br>" + jobException.Message ); if ( jobException.InnerException != null ) { job.LastStatusMessage += " Inner Exception: " + jobException.InnerException.Message; message.Append( "<p>Inner Exception:<br>" + jobException.InnerException.Message ); } if ( job.NotificationStatus == JobNotificationStatus.Error ) sendMessage = true; } jobService.Save( job, null ); // send notification if ( sendMessage ) { // TODO: implement email send once it's available } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { ServiceJob job; ServiceJobService jobService = new ServiceJobService(); int jobId = int.Parse( hfId.Value ); if ( jobId == 0 ) { job = new ServiceJob(); jobService.Add( job, CurrentPersonId ); } else { job = jobService.Get( jobId ); } job.Name = tbName.Text; job.Description = tbDescription.Text; job.IsActive = cbActive.Checked; job.Class = ddlJobTypes.SelectedValue; job.NotificationEmails = tbNotificationEmails.Text; job.NotificationStatus = (JobNotificationStatus)int.Parse( ddlNotificationStatus.SelectedValue ); job.CronExpression = tbCronExpression.Text; if ( !job.IsValid ) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction( () => { jobService.Save( job, CurrentPersonId ); job.LoadAttributes(); Rock.Attribute.Helper.GetEditValues( phAttributes, job ); Rock.Attribute.Helper.SaveAttributeValues( job, CurrentPersonId ); } ); NavigateToParentPage(); }