public async Task <IActionResult> OnPost() { TaskInterval interval = null; if (!string.IsNullOrEmpty(Input.Interval)) { try { interval = Input.Interval; } catch (Exception) { ModelState.AddModelError("Input.Interval", "时间间隔格式错误,请输入正确的格式!"); return(Error()); } } Task = _taskManager.GeTask(Input.Id); if (await _taskManager.SaveArgumentIntervalAsync(Input.Id, interval?.ToString())) { interval = Task.Interval; await LogAsync("将后台服务 {2} 的时间间隔由 {0} 修改为 {1}。", Task.ToIntervalDisplayString(), interval.ToDisplayString(), Task.Name); return(Success("你已经成功更改了时间间隔!")); } return(Error()); }
/// <summary> /// Registers the web farm server cleaner scheduled task /// </summary> public override void Init() { // Don't create task if it already exists if (TaskInfoProvider.GetTasks().WhereEquals("TaskName", "AzureStorageCacheCleaner").HasResults()) { return; } // Set the interval for every hour var interval = new TaskInterval { Every = 1, Period = SchedulingHelper.PERIOD_HOUR, StartTime = DateTime.Now, BetweenEnd = DateTime.Today.AddMinutes(-1), Days = new ArrayList(Enum.GetNames(typeof(DayOfWeek))) }; // Register the scheduled task var task = new TaskInfo { TaskAssemblyName = Assembly.GetExecutingAssembly().GetName().Name, TaskClass = "AzureStorageCacheCleaner", TaskDisplayName = "Azure storage cache cleaner", TaskInterval = SchedulingHelper.EncodeInterval(interval), TaskName = "AzureStorageCacheCleaner", TaskNextRunTime = DateTime.Now, TaskEnabled = true, TaskData = String.Empty }; TaskInfoProvider.SetTaskInfo(task); }
private static void EnsureTask(ISiteInfo site) { var currentServerName = WebFarmHelper.ServerName; var taskServerName = Service.Resolve <IWebFarmService>().GetEnabledServerNames().First(serverName => !currentServerName.Equals(serverName, StringComparison.Ordinal)); TaskInterval interval = new TaskInterval { StartTime = DateTime.Now, Period = SchedulingHelper.PERIOD_ONCE }; var task = new TaskInfo { TaskAssemblyName = "CMS.UIControls", TaskClass = "Samples.DancingGoat.EnableDataProtectionSampleTask", TaskEnabled = true, TaskLastResult = string.Empty, TaskData = string.Empty, TaskDisplayName = "Data protection sample", TaskName = "EnableDataProtectionSampleTask", TaskType = ScheduledTaskTypeEnum.System, TaskInterval = SchedulingHelper.EncodeInterval(interval), TaskNextRunTime = SchedulingHelper.GetFirstRunTime(interval), TaskDeleteAfterLastRun = true, TaskRunInSeparateThread = true, TaskSiteID = site.SiteID, TaskServerName = taskServerName, TaskAvailability = TaskAvailabilityEnum.Administration }; TaskInfo.Provider.Set(task); }
public IActionResult OnGet(int id) { Task = _taskManager.GeTask(id); if (Task == null) { return(NotFound()); } TaskInterval interval = Task.Interval; DefaultInterval = interval.ToDisplayString(); Input = new InputModel { Id = Task.Id, Interval = Task.TaskArgument.Interval ?? Task.Interval }; return(Page()); }
private void ExecuteRevokeTrackingConsentTask(ISiteInfo site, ContactInfo contact) { const string TASK_NAME_PREFIX = "DataProtectionSampleRevokeTrackingConsentTask"; string taskName = $"{TASK_NAME_PREFIX}_{contact.ContactID}"; // Do not create same task if already scheduled var scheduledTask = taskInfoProvider.Get(taskName, site.SiteID); if (scheduledTask != null) { return; } var currentServerName = WebFarmHelper.ServerName; var taskServerName = webFarmService.GetEnabledServerNames().First(serverName => !currentServerName.Equals(serverName, StringComparison.Ordinal)); TaskInterval interval = new TaskInterval { StartTime = DateTime.Now, Period = SchedulingHelper.PERIOD_ONCE }; var task = new TaskInfo { TaskAssemblyName = "CMS.UIControls", TaskClass = "Samples.DancingGoat.RevokeTrackingConsentTask", TaskEnabled = true, TaskLastResult = string.Empty, TaskData = contact.ContactID.ToString(), TaskDisplayName = "Data protection sample - Revoke tracking consent", TaskName = taskName, TaskType = ScheduledTaskTypeEnum.System, TaskInterval = SchedulingHelper.EncodeInterval(interval), TaskNextRunTime = SchedulingHelper.GetFirstRunTime(interval), TaskDeleteAfterLastRun = true, TaskRunInSeparateThread = true, TaskSiteID = site.SiteID, TaskServerName = taskServerName, TaskAvailability = TaskAvailabilityEnum.Administration }; taskInfoProvider.Set(task); }
private void UpdateDynamicNewsletterTask(NewsletterInfo newsletterObj, TaskInterval taskInterval) { var currentTask = TaskInfoProvider.GetTaskInfo(newsletterObj.NewsletterDynamicScheduledTaskID); var taskIntervalStr = SchedulingHelper.EncodeInterval(taskInterval); if ((currentTask != null) && (currentTask.TaskInterval == taskIntervalStr)) { // No need to update anything, nothing has changed return; } // Update or create new task based on current taskInterval var task = NewsletterTasksManager.CreateOrUpdateDynamicNewsletterTask(newsletterObj, taskInterval, currentTask); TaskInfoProvider.SetTaskInfo(task); // Update taskID newsletterObj.NewsletterDynamicScheduledTaskID = task.TaskID; }
string AddTaskPriv(string topic, string body, int round, TaskInterval interval, string intervalArgument) { var task = new TaskInfo { Id = $"{DateTime.UtcNow.ToString("yyyyMMdd")}.{Snowfake.Default.nextId().ToString()}", Topic = topic, Body = body, CreateTime = DateTime.UtcNow, Round = round, Interval = interval, IntervalArgument = intervalArgument, CurrentRound = 0, ErrorTimes = 0, LastRunTime = new DateTime(1970, 1, 1) }; AddTaskPriv(task, true); return(task.Id); }
/// <summary> /// Creates scheduled task. Called when the "Create task" button is pressed. /// </summary> private bool CreateScheduledTask() { // Create new scheduled task object TaskInfo newTask = new TaskInfo(); // Set the properties newTask.TaskDisplayName = "My new task"; newTask.TaskName = "MyNewTask"; newTask.TaskAssemblyName = "CMS.WorkflowEngine"; newTask.TaskClass = "CMS.WorkflowEngine.ContentPublisher"; // Create interval TaskInterval interval = new TaskInterval(); // Set interval properties interval.Period = SchedulingHelper.PERIOD_DAY; interval.StartTime = DateTime.Now; interval.Every = 2; // Add some days to interval ArrayList days = new ArrayList(); days.Add(DayOfWeek.Monday.ToString()); days.Add(DayOfWeek.Sunday.ToString()); days.Add(DayOfWeek.Thursday.ToString()); interval.Days = days; newTask.TaskInterval = SchedulingHelper.EncodeInterval(interval); newTask.TaskSiteID = CMSContext.CurrentSiteID; newTask.TaskData = "<data></data>"; newTask.TaskEnabled = true; newTask.TaskNextRunTime = SchedulingHelper.GetNextTime(newTask.TaskInterval, DateTime.Now, DateTime.Now); // Save the scheduled task TaskInfoProvider.SetTaskInfo(newTask); return(true); }
/// <summary> /// Creates scheduled task. Called when the "Create task" button is pressed. /// </summary> private bool CreateScheduledTask() { // Create new scheduled task object TaskInfo newTask = new TaskInfo(); // Set the properties newTask.TaskDisplayName = "My new task"; newTask.TaskName = "MyNewTask"; newTask.TaskAssemblyName = "CMS.WorkflowEngine"; newTask.TaskClass = "CMS.WorkflowEngine.ContentPublisher"; // Create interval TaskInterval interval = new TaskInterval(); // Set interval properties interval.Period = SchedulingHelper.PERIOD_DAY; interval.StartTime = DateTime.Now; interval.Every = 2; // Add some days to interval ArrayList days = new ArrayList(); days.Add(DayOfWeek.Monday.ToString()); days.Add(DayOfWeek.Sunday.ToString()); days.Add(DayOfWeek.Thursday.ToString()); interval.Days = days; newTask.TaskInterval = SchedulingHelper.EncodeInterval(interval); newTask.TaskSiteID = CMSContext.CurrentSiteID; newTask.TaskData = "<data></data>"; newTask.TaskEnabled = true; newTask.TaskNextRunTime = SchedulingHelper.GetNextTime(newTask.TaskInterval, DateTime.Now, DateTime.Now); // Save the scheduled task TaskInfoProvider.SetTaskInfo(newTask); return true; }
/// <summary> /// Reloads form with values from the schedule interval. /// </summary> public void ReloadData() { EnsureChildControls(); TaskInterval ti = TaskInterval; if (ti == null) { ti = new TaskInterval(); ti.Every = 1; ti.Period = SchedulingHelper.PERIOD_DAY; ti.StartTime = DateTime.Now; } // Set period type Period.SelectedValue = ti.Period; OnPeriodChangeInit(); // Start time if (StartTime != null) { StartTime.SelectedDateTime = ti.StartTime; } switch (Period.SelectedValue) { case SchedulingHelper.PERIOD_SECOND: case SchedulingHelper.PERIOD_MINUTE: case SchedulingHelper.PERIOD_HOUR: Quantity.Text = ti.Every.ToString(); FromHours.Text = ti.BetweenStart.TimeOfDay.Hours >= 10 ? ti.BetweenStart.TimeOfDay.Hours.ToString() : "0" + ti.BetweenStart.TimeOfDay.Hours.ToString(); FromMinutes.Text = ti.BetweenStart.TimeOfDay.Minutes >= 10 ? ti.BetweenStart.TimeOfDay.Minutes.ToString() : "0" + ti.BetweenStart.TimeOfDay.Minutes.ToString(); ToHours.Text = ti.BetweenEnd.TimeOfDay.Hours >= 10 ? ti.BetweenEnd.TimeOfDay.Hours.ToString() : "0" + ti.BetweenEnd.TimeOfDay.Hours.ToString(); ToMinutes.Text = ti.BetweenEnd.TimeOfDay.Minutes >= 10 ? ti.BetweenEnd.TimeOfDay.Minutes.ToString() : "0" + ti.BetweenEnd.TimeOfDay.Minutes.ToString(); SetDays(WeekDays, ti.Days); SetDays(WeekEnd, ti.Days); break; case SchedulingHelper.PERIOD_DAY: Quantity.Text = ti.Every.ToString(); SetDays(WeekDays, ti.Days); SetDays(WeekEnd, ti.Days); break; case SchedulingHelper.PERIOD_WEEK: case SchedulingHelper.PERIOD_YEAR: Quantity.Text = ti.Every.ToString(); break; case SchedulingHelper.PERIOD_MONTH: if (string.IsNullOrEmpty(ti.Day)) { MonthDate.SelectedValue = ti.Order.ToLowerCSafe(); MonthModeDate.Checked = true; MonthModeSelectionChanged(true); } else { MonthOrder.SelectedValue = ti.Order.ToLowerCSafe(); MonthModeSpecification.Checked = true; MonthModeSelectionChanged(false); MonthDay.SelectedValue = ti.Day; } break; } WeekListChecked = (TaskInterval != null); }
/// <summary> /// Reloads form with values from the schedule interval. /// </summary> public void ReloadData() { EnsureChildControls(); TaskInterval ti = TaskInterval; if (ti == null) { ti = new TaskInterval(); ti.Every = 1; ti.Period = SchedulingHelper.PERIOD_DAY; ti.StartTime = DateTime.Now; } // Set period type Period.SelectedValue = ti.Period; OnPeriodChangeInit(); // Start time if (StartTime != null) { StartTime.SelectedDateTime = ti.StartTime; } switch (Period.SelectedValue) { case SchedulingHelper.PERIOD_SECOND: case SchedulingHelper.PERIOD_MINUTE: case SchedulingHelper.PERIOD_HOUR: Quantity.Text = ti.Every.ToString(); FromHours.Text = ti.BetweenStart.TimeOfDay.Hours >= 10 ? ti.BetweenStart.TimeOfDay.Hours.ToString() : "0" + ti.BetweenStart.TimeOfDay.Hours.ToString(); FromMinutes.Text = ti.BetweenStart.TimeOfDay.Minutes >= 10 ? ti.BetweenStart.TimeOfDay.Minutes.ToString() : "0" + ti.BetweenStart.TimeOfDay.Minutes.ToString(); ToHours.Text = ti.BetweenEnd.TimeOfDay.Hours >= 10 ? ti.BetweenEnd.TimeOfDay.Hours.ToString() : "0" + ti.BetweenEnd.TimeOfDay.Hours.ToString(); ToMinutes.Text = ti.BetweenEnd.TimeOfDay.Minutes >= 10 ? ti.BetweenEnd.TimeOfDay.Minutes.ToString() : "0" + ti.BetweenEnd.TimeOfDay.Minutes.ToString(); SetDays(WeekDays, ti.Days); SetDays(WeekEnd, ti.Days); break; case SchedulingHelper.PERIOD_DAY: Quantity.Text = ti.Every.ToString(); SetDays(WeekDays, ti.Days); SetDays(WeekEnd, ti.Days); break; case SchedulingHelper.PERIOD_WEEK: Quantity.Text = ti.Every.ToString(); break; case SchedulingHelper.PERIOD_MONTH: if (string.IsNullOrEmpty(ti.Day)) { MonthDate.SelectedValue = ti.Order.ToLowerCSafe(); MonthModeDate.Checked = true; MonthModeSelectionChanged(true); } else { MonthOrder.SelectedValue = ti.Order.ToLowerCSafe(); MonthModeSpecification.Checked = true; MonthModeSelectionChanged(false); MonthDay.SelectedValue = ti.Day; } break; } WeekListChecked = (TaskInterval != null); }
/// <summary> /// Handles the UniGrid's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that threw event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void UniGridTasks_OnAction(string actionName, object actionArgument) { switch (actionName.ToLower()) { case "edit": URLHelper.Redirect("Task_Edit.aspx?taskname=" + actionArgument.ToString() + "&" + GetSiteOrSelectedSite()); break; case "delete": { // Check "modify" permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.ScheduledTasks", "Modify")) { RedirectToAccessDenied("CMS.ScheduledTasks", "Modify"); } // Delete the task try { int taskId = Convert.ToInt32(actionArgument); TaskInfo ti = TaskInfoProvider.GetTaskInfo(taskId); if (ti != null) { ti.Generalized.LogSynchronization = SynchronizationTypeEnum.LogSynchronization; ti.Generalized.LogIntegration = true; ti.Generalized.LogEvents = true; TaskInfoProvider.DeleteTaskInfo(ti); } } catch (Exception ex) { lblError.Visible = true; lblError.Text = GetString("Task_List.DeleteError") + " Original exception: " + ex.Message; } } break; case "execute": { // Check "modify" permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.ScheduledTasks", "Modify")) { RedirectToAccessDenied("CMS.ScheduledTasks", "Modify"); } TaskInfo ti = TaskInfoProvider.GetTaskInfo(Convert.ToInt32(actionArgument)); if (ti != null) { if (ti.TaskEnabled) { TaskInterval interval = new TaskInterval(); interval = SchedulingHelper.DecodeInterval(ti.TaskInterval); if ((ti.TaskNextRunTime != DateTimeHelper.ZERO_TIME) || (interval.Period == SchedulingHelper.PERIOD_ONCE)) { ti.TaskNextRunTime = DateTime.Now; // Update the task TaskInfoProvider.SetTaskInfo(ti); // Run the task SchedulingTimer.RunSchedulerImmediately = true; if (si != null) { SchedulingTimer.SchedulerRunImmediatelySiteName = si.SiteName; } string url = URLHelper.Url.AbsoluteUri; url = URLHelper.AddParameterToUrl(url, "selectedsiteid", SelectedSiteID.ToString()); lblInfo.Text = GetString("ScheduledTask.WasExecuted"); lblInfo.Visible = true; //ScriptHelper.RegisterStartupScript(this, typeof(string), "InformExecuted", // "alert('" + GetString("ScheduledTask.WasExecuted") + "'); \n" + // "document.location = '" + url + "'; \n", true); } else { lblInfo.Text = GetString("ScheduledTask.TaskAlreadyrunning"); lblInfo.Visible = true; } } else { lblError.Text = GetString("ScheduledTask.TaskNotEnabled"); lblError.Visible = true; } } } break; } }
/// <summary> /// Handles the UniGrid's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that threw event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void gridElem_OnAction(string actionName, object actionArgument) { switch (actionName.ToLowerCSafe()) { case "edit": if (!String.IsNullOrEmpty(EditURL)) { URLHelper.Redirect(String.Format(EditURL, actionArgument.ToString())); } break; case "delete": { // Check "modify" permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.ScheduledTasks", "Modify")) { RedirectToAccessDenied("CMS.ScheduledTasks", "Modify"); } // Delete the task try { int taskId = Convert.ToInt32(actionArgument); TaskInfo ti = TaskInfoProvider.GetTaskInfo(taskId); if (ti != null) { ti.Generalized.LogSynchronization = SynchronizationTypeEnum.LogSynchronization; ti.Generalized.LogIntegration = true; ti.Generalized.LogEvents = true; TaskInfoProvider.DeleteTaskInfo(ti); } } catch (Exception ex) { ShowError(GetString("Task_List.DeleteError"), ex.Message, null); } } break; case "execute": { // Check "modify" permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.ScheduledTasks", "Modify")) { RedirectToAccessDenied("CMS.ScheduledTasks", "Modify"); } TaskInfo ti = TaskInfoProvider.GetTaskInfo(Convert.ToInt32(actionArgument)); if (ti != null) { SiteInfo si = SiteInfoProvider.GetSiteInfo(SiteID); if (!ti.TaskEnabled) { // Task is not enabled (won't be executed at the end of request), run it now SchedulingExecutor.ExecuteTask(ti.TaskID, (si != null) ? si.SiteName : CMSContext.CurrentSiteName); } else { TaskInterval interval = new TaskInterval(); interval = SchedulingHelper.DecodeInterval(ti.TaskInterval); if ((ti.TaskNextRunTime != DateTimeHelper.ZERO_TIME) || (interval.Period == SchedulingHelper.PERIOD_ONCE)) { ti.TaskNextRunTime = DateTime.Now; // Update the task TaskInfoProvider.SetTaskInfo(ti); // Run the task SchedulingTimer.RunSchedulerImmediately = true; if (si != null) { SchedulingTimer.SchedulerRunImmediatelySiteName = si.SiteName; } } else { ShowWarning(GetString("ScheduledTask.TaskAlreadyrunning"), null, null); return; } } ShowConfirmation(GetString("ScheduledTask.WasExecuted")); } } break; } }
/// <summary> /// Sets form with values from the schedule interval string. /// </summary> /// <param name="interval">Schedule interval string</param> protected void SetupForm(TaskInterval interval) { EnsureChildControls(); if (TimeoutEnabled || !AllowNoTimeout) { interval = interval ?? new TaskInterval(); // Set period type if (interval.Period == SchedulingHelper.PERIOD_ONCE) { rbDateMode.Checked = true; } else { rbIntervalMode.Checked = true; drpScale.SelectedValue = interval.Period; OnPeriodChangeInit(); } if (interval.UseSpecificTime) { cbSpecificTime.Checked = true; timePicker.Visible = true; timePicker.Time = interval.StartTime; } rbExactly.Checked = false; rbNextDay.Checked = false; rbNextDate.Checked = false; switch (Mode) { case SchedulingHelper.PERIOD_MINUTE: case SchedulingHelper.PERIOD_HOUR: case SchedulingHelper.PERIOD_DAY: txtQuantity.Text = interval.Every.ToString(); break; case SchedulingHelper.PERIOD_WEEK: txtQuantity.Text = interval.Every.ToString(); if (String.IsNullOrEmpty(interval.Day)) { rbExactly.Checked = true; } else { drpNextDay.SelectedValue = interval.Day; rbNextDay.Checked = true; } DateModeChanged(); break; case SchedulingHelper.PERIOD_MONTH: txtQuantity.Text = interval.Every.ToString(); if (String.IsNullOrEmpty(interval.Order)) { rbExactly.Checked = true; } else if (ValidationHelper.GetInteger(interval.Order, 0) != 0) { rbNextDate.Checked = true; drpNextDate.SelectedValue = interval.Order; DateModeChanged(); } else { rbNextDay.Checked = true; drpNextOrder.SelectedValue = interval.Order; DateModeChanged(); drpNextDay.SelectedValue = interval.Day; } break; case SchedulingHelper.PERIOD_YEAR: txtQuantity.Text = interval.Every.ToString(); if (!String.IsNullOrEmpty(interval.Day) && !String.IsNullOrEmpty(interval.Order)) { rbNextDate.Checked = true; drpNextDateMonth.SelectedValue = interval.Order; DateModeChanged(); drpNextDate.SelectedValue = interval.Day; } else { rbExactly.Checked = true; DateModeChanged(); } break; case SchedulingHelper.PERIOD_ONCE: ShowDatePanel(); dateTimePicker.SelectedDateTime = interval.StartTime; break; } } else { HideAllPanels(); } }
/// <summary> /// Saves configuration changes. /// </summary> protected void SaveData() { // Check "configure" permission if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.newsletter", "configure")) { RedirectToAccessDenied("cms.newsletter", "configure"); } string scheduledInterval = null; if (isDynamic && chkSchedule.Checked) { // Get scheduled interval for dynamic newsletter scheduledInterval = schedulerInterval.ScheduleInterval; } string errorMessage = ValidateNewsletterValues(); if (!string.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); return; } NewsletterInfo newsletterObj = NewsletterInfoProvider.GetNewsletterInfo(txtNewsletterName.Text.Trim(), SiteContext.CurrentSiteID); // Newsletter's code name must be unique if (newsletterObj != null && newsletterObj.NewsletterID != EditedNewsletter.NewsletterID) { ShowError(GetString("Newsletter_Edit.NewsletterNameExists")); return; } if (newsletterObj == null) { newsletterObj = NewsletterInfoProvider.GetNewsletterInfo(EditedNewsletter.NewsletterID); } SetNewsletterValues(newsletterObj); // Check if subscription template was selected int subscriptionTemplateValue = ValidationHelper.GetInteger(subscriptionTemplate.Value, 0); if (EditedFeedIsNewsletter() && subscriptionTemplateValue == 0) { ShowError(GetString("Newsletter_Edit.NoSubscriptionTemplateSelected")); return; } newsletterObj.NewsletterSubscriptionTemplateID = subscriptionTemplateValue; // Check if double opt-in template was selected if (chkEnableOptIn.Checked) { int optInTemplateValue = ValidationHelper.GetInteger(optInSelector.Value, 0); if (optInTemplateValue == 0) { ShowError(GetString("Newsletter_Edit.NoOptInTemplateSelected")); return; } newsletterObj.NewsletterOptInTemplateID = optInTemplateValue; } else { newsletterObj.NewsletterOptInTemplateID = 0; } // Check if unsubscription template was selected int unsubscriptionTemplateValue = ValidationHelper.GetInteger(unsubscriptionTemplate.Value, 0); if (unsubscriptionTemplateValue == 0) { ShowError(GetString("Newsletter_Edit.NoUnsubscriptionTemplateSelected")); return; } newsletterObj.NewsletterUnsubscriptionTemplateID = unsubscriptionTemplateValue; // ID of scheduled task which should be deleted int deleteScheduledTaskId = 0; if (isDynamic) { newsletterObj.NewsletterSource = NewsletterSource.Dynamic; newsletterObj.NewsletterDynamicURL = txtNewsletterDynamicURL.Value.ToString(); newsletterObj.NewsletterDynamicSubject = radFollowing.Checked ? txtSubject.Text : string.Empty; if ((String.IsNullOrEmpty(txtNewsletterDynamicURL.Value.ToString()))) { // Dynamic URL cannot be empty ShowError(GetString("newsletter_edit.sourcepageurlempty")); return; } if (chkSchedule.Checked) { if (!schedulerInterval.CheckOneDayMinimum()) { // If problem occurred while setting schedule interval ShowError(GetString("Newsletter_Edit.NoDaySelected")); return; } TaskInterval taskInterval = SchedulingHelper.DecodeInterval(scheduledInterval); if (!DataTypeManager.IsValidDate(taskInterval.StartTime)) { ShowError(GetString("Newsletter.IncorrectDate")); return; } UpdateDynamicNewsletterTask(newsletterObj, taskInterval); } else { if (newsletterObj.NewsletterDynamicScheduledTaskID > 0) { // Store task ID for deletion deleteScheduledTaskId = newsletterObj.NewsletterDynamicScheduledTaskID; } newsletterObj.NewsletterDynamicScheduledTaskID = 0; schedulerInterval.Visible = false; } } else { newsletterObj.NewsletterSource = NewsletterSource.TemplateBased; // Check if at least one template is selected if (string.IsNullOrEmpty(ValidationHelper.GetString(usTemplates.Value, null))) { ShowError(GetString("Newsletter_Edit.NoEmailTemplateSelected")); usTemplates.Value = mCurrentTemplates; return; } SaveTemplates(); } // Save changes to DB NewsletterInfoProvider.SetNewsletterInfo(newsletterObj); if (deleteScheduledTaskId > 0) { // Delete scheduled task if schedule mail-outs were unchecked TaskInfoProvider.DeleteTaskInfo(deleteScheduledTaskId); } ShowChangesSaved(); // Update breadcrumbs ScriptHelper.RefreshTabHeader(Page, newsletterObj.NewsletterDisplayName); }
/// <summary> /// Creates schedule interval string. /// </summary> protected string EncodeInterval() { //string intervalCode = null; TaskInterval ti = new TaskInterval(); string error = GetString("ScheduleInterval.WrongFormat"); string empty = GetString("ScheduleInterval.ErrorEmpty"); string result = string.Empty; try { ti.Period = drpPeriod.SelectedValue; ti.StartTime = dateTimePicker.SelectedDateTime; switch (drpPeriod.SelectedIndex) { case 0: // Second case 1: // Minute case 2: // Hour result = new Validator().NotEmpty(txtFromHours.Text, empty).IsInteger(txtFromHours.Text, error).NotEmpty(txtFromMinutes.Text, empty).IsInteger(txtFromMinutes.Text, error).NotEmpty(txtToHours.Text, empty).IsInteger(txtToHours.Text, error).NotEmpty(txtToMinutes.Text, empty).IsInteger(txtToMinutes.Text, error).NotEmpty(txtEvery.Text, empty).IsInteger(txtEvery.Text, error).Result; if (string.IsNullOrEmpty(result)) { if ((Convert.ToInt32(txtFromHours.Text) >= 0) && (Convert.ToInt32(txtFromHours.Text) <= 23) && (Convert.ToInt32(txtFromMinutes.Text) >= 0) && (Convert.ToInt32(txtFromMinutes.Text) <= 59)) { if ((Convert.ToInt32(txtToHours.Text) >= 0) && (Convert.ToInt32(txtToHours.Text) <= 23) && (Convert.ToInt32(txtToMinutes.Text) >= 0) && (Convert.ToInt32(txtToMinutes.Text) <= 59)) { if ((Convert.ToInt32(txtEvery.Text) >= 0) && (Convert.ToInt32(txtEvery.Text) <= 10000)) { DateTime time = new DateTime(); ti.Every = Convert.ToInt32(txtEvery.Text); time = new DateTime(1, 1, 1, Convert.ToInt32(txtFromHours.Text), Convert.ToInt32(txtFromMinutes.Text), 0); ti.BetweenStart = time; time = new DateTime(1, 1, 1, Convert.ToInt32(txtToHours.Text), Convert.ToInt32(txtToMinutes.Text), 0); ti.BetweenEnd = time; foreach (ListItem item in chkWeek.Items) { if (item.Selected) { ti.Days.Add(item.Value); } } foreach (ListItem item in chkWeekEnd.Items) { if (item.Selected) { ti.Days.Add(item.Value); } } } else { lblError.Text = error; txtEvery.ForeColor = System.Drawing.Color.Red; } } else { lblError.Text = error; txtToHours.ForeColor = System.Drawing.Color.Red; txtToMinutes.ForeColor = System.Drawing.Color.Red; } } else { lblError.Text = error; txtFromHours.ForeColor = System.Drawing.Color.Red; txtFromMinutes.ForeColor = System.Drawing.Color.Red; } } break; case 3: // Day result = new Validator().NotEmpty(txtEvery.Text, empty).IsInteger(txtEvery.Text, error).Result; if (string.IsNullOrEmpty(result)) { if ((Convert.ToInt32(txtEvery.Text) >= 0) && (Convert.ToInt32(txtEvery.Text) <= 10000)) { ti.Every = Convert.ToInt32(txtEvery.Text); // Days foreach (ListItem item in chkWeek.Items) { if (item.Selected) { ti.Days.Add(item.Value); } } foreach (ListItem item in chkWeekEnd.Items) { if (item.Selected) { ti.Days.Add(item.Value); } } } else { lblError.Text = error; txtEvery.ForeColor = System.Drawing.Color.Red; } } break; case 4: // Week result = new Validator().NotEmpty(txtEvery.Text, empty).IsInteger(txtEvery.Text, error).Result; if (string.IsNullOrEmpty(result)) { if ((Convert.ToInt32(txtEvery.Text) >= 0) && (Convert.ToInt32(txtEvery.Text) <= 10000)) { ti.Every = Convert.ToInt32(txtEvery.Text); } else { lblError.Text = error; txtEvery.ForeColor = System.Drawing.Color.Red; } } break; case 5: // Month if (radMonth1.Checked) { ti.Order = drpMonth1.SelectedValue; } else { ti.Order = drpMonth2.SelectedValue; ti.Day = drpMonth3.SelectedValue; } break; case 6: // Once break; } } catch { lblError.Text = error; dateTimePicker.DateTimeTextBox.ForeColor = System.Drawing.Color.Red; } if (!string.IsNullOrEmpty(result)) { lblError.Text = result; ti = new TaskInterval(); } mWeekListChecked = true; string enti = SchedulingHelper.EncodeInterval(ti); return enti; }
/// <summary> /// Creates schedule interval string. /// </summary> protected override string EncodeInterval() { if (!TimeoutEnabled) { return String.Empty; } TaskInterval ti = new TaskInterval(); string result = string.Empty; try { ti.Period = Mode; if (Mode != SchedulingHelper.PERIOD_ONCE) { result = new Validator().NotEmpty(txtQuantity.Text, GetString("timeoutselector.quantity.errorempty")).IsInteger(txtQuantity.Text, String.Format(GetString("timeoutselector.quantity.wrongformat"), QUANTITYMAXIMUM)).Result; if (String.IsNullOrEmpty(result)) { int quantity = ValidationHelper.GetInteger(txtQuantity.Text, -1); if ((quantity >= QuantityLowerBound) && (quantity <= QUANTITYMAXIMUM)) { ti.Every = quantity; } else { txtQuantity.ForeColor = Color.Red; } } } if (String.IsNullOrEmpty(result)) { switch (Mode) { case SchedulingHelper.PERIOD_MINUTE: case SchedulingHelper.PERIOD_HOUR: case SchedulingHelper.PERIOD_DAY: ti.BetweenStart = DateTime.MinValue; ti.BetweenEnd = DateTime.MaxValue; // Add all days to match the format AddWeekDays(ti); AddWeekEnd(ti); break; case SchedulingHelper.PERIOD_WEEK: if (rbNextDay.Checked) { ti.Order = drpNextOrder.SelectedValue; ti.Day = drpNextDay.SelectedValue; } break; case SchedulingHelper.PERIOD_MONTH: if (rbNextDate.Checked) { ti.Order = drpNextDate.SelectedValue; } else if (rbNextDay.Checked) { ti.Order = drpNextOrder.SelectedValue; ti.Day = drpNextDay.SelectedValue; } break; case SchedulingHelper.PERIOD_YEAR: if (rbNextDate.Checked) { ti.Order = drpNextDateMonth.SelectedValue; ti.Day = drpNextDate.SelectedValue; } break; case SchedulingHelper.PERIOD_ONCE: if (dateTimePicker.SelectedDateTime != DateTime.MinValue) { ti.StartTime = dateTimePicker.SelectedDateTime; } else { result = GetString("timeoutselector.errorinvaliddate"); } break; } // Add specific time to start date if (String.IsNullOrEmpty(result) && cbSpecificTime.Visible && cbSpecificTime.Checked) { //result = new Validator().NotEmpty(txtSpecificTimeHour.Text, GetString("timeoutselector.specifichour.errorempty")).IsInteger(txtSpecificTimeHour.Text, GetString("timeoutselector.specifichour.wrongformat")).NotEmpty(txtSpecificTimeMinute.Text, GetString("timeoutselector.specificminute.errorempty")).IsInteger(txtSpecificTimeMinute.Text, GetString("timeoutselector.specificminute.wrongformat")).Result; if (timePicker.IsValid()) { ti.StartTime = ti.StartTime.AddHours(timePicker.Time.Hour); ti.StartTime = ti.StartTime.AddMinutes(timePicker.Time.Minute); ti.UseSpecificTime = true; } else { result = timePicker.ErrorMessage; } } else { ti.UseSpecificTime = false; } } } catch(Exception ex) { ShowError(ex.Message); result = ex.Message; dateTimePicker.DateTimeTextBox.ForeColor = Color.Red; } if (!String.IsNullOrEmpty(result)) { AddError(result); return null; } WeekListChecked = true; return SchedulingHelper.EncodeInterval(ti); }
/// <summary> /// Sets form with values from the schedule interval string. /// </summary> /// <param name="interval">Schedule interval string</param> protected void DecodeInterval(string interval) { EnsureChildControls(); if (string.IsNullOrEmpty(interval)) { return; } // Decode interval string TaskInterval ti = new TaskInterval(); ti = SchedulingHelper.DecodeInterval(interval); // Set period type drpPeriod.SelectedValue = ti.Period; OnPeriodChangeInit(); // Start time dateTimePicker.SelectedDateTime = ti.StartTime; switch (drpPeriod.SelectedIndex) { case 0: // Second case 1: // Minute case 2: // Hour txtEvery.Text = ti.Every.ToString(); txtFromHours.Text = ti.BetweenStart.TimeOfDay.Hours >= 10 ? ti.BetweenStart.TimeOfDay.Hours.ToString() : "0" + ti.BetweenStart.TimeOfDay.Hours.ToString(); txtFromMinutes.Text = ti.BetweenStart.TimeOfDay.Minutes >= 10 ? ti.BetweenStart.TimeOfDay.Minutes.ToString() : "0" + ti.BetweenStart.TimeOfDay.Minutes.ToString(); txtToHours.Text = ti.BetweenEnd.TimeOfDay.Hours >= 10 ? ti.BetweenEnd.TimeOfDay.Hours.ToString() : "0" + ti.BetweenEnd.TimeOfDay.Hours.ToString(); txtToMinutes.Text = ti.BetweenEnd.TimeOfDay.Minutes >= 10 ? ti.BetweenEnd.TimeOfDay.Minutes.ToString() : "0" + ti.BetweenEnd.TimeOfDay.Minutes.ToString(); foreach (ListItem li in chkWeek.Items) { li.Selected = false; foreach (string Day in ti.Days) { if (li.Value.ToLower() == Day.ToLower()) { li.Selected = true; } } } foreach (ListItem li in chkWeekEnd.Items) { li.Selected = false; foreach (string Day in ti.Days) { if (li.Value.ToLower() == Day.ToLower()) { li.Selected = true; } } } break; case 3: // Day txtEvery.Text = ti.Every.ToString(); foreach (ListItem li in chkWeek.Items) { li.Selected = false; foreach (string Day in ti.Days) { if (li.Value.ToLower() == Day.ToLower()) { li.Selected = true; } } } foreach (ListItem li in chkWeekEnd.Items) { li.Selected = false; foreach (string Day in ti.Days) { if (li.Value.ToLower() == Day.ToLower()) { li.Selected = true; } } } break; case 4: // Week txtEvery.Text = ti.Every.ToString(); break; case 5: // Month if (string.IsNullOrEmpty(ti.Day)) { drpMonth1.SelectedValue = ti.Order.ToLower(); radMonth1.Checked = true; radMonth1_CheckedChanged(null, null); } else { drpMonth2.SelectedValue = ti.Order.ToLower(); radMonth2.Checked = true; radMonth2_CheckedChanged(null, null); drpMonth3.SelectedValue = ti.Day; } break; } mWeekListChecked = true; }
/// <summary> /// Creates schedule interval string. /// </summary> protected string EncodeInterval() { //string intervalCode = null; TaskInterval ti = new TaskInterval(); string error = GetString("ScheduleInterval.WrongFormat"); string empty = GetString("ScheduleInterval.ErrorEmpty"); string result = string.Empty; try { ti.Period = drpPeriod.SelectedValue; ti.StartTime = dateTimePicker.SelectedDateTime; switch (drpPeriod.SelectedIndex) { case 0: // Second case 1: // Minute case 2: // Hour result = new Validator().NotEmpty(txtFromHours.Text, empty).IsInteger(txtFromHours.Text, error).NotEmpty(txtFromMinutes.Text, empty).IsInteger(txtFromMinutes.Text, error).NotEmpty(txtToHours.Text, empty).IsInteger(txtToHours.Text, error).NotEmpty(txtToMinutes.Text, empty).IsInteger(txtToMinutes.Text, error).NotEmpty(txtEvery.Text, empty).IsInteger(txtEvery.Text, error).Result; if (string.IsNullOrEmpty(result)) { if ((Convert.ToInt32(txtFromHours.Text) >= 0) && (Convert.ToInt32(txtFromHours.Text) <= 23) && (Convert.ToInt32(txtFromMinutes.Text) >= 0) && (Convert.ToInt32(txtFromMinutes.Text) <= 59)) { if ((Convert.ToInt32(txtToHours.Text) >= 0) && (Convert.ToInt32(txtToHours.Text) <= 23) && (Convert.ToInt32(txtToMinutes.Text) >= 0) && (Convert.ToInt32(txtToMinutes.Text) <= 59)) { if ((Convert.ToInt32(txtEvery.Text) >= 0) && (Convert.ToInt32(txtEvery.Text) <= 10000)) { DateTime time = new DateTime(); ti.Every = Convert.ToInt32(txtEvery.Text); time = new DateTime(1, 1, 1, Convert.ToInt32(txtFromHours.Text), Convert.ToInt32(txtFromMinutes.Text), 0); ti.BetweenStart = time; time = new DateTime(1, 1, 1, Convert.ToInt32(txtToHours.Text), Convert.ToInt32(txtToMinutes.Text), 0); ti.BetweenEnd = time; foreach (ListItem item in chkWeek.Items) { if (item.Selected) { ti.Days.Add(item.Value); } } foreach (ListItem item in chkWeekEnd.Items) { if (item.Selected) { ti.Days.Add(item.Value); } } } else { lblError.Text = error; txtEvery.ForeColor = System.Drawing.Color.Red; } } else { lblError.Text = error; txtToHours.ForeColor = System.Drawing.Color.Red; txtToMinutes.ForeColor = System.Drawing.Color.Red; } } else { lblError.Text = error; txtFromHours.ForeColor = System.Drawing.Color.Red; txtFromMinutes.ForeColor = System.Drawing.Color.Red; } } break; case 3: // Day result = new Validator().NotEmpty(txtEvery.Text, empty).IsInteger(txtEvery.Text, error).Result; if (string.IsNullOrEmpty(result)) { if ((Convert.ToInt32(txtEvery.Text) >= 0) && (Convert.ToInt32(txtEvery.Text) <= 10000)) { ti.Every = Convert.ToInt32(txtEvery.Text); // Days foreach (ListItem item in chkWeek.Items) { if (item.Selected) { ti.Days.Add(item.Value); } } foreach (ListItem item in chkWeekEnd.Items) { if (item.Selected) { ti.Days.Add(item.Value); } } } else { lblError.Text = error; txtEvery.ForeColor = System.Drawing.Color.Red; } } break; case 4: // Week result = new Validator().NotEmpty(txtEvery.Text, empty).IsInteger(txtEvery.Text, error).Result; if (string.IsNullOrEmpty(result)) { if ((Convert.ToInt32(txtEvery.Text) >= 0) && (Convert.ToInt32(txtEvery.Text) <= 10000)) { ti.Every = Convert.ToInt32(txtEvery.Text); } else { lblError.Text = error; txtEvery.ForeColor = System.Drawing.Color.Red; } } break; case 5: // Month if (radMonth1.Checked) { ti.Order = drpMonth1.SelectedValue; } else { ti.Order = drpMonth2.SelectedValue; ti.Day = drpMonth3.SelectedValue; } break; case 6: // Once break; } } catch { lblError.Text = error; dateTimePicker.DateTimeTextBox.ForeColor = System.Drawing.Color.Red; } if (!string.IsNullOrEmpty(result)) { lblError.Text = result; ti = new TaskInterval(); } mWeekListChecked = true; string enti = SchedulingHelper.EncodeInterval(ti); return(enti); }
/// <summary> /// Sets data to database. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Check "modify" permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.ScheduledTasks", "Modify")) { RedirectToAccessDenied("CMS.ScheduledTasks", "Modify"); } // Check required fields format string errorMessage = new Validator().NotEmpty(txtTaskDisplayName.Text, rfvDisplayName.ErrorMessage).NotEmpty(txtTaskName.Text, rfvName.ErrorMessage).NotEmpty(txtTaskAssemblyName.Text, rfvAssembly.ErrorMessage).NotEmpty(txtTaskClass.Text, rfvClass.ErrorMessage). IsCodeName(txtTaskName.Text, GetString("Task_Edit.InvalidTaskName")). IsCodeName(txtTaskAssemblyName.Text, GetString("Task_Edit.InvalidTaskAssemblyName")). IsCodeName(txtTaskClass.Text, GetString("Task_Edit.InvalidTaskClass")) .Result; if ((errorMessage == String.Empty) && !ScheduleInterval1.CheckIntervalPreceedings()) { errorMessage = GetString("Task_Edit.BetweenIntervalPreceedingsError"); } if ((errorMessage == String.Empty) && !ScheduleInterval1.CheckOneDayMinimum()) { errorMessage = GetString("Task_Edit.AtLeastOneDayError"); } // Checking date/time limit (SQL limit) if (errorMessage == String.Empty) { TaskInterval ti = SchedulingHelper.DecodeInterval(ScheduleInterval1.ScheduleInterval); if ((ti != null) && ((ti.StartTime < new DateTime(1755, 1, 1, 0, 0, 0)) || (ti.StartTime > new DateTime(9997, 12, 31, 23, 59, 59)))) { ti.StartTime = DateTime.Now; ScheduleInterval1.ScheduleInterval = SchedulingHelper.EncodeInterval(ti); } } if (errorMessage != "") { lblError.Visible = true; lblError.Text = errorMessage; } else { // Check existing task name TaskInfo existingTask; if (si != null) { existingTask = TaskInfoProvider.GetTaskInfo(txtTaskName.Text.Trim(), si.SiteName); } else { existingTask = TaskInfoProvider.GetTaskInfo(txtTaskName.Text.Trim(), null); } if ((existingTask != null) && ((taskObj == null) || (existingTask.TaskID != taskObj.TaskID))) { lblError.Visible = true; lblError.Text = GetString("Task_Edit.TaskNameExists").Replace("%%name%%", existingTask.TaskName); return; } if (taskObj == null) { // create new item -> insert taskObj = new TaskInfo(); taskObj.TaskSiteID = siteID; if (!developmentMode) { taskObj.TaskAllowExternalService = true; } } taskObj.TaskAssemblyName = txtTaskAssemblyName.Text.Trim(); taskObj.TaskClass = txtTaskClass.Text.Trim(); taskObj.TaskData = txtTaskData.Text.Trim(); taskObj.TaskName = txtTaskName.Text.Trim(); taskObj.TaskEnabled = chkTaskEnabled.Checked; taskObj.TaskDeleteAfterLastRun = chkTaskDeleteAfterLastRun.Checked; taskObj.TaskInterval = ScheduleInterval1.ScheduleInterval; taskObj.TaskDisplayName = txtTaskDisplayName.Text.Trim(); taskObj.TaskServerName = txtServerName.Text.Trim(); taskObj.TaskRunInSeparateThread = chkRunTaskInSeparateThread.Checked; taskObj.TaskUseExternalService = chkTaskUseExternalService.Checked; if (plcAllowExternalService.Visible) { taskObj.TaskAllowExternalService = chkTaskAllowExternalService.Checked; } if (plcUseExternalService.Visible) { taskObj.TaskUseExternalService = chkTaskUseExternalService.Checked; } taskObj.TaskNextRunTime = SchedulingHelper.GetNextTime(taskObj.TaskInterval, new DateTime(), new DateTime()); if (drpModule.Visible) { taskObj.TaskResourceID = ValidationHelper.GetInteger(drpModule.Value, 0); } // Set synchronization to true (default is false for Scheduled task) taskObj.Generalized.LogSynchronization = SynchronizationTypeEnum.LogSynchronization; taskObj.Generalized.LogIntegration = true; taskObj.Generalized.LogEvents = true; // If web farm support, create the tasks for all servers if (chkAllServers.Checked) { TaskInfoProvider.CreateWebFarmTasks(taskObj); } else { TaskInfoProvider.SetTaskInfo(taskObj); } if (cmsdesk) { URLHelper.Redirect("Task_Edit.aspx?taskname=" + taskObj.TaskID + "&saved=1&siteid=" + siteID); } else { URLHelper.Redirect("Task_Edit.aspx?taskname=" + taskObj.TaskID + "&saved=1&selectedsiteid=" + siteID); } } }
/// <summary> /// Handles the UniGrid's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that threw event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void gridElem_OnAction(string actionName, object actionArgument) { switch (actionName.ToLowerCSafe()) { case "edit": if (!String.IsNullOrEmpty(EditURL)) { URLHelper.Redirect(String.Format(EditURL, actionArgument)); } break; case "delete": { // Check "modify" permission if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.ScheduledTasks", "Modify")) { RedirectToAccessDenied("CMS.ScheduledTasks", "Modify"); } // Delete the task try { int taskId = Convert.ToInt32(actionArgument); TaskInfo ti = TaskInfoProvider.GetTaskInfo(taskId); if (ti != null) { ti.Generalized.LogSynchronization = SynchronizationTypeEnum.LogSynchronization; ti.Generalized.LogIntegration = true; ti.Generalized.LogEvents = true; TaskInfoProvider.DeleteTaskInfo(ti); } } catch (Exception ex) { ShowError(GetString("Task_List.DeleteError"), ex.Message); } } break; case "execute": { // Check "modify" permission if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.ScheduledTasks", "Modify")) { RedirectToAccessDenied("CMS.ScheduledTasks", "Modify"); } TaskInfo ti = TaskInfoProvider.GetTaskInfo(Convert.ToInt32(actionArgument)); if (ti != null) { SiteInfo si = SiteInfoProvider.GetSiteInfo(SiteID); if (!ti.TaskEnabled) { // Task is not enabled (won't be executed at the end of request), run it now SchedulingExecutor.ExecuteTask(ti.TaskID, (si != null) ? si.SiteName : SiteContext.CurrentSiteName); } else { TaskInterval interval = SchedulingHelper.DecodeInterval(ti.TaskInterval); if ((ti.TaskNextRunTime != DateTimeHelper.ZERO_TIME) || (interval.Period == SchedulingHelper.PERIOD_ONCE)) { ti.TaskNextRunTime = DateTime.Now; // Update the task TaskInfoProvider.SetTaskInfo(ti); // Run the task SchedulingTimer.RunSchedulerImmediately = true; if (si != null) { SchedulingTimer.SchedulerRunImmediatelySiteName = si.SiteName; } } else { ShowWarning(GetString("ScheduledTask.TaskAlreadyrunning")); return; } } ShowConfirmation(GetString("ScheduledTask.WasExecuted")); } } break; } }
/// <summary> /// Creates schedule interval string. /// </summary> protected override string EncodeInterval() { if (!TimeoutEnabled) { return(String.Empty); } TaskInterval ti = new TaskInterval(); string result = string.Empty; try { ti.Period = Mode; if (Mode != SchedulingHelper.PERIOD_ONCE) { result = new Validator().NotEmpty(txtQuantity.Text, GetString("timeoutselector.quantity.errorempty")).IsInteger(txtQuantity.Text, String.Format(GetString("timeoutselector.quantity.wrongformat"), QUANTITYMAXIMUM)).Result; if (String.IsNullOrEmpty(result)) { int quantity = ValidationHelper.GetInteger(txtQuantity.Text, -1); if ((quantity >= QuantityLowerBound) && (quantity <= QUANTITYMAXIMUM)) { ti.Every = quantity; } else { txtQuantity.ForeColor = Color.Red; } } } if (String.IsNullOrEmpty(result)) { switch (Mode) { case SchedulingHelper.PERIOD_MINUTE: case SchedulingHelper.PERIOD_HOUR: case SchedulingHelper.PERIOD_DAY: ti.BetweenStart = DateTime.MinValue; ti.BetweenEnd = DateTime.MaxValue; // Add all days to match the format AddWeekDays(ti); AddWeekEnd(ti); break; case SchedulingHelper.PERIOD_WEEK: if (rbNextDay.Checked) { ti.Order = drpNextOrder.SelectedValue; ti.Day = drpNextDay.SelectedValue; } break; case SchedulingHelper.PERIOD_MONTH: if (rbNextDate.Checked) { ti.Order = drpNextDate.SelectedValue; } else if (rbNextDay.Checked) { ti.Order = drpNextOrder.SelectedValue; ti.Day = drpNextDay.SelectedValue; } break; case SchedulingHelper.PERIOD_YEAR: if (rbNextDate.Checked) { ti.Order = drpNextDateMonth.SelectedValue; ti.Day = drpNextDate.SelectedValue; } break; case SchedulingHelper.PERIOD_ONCE: if (dateTimePicker.SelectedDateTime != DateTime.MinValue) { ti.StartTime = dateTimePicker.SelectedDateTime; } else { result = GetString("timeoutselector.errorinvaliddate"); } break; } // Add specific time to start date if (String.IsNullOrEmpty(result) && cbSpecificTime.Visible && cbSpecificTime.Checked) { //result = new Validator().NotEmpty(txtSpecificTimeHour.Text, GetString("timeoutselector.specifichour.errorempty")).IsInteger(txtSpecificTimeHour.Text, GetString("timeoutselector.specifichour.wrongformat")).NotEmpty(txtSpecificTimeMinute.Text, GetString("timeoutselector.specificminute.errorempty")).IsInteger(txtSpecificTimeMinute.Text, GetString("timeoutselector.specificminute.wrongformat")).Result; if (timePicker.IsValid()) { ti.StartTime = ti.StartTime.AddHours(timePicker.Time.Hour); ti.StartTime = ti.StartTime.AddMinutes(timePicker.Time.Minute); ti.UseSpecificTime = true; } else { result = timePicker.ErrorMessage; } } else { ti.UseSpecificTime = false; } } } catch (Exception ex) { ShowError(ex.Message); result = ex.Message; dateTimePicker.DateTimeTextBox.ForeColor = Color.Red; } if (!String.IsNullOrEmpty(result)) { AddError(result); return(null); } WeekListChecked = true; return(SchedulingHelper.EncodeInterval(ti)); }
/// <summary> /// Sets data to database. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Check "modify" permission if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.ScheduledTasks", "Modify")) { RedirectToAccessDenied("CMS.ScheduledTasks", "Modify"); } // Check required fields format string errorMessage = new Validator() .NotEmpty(txtTaskDisplayName.Text, rfvDisplayName.ErrorMessage) .NotEmpty(txtTaskName.Text, rfvName.ErrorMessage) .IsCodeName(txtTaskName.Text, GetString("Task_Edit.InvalidTaskName")) .MatchesCondition(schedInterval.StartTime.SelectedDateTime, DataTypeManager.IsValidDate, String.Format("{0} {1}.", GetString("BasicForm.ErrorInvalidDateTime"), DateTime.Now)) .Result; if ((errorMessage == String.Empty) && !schedInterval.CheckIntervalPreceedings()) { errorMessage = GetString("Task_Edit.BetweenIntervalPreceedingsError"); } if ((errorMessage == String.Empty) && !schedInterval.CheckOneDayMinimum()) { errorMessage = GetString("Task_Edit.AtLeastOneDayError"); } // Validate assembly, but only if task is enabled (so tasks for not-installed modules can be disabled) if ((errorMessage == String.Empty) && chkTaskEnabled.Checked && !assemblyElem.IsValid()) { errorMessage = assemblyElem.ErrorMessage; } // Checking date/time limit (SQL limit) if (errorMessage == String.Empty) { TaskInterval ti = SchedulingHelper.DecodeInterval(schedInterval.ScheduleInterval); if ((ti != null) && ((ti.StartTime < DataTypeManager.MIN_DATETIME) || (ti.StartTime > DataTypeManager.MAX_DATETIME))) { ti.StartTime = DateTime.Now; schedInterval.ScheduleInterval = SchedulingHelper.EncodeInterval(ti); } } // Check macro condition length if ((errorMessage == String.Empty) && (ucMacroEditor.Text.Length > 400)) { errorMessage = String.Format(GetString("task_edit.invalidlength"), 400); } if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); } else { // Check existing task name TaskInfo existingTask = TaskInfoProvider.GetTaskInfo(txtTaskName.Text.Trim(), SiteInfo != null ? SiteInfo.SiteName : null); if ((existingTask != null) && ((TaskInfo == null) || (existingTask.TaskID != TaskInfo.TaskID))) { ShowError(GetString("Task_Edit.TaskNameExists").Replace("%%name%%", existingTask.TaskName)); return; } if (TaskInfo == null) { // create new item -> insert TaskInfo = new TaskInfo { TaskSiteID = SiteID }; if (!developmentMode) { TaskInfo.TaskAllowExternalService = true; } } TaskInfo.TaskAssemblyName = assemblyElem.AssemblyName.Trim(); TaskInfo.TaskClass = assemblyElem.ClassName.Trim(); TaskInfo.TaskData = txtTaskData.Text.Trim(); TaskInfo.TaskName = txtTaskName.Text.Trim(); TaskInfo.TaskEnabled = chkTaskEnabled.Checked; TaskInfo.TaskDeleteAfterLastRun = chkTaskDeleteAfterLastRun.Checked; TaskInfo.TaskInterval = schedInterval.ScheduleInterval; TaskInfo.TaskDisplayName = txtTaskDisplayName.Text.Trim(); TaskInfo.TaskServerName = txtServerName.Text.Trim(); TaskInfo.TaskRunInSeparateThread = chkRunTaskInSeparateThread.Checked; TaskInfo.TaskUseExternalService = chkTaskUseExternalService.Checked; TaskInfo.TaskCondition = ucMacroEditor.Text; TaskInfo.TaskRunIndividuallyForEachSite = chkRunIndividually.Checked; if (plcAllowExternalService.Visible) { TaskInfo.TaskAllowExternalService = chkTaskAllowExternalService.Checked; } if (plcUseExternalService.Visible) { TaskInfo.TaskUseExternalService = chkTaskUseExternalService.Checked; } TaskInfo.TaskNextRunTime = SchedulingHelper.GetFirstRunTime(SchedulingHelper.DecodeInterval(TaskInfo.TaskInterval)); if (drpModule.Visible) { TaskInfo.TaskResourceID = ValidationHelper.GetInteger(drpModule.Value, 0); } TaskInfo.TaskUserID = ValidationHelper.GetInteger(ucUser.Value, 0); // Set synchronization to true (default is false for Scheduled task) TaskInfo.Generalized.StoreSettings(); TaskInfo.Generalized.LogSynchronization = SynchronizationTypeEnum.LogSynchronization; TaskInfo.Generalized.LogIntegration = true; TaskInfo.Generalized.LogEvents = true; // If web farm support, create the tasks for all servers if (chkAllServers.Checked) { TaskInfoProvider.CreateWebFarmTasks(TaskInfo); } else { TaskInfoProvider.SetTaskInfo(TaskInfo); } // Restore original settings TaskInfo.Generalized.RestoreSettings(); bool notSystem = (TaskInfo == null) || (TaskInfo.TaskType != ScheduledTaskTypeEnum.System); string url = UIContextHelper.GetElementUrl("CMS.ScheduledTasks", GetElementName(notSystem ? "EditTask" : "EditSystemTask"), true); // Add task ID and saved="1" query parameters url = URLHelper.AddParameterToUrl(String.Format(url, TaskInfo.TaskID), "saved", "1"); // Add site ID query parameter and redirect to the finished URL URLHelper.Redirect(URLHelper.AddParameterToUrl(url, "siteid", SiteID.ToString())); } }