Пример #1
0
 /// <summary>
 /// Closing the campaign
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 public static void ProcessOrders(int campaignID)
 {
     try
     {
         Campaign campaign = CampaignProvider.GetCampaigns()
                             .WhereEquals("NodeSiteID", SiteContext.CurrentSiteID)
                             .WhereEquals("CampaignID", campaignID)
                             .FirstObject;
         if (campaign != null)
         {
             var _failedOrders = DIContainer.Resolve <IFailedOrderStatusProvider>();
             _failedOrders.UpdateCampaignOrderStatus(campaign.CampaignID);
             TaskInfo runTask = TaskInfoProvider.GetTaskInfo(ScheduledTaskNames.PrebuyOrderCreation, SiteContext.CurrentSiteID);
             if (runTask != null)
             {
                 runTask.TaskRunInSeparateThread = true;
                 runTask.TaskEnabled             = true;
                 runTask.TaskData = $"{campaign.CampaignID}|{SiteContext.CurrentSiteID}";
                 SchedulingExecutor.ExecuteTask(runTask);
             }
             var users = UserInfoProvider.GetUsers();
             if (users != null)
             {
                 foreach (var user in users)
                 {
                     ProductEmailNotifications.CampaignEmail(campaign.DocumentName, user.Email, "CampaignCloseEmail");
                 }
             }
         }
     }
     catch (Exception ex)
     {
         EventLogProvider.LogException("Kadena_CMSWebParts_Kadena_Cart_FailedOrdersCheckout", "ProcessOrders", ex, SiteContext.CurrentSiteID, ex.Message);
     }
 }
Пример #2
0
 protected override void OnPreRender(EventArgs e)
 {
     // Get task data
     if (taskId > 0)
     {
         TaskInfo ti = TaskInfoProvider.GetTaskInfo(taskId);
         if (ti != null)
         {
             lblInfo.Text += String.Format(GetString("Task.LogTaskInfo"), HTMLHelper.HTMLEncode(ti.TaskTitle));
         }
     }
     // Get server data
     if (serverId > 0)
     {
         ServerInfo si = ServerInfoProvider.GetServerInfo(serverId);
         if (si != null)
         {
             if (lblInfo.Text != "")
             {
                 lblInfo.Text += "<br /><br />";
             }
             lblInfo.Text += String.Format(GetString("Task.LogServerInfo"), si.ServerDisplayName);
         }
     }
     lblInfo.Visible = (lblInfo.Text != "");
     base.OnPreRender(e);
 }
Пример #3
0
    /// <summary>
    /// Deletes selected tasks.
    /// </summary>
    protected void DeleteSelected(object parameter)
    {
        if (parameter == null)
        {
            return;
        }

        eventCode = "DELETESELECTEDDATA";
        ArrayList list = (ArrayList)parameter;

        CanceledString = GetString("Tasks.DeletionCanceled");
        try
        {
            AddLog(GetString("Synchronization.DeletingTasks"));

            foreach (string taskIdString in list)
            {
                int taskId = ValidationHelper.GetInteger(taskIdString, 0);
                if (taskId > 0)
                {
                    TaskInfo task = TaskInfoProvider.GetTaskInfo(taskId);

                    if (task != null)
                    {
                        AddLog(string.Format(ResHelper.GetAPIString("deletion.running", "Deleting '{0}' task"), HTMLHelper.HTMLEncode(task.TaskTitle)));
                        // Delete synchronization
                        SynchronizationInfoProvider.DeleteSynchronizationInfo(task, serverId, currentSiteId);
                    }
                }
            }

            CurrentInfo = GetString("Tasks.DeleteOK");
            AddLog(CurrentInfo);
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // Canceled by user
                CurrentInfo = CanceledString;
                AddLog(CurrentInfo);
            }
            else
            {
                CurrentError = GetString("Tasks.DeletionFailed");
                AddErrorLog(CurrentError);
            }
        }
        catch (Exception ex)
        {
            CurrentError = GetString("Tasks.DeletionFailed") + ": " + ex.Message;
            AddErrorLog(CurrentError);
        }
        finally
        {
            // Finalize log context
            FinalizeContext();
        }
    }
Пример #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        TaskInfo ti = TaskInfoProvider.GetTaskInfo(TaskId);

        // Set edited object
        EditedObject = ti;

        if (ti != null)
        {
            ((CMSDeskPage)Page).CurrentMaster.Title.TitleText += " (" + HTMLHelper.HTMLEncode(ti.TaskTitle) + ")";

            // Prepare task description
            StringBuilder sbTaskInfo = new StringBuilder();
            sbTaskInfo.Append("<table>");
            sbTaskInfo.Append("<tr><td class=\"Title Grid\" style=\"width:135px\">" + GetString("staging.tasktype") + "</td><td>" + ti.TaskType.ToString() + "</td></tr>");
            sbTaskInfo.Append("<tr><td class=\"Title Grid\">" + GetString("staging.tasktime") + "</td><td>" + ti.TaskTime.ToString() + "</td></tr>");
            sbTaskInfo.Append("<tr><td class=\"Title Grid\">" + GetString("staging.taskprocessedby") + "</td><td>" + DataHelper.GetNotEmpty(ti.TaskServers.Trim(';').Replace(";", ", "), "-") + "</td></tr>");
            sbTaskInfo.Append("</table>");

            string objectType = ti.TaskObjectType;
            if (ti.TaskNodeID > 0)
            {
                objectType = PredefinedObjectType.DOCUMENT;
            }
            viewDataSet.ObjectType        = objectType;
            viewDataSet.DataSet           = GetDataSet(ti.TaskData, ti.TaskType, ti.TaskObjectType);
            viewDataSet.AdditionalContent = sbTaskInfo.ToString();
        }
    }
Пример #5
0
    private string GetWaitingToSelectWinnerInfoMessage(IssueInfo issue, ABTestWinnerSelectionEnum winnerOption)
    {
        // Get current planned winner selection task
        var taskToSelectWinner         = TaskInfoProvider.GetTaskInfo(mABTest.TestWinnerScheduledTaskID);
        var plannedWinnerSelectionTime = taskToSelectWinner?.TaskNextRunTime ?? DateTimeHelper.ZERO_TIME;

        switch (winnerOption)
        {
        case ABTestWinnerSelectionEnum.Manual:
            if (issue.IssueMailoutTime > DateTime.Now)
            {
                return(String.Format(GetString("newsletterinfo.issuesentwaitingtosentwinner"), GetTimeOrNA(issue.IssueMailoutTime), GetWinnerSelectionTime()));
            }
            return(String.Format(GetString("newsletterinfo.issuesentwaitingtoselwinnermanually"), GetTimeOrNA(issue.IssueMailoutTime)));

        case ABTestWinnerSelectionEnum.OpenRate:
            return(String.Format(GetString("newsletterinfo.issuesentwaitingtoselwinneropen"), GetTimeOrNA(issue.IssueMailoutTime), GetTimeOrNA(plannedWinnerSelectionTime)));

        case ABTestWinnerSelectionEnum.TotalUniqueClicks:
            return(String.Format(GetString("newsletterinfo.issuesentwaitingtoselwinnerclicks"), GetTimeOrNA(issue.IssueMailoutTime), GetTimeOrNA(plannedWinnerSelectionTime)));

        default:
            return(null);
        }
    }
Пример #6
0
    /// <summary>
    /// Returns information message according to current state, issue and A/B test.
    /// </summary>
    /// <param name="currState">Current state</param>
    /// <param name="issue">Issue</param>
    /// <param name="winnerOption">Winner option</param>
    /// <param name="plannedMailoutTime">Planned mailout time</param>
    private string GetInfoMessage(int currState, IssueInfo issue, ABTestWinnerSelectionEnum winnerOption, DateTime plannedMailoutTime)
    {
        if (issue == null)
        {
            return(null);
        }

        switch (currState)
        {
        case STATE_WAITING_TO_SEND_WIZARD:
            return(null);

        case STATE_WAITING_TO_SEND_PAGE:
            return(GetString("Newsletter_Issue_Header.NotSentYet"));

        case STATE_TEST_WAITING_TO_SEL_WINNER:

            // Get current planned winner selection task
            var taskToSelectWinner         = TaskInfoProvider.GetTaskInfo(mABTest.TestWinnerScheduledTaskID);
            var plannedWinnerSelectionTime = (taskToSelectWinner == null) ? DateTimeHelper.ZERO_TIME : taskToSelectWinner.TaskNextRunTime;

            switch (winnerOption)
            {
            case ABTestWinnerSelectionEnum.Manual:
                if (issue.IssueMailoutTime > DateTime.Now)
                {
                    return(String.Format(GetString("newsletterinfo.issuesentwaitingtosentwinner"), GetTimeOrNA(issue.IssueMailoutTime), GetWinnerSelectionTime()));
                }
                return(String.Format(GetString("newsletterinfo.issuesentwaitingtoselwinnermanually"), GetTimeOrNA(issue.IssueMailoutTime)));

            case ABTestWinnerSelectionEnum.OpenRate:
                return(String.Format(GetString("newsletterinfo.issuesentwaitingtoselwinneropen"), GetTimeOrNA(issue.IssueMailoutTime), GetTimeOrNA(plannedWinnerSelectionTime)));

            case ABTestWinnerSelectionEnum.TotalUniqueClicks:
                return(String.Format(GetString("newsletterinfo.issuesentwaitingtoselwinnerclicks"), GetTimeOrNA(issue.IssueMailoutTime), GetTimeOrNA(plannedWinnerSelectionTime)));
            }
            break;

        case STATE_TEST_READY_FOR_SENDING:
            return(String.Format(GetString("newsletter_issue_header.issuesending"), GetTimeOrNA(plannedMailoutTime)));

        case STATE_TEST_FINISHED:
            switch (winnerOption)
            {
            case ABTestWinnerSelectionEnum.Manual:
                return(String.Format(GetString("newsletterinfo.issuesentwinnerselmanually"), GetTimeOrNA(issue.IssueMailoutTime), GetWinnerSelectionTime()));

            case ABTestWinnerSelectionEnum.OpenRate:
                return(String.Format(GetString("newsletterinfo.issuesentwinnerselopen"), GetWinnerSelectionTime()));

            case ABTestWinnerSelectionEnum.TotalUniqueClicks:
                return(String.Format(GetString("newsletterinfo.issuesentwinnerselclicks"), GetWinnerSelectionTime()));
            }
            break;
        }
        return(null);
    }
Пример #7
0
    /// <summary>
    /// Deletes scheduled task. Called when the "Delete task" button is pressed.
    /// Expects the CreateScheduledTask method to be run first.
    /// </summary>
    private bool DeleteScheduledTask()
    {
        // Get the scheduled task
        TaskInfo deleteTask = TaskInfoProvider.GetTaskInfo("MyNewTask", CMSContext.CurrentSiteID);

        // Delete the scheduled task
        TaskInfoProvider.DeleteTaskInfo(deleteTask);

        return(deleteTask != null);
    }
Пример #8
0
    private DateTime GetMailoutTimeFromScheduledTask(DataRowView rowView)
    {
        var taskId = ValidationHelper.GetInteger(rowView["IssueScheduledTaskID"], 0);
        var task = TaskInfoProvider.GetTaskInfo(taskId);
        if (task != null && task.TaskNextRunTime > DateTimeHelper.ZERO_TIME)
        {
            return task.TaskNextRunTime;
        }

        return DateTimeHelper.ZERO_TIME;
    }
Пример #9
0
    protected void gridTasks_OnAction(string actionName, object actionArgument)
    {
        // Parse action argument
        int taskId = ValidationHelper.GetInteger(actionArgument, 0);

        eventType = EventLogProvider.EVENT_TYPE_INFORMATION;

        if (taskId > 0)
        {
            TaskInfo task = TaskInfoProvider.GetTaskInfo(taskId);

            if (task != null)
            {
                switch (actionName.ToLower())
                {
                case "delete":
                    // Delete task
                    eventCode = "DELETESELECTEDDATA";
                    AddEventLog(string.Format(ResHelper.GetAPIString("deletion.running", "Deleting '{0}' task"), HTMLHelper.HTMLEncode(task.TaskTitle)));
                    SynchronizationInfoProvider.DeleteSynchronizationInfo(taskId, serverId, currentSiteId);
                    break;

                case "synchronize":
                    string result = null;
                    try
                    {
                        // Run task synchronization
                        eventCode = "SYNCSELECTEDDATA";
                        result    = StagingHelper.RunSynchronization(taskId, serverId, true, currentSiteId);

                        if (string.IsNullOrEmpty(result))
                        {
                            lblInfo.Text = GetString("Tasks.SynchronizationOK");
                        }
                        else
                        {
                            lblError.Text = GetString("Tasks.SynchronizationFailed");
                            eventType     = EventLogProvider.EVENT_TYPE_ERROR;
                        }
                    }
                    catch (Exception ex)
                    {
                        result        = ex.Message;
                        lblError.Text = GetString("Tasks.SynchronizationFailed");
                        eventType     = EventLogProvider.EVENT_TYPE_ERROR;
                    }
                    // Log message
                    AddEventLog(result + string.Format(ResHelper.GetAPIString("synchronization.running", "Processing '{0}' task"), HTMLHelper.HTMLEncode(task.TaskTitle)));
                    break;
                }
            }
        }
    }
 /// <summary>
 /// Loads controls with values from existing score.
 /// </summary>
 /// <param name="score"></param>
 private void LoadValuesFromExistingScore(ScoreInfo score)
 {
     if (score.ScoreScheduledTaskID > 0)
     {
         TaskInfo taskInfo = TaskInfoProvider.GetTaskInfo(score.ScoreScheduledTaskID);
         if ((taskInfo != null) && taskInfo.TaskEnabled)
         {
             radLater.Checked                 = true;
             calendarControl.Enabled          = true;
             calendarControl.SelectedDateTime = taskInfo.TaskNextRunTime;
         }
     }
 }
Пример #11
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string url = UIContextHelper.GetElementUrl("CMS.OnlineMarketing", "EditContactGroup");

        url = URLHelper.AddParameterToUrl(url, "displayTitle", "false");
        url = URLHelper.AddParameterToUrl(url, "objectId", "{%EditedObject.ID%}");
        url = URLHelper.AddParameterToUrl(url, "saved", "1");
        url = URLHelper.AddParameterToUrl(url, "siteid", SiteID.ToString());

        if (ContactHelper.IsSiteManager)
        {
            url = URLHelper.AddParameterToUrl(url, "issitemanager", "1");
        }
        EditForm.RedirectUrlAfterCreate = url;

        // Get edited contact group
        ContactGroupInfo cgi = (ContactGroupInfo)EditForm.EditedObject;

        // Get scheduled task
        if (cgi.ContactGroupScheduledTaskID > 0)
        {
            task = TaskInfoProvider.GetTaskInfo(cgi.ContactGroupScheduledTaskID);
        }

        if (!RequestHelper.IsPostBack())
        {
            // Hide dialog for condition when creating new contact group
            plcUpdate.Visible = (cgi.ContactGroupID > 0);

            chkSchedule.Checked = schedulerInterval.Visible = ((task != null) && task.TaskEnabled);

            if (schedulerInterval.Visible)
            {
                // Initialize interval control
                schedulerInterval.ScheduleInterval = task.TaskInterval;
            }
        }

        // Set proper resolver to condition builder
        conditionBuilder.ResolverName = "ContactResolver";

        if (task != null)
        {
            // Display info panel for dynamic contact group
            pnlInfo.Visible = true;

            // Display basic info about dynamic contact group
            InitInfoPanel(cgi, false);
        }
    }
Пример #12
0
    /// <summary>
    /// Returns scheduled task of the contact group or creates new one.
    /// </summary>
    /// <param name="cgi">Contact group info</param>
    private TaskInfo GetScheduledTask(ContactGroupInfo cgi)
    {
        if (cgi == null)
        {
            return(null);
        }

        if (cgi.ContactGroupScheduledTaskID > 0)
        {
            return(TaskInfoProvider.GetTaskInfo(ValidationHelper.GetInteger(cgi.ContactGroupScheduledTaskID, 0)) ??
                   CreateScheduledTask(cgi));
        }

        return(CreateScheduledTask(cgi));
    }
Пример #13
0
    /// <summary>
    /// Runs scheduled task. Called when the "Run task" button is pressed.
    /// Expects the CreateScheduledTask method to be run first.
    /// </summary>
    private bool RunTask()
    {
        // Get the scheduled task
        TaskInfo runTask = TaskInfoProvider.GetTaskInfo("MyNewTask", CMSContext.CurrentSiteID);

        if (runTask != null)
        {
            // Run task
            SchedulingExecutor.ExecuteTask(runTask);

            return(true);
        }

        return(false);
    }
Пример #14
0
    /// <summary>
    /// Actions handler.
    /// </summary>
    protected void HeaderActions_ActionPerformed(object sender, CommandEventArgs e)
    {
        if (ContactGroupHelper.AuthorizedModifyContactGroup(this.SiteID, true))
        {
            switch (e.CommandName.ToLower())
            {
            case "save":
                // Save changes in the contact group
                EditForm.SaveData(null);
                break;

            case "evaluate":
                if (EditForm.EditedObject != null)
                {
                    ContactGroupInfo cgi = (ContactGroupInfo)EditForm.EditedObject;
                    if (cgi != null)
                    {
                        // Set 'Rebuilding' status
                        cgi.ContactGroupStatus = ContactGroupStatusEnum.Rebuilding;
                        ContactGroupInfoProvider.SetContactGroupInfo(cgi);

                        // Evaluate the membership of the contact group
                        ContactGroupEvaluator evaluator = new ContactGroupEvaluator();
                        evaluator.ContactGroupID = cgi.ContactGroupID;
                        evaluator.Execute(null);

                        EditForm.InfoLabel.Text    = GetString("om.contactgroup.evaluationstarted");
                        EditForm.InfoLabel.Visible = true;

                        // Get scheduled task and update last run time
                        if (cgi.ContactGroupScheduledTaskID > 0)
                        {
                            task = TaskInfoProvider.GetTaskInfo(cgi.ContactGroupScheduledTaskID);
                            if (task != null)
                            {
                                task.TaskLastRunTime = DateTime.Now;
                                TaskInfoProvider.SetTaskInfo(task);
                            }
                        }

                        // Display basic info about dynamic contact group
                        InitInfoPanel(cgi, false);
                    }
                }
                break;
            }
        }
    }
Пример #15
0
    /// <summary>
    /// Returns scheduled task of the contact group or creates new one.
    /// </summary>
    /// <param name="score">Score info</param>
    private TaskInfo GetScheduledTask(ScoreInfo score)
    {
        if (score == null)
        {
            return(null);
        }

        if (score.ScoreScheduledTaskID > 0)
        {
            return(TaskInfoProvider.GetTaskInfo(ValidationHelper.GetInteger(score.ScoreScheduledTaskID, 0)) ??
                   CreateScheduledTask(score));
        }
        else
        {
            return(CreateScheduledTask(score));
        }
    }
 /// <summary>
 /// Closing the campaign
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void lnkCloseCampaign_Click(object sender, EventArgs e)
 {
     try
     {
         LinkButton btn        = (LinkButton)sender;
         int        campaignID = ValidationHelper.GetInteger(btn.CommandArgument, 0);
         if (!DIContainer.Resolve <IShoppingCartProvider>().ValidateAllCarts(campaignID: campaignID))
         {
             Response.Cookies["status"].Value    = QueryStringStatus.InvalidCartItems;
             Response.Cookies["status"].HttpOnly = false;
             return;
         }
         Campaign campaign = CampaignProvider.GetCampaigns()
                             .WhereEquals("NodeSiteID", CurrentSite.SiteID)
                             .WhereEquals("CampaignID", campaignID)
                             .FirstObject;
         if (campaign != null)
         {
             campaign.CloseCampaign = true;
             campaign.Update();
             var oderStatus = DIContainer.Resolve <IFailedOrderStatusProvider>();
             oderStatus.InsertCampaignOrdersInProgress(campaign.CampaignID);
             TaskInfo runTask = TaskInfoProvider.GetTaskInfo(ScheduledTaskNames.PrebuyOrderCreation, CurrentSite.SiteID);
             if (runTask != null)
             {
                 runTask.TaskRunInSeparateThread = true;
                 runTask.TaskEnabled             = true;
                 runTask.TaskData = $"{campaign.CampaignID}|{CurrentUser.UserID}";
                 SchedulingExecutor.ExecuteTask(runTask);
             }
             var users = UserInfoProvider.GetUsers();
             if (users != null)
             {
                 foreach (var user in users)
                 {
                     ProductEmailNotifications.CampaignEmail(campaign.DocumentName, user.Email, "CampaignCloseEmail");
                 }
             }
             Response.Redirect(CurrentDocument.DocumentUrlPath);
         }
     }
     catch (Exception ex)
     {
         EventLogProvider.LogException("CMSWebParts_Kadena_Campaign_Web_Form_CampaignWebFormActions", "lnkCloseCampaign_Click", ex, CurrentSite.SiteID, ex.Message);
     }
 }
Пример #17
0
    /// <summary>
    /// Gets and updates scheduled task. Called when the "Get and update task" button is pressed.
    /// Expects the CreateScheduledTask method to be run first.
    /// </summary>
    private bool GetAndUpdateScheduledTask()
    {
        // Get the scheduled task
        TaskInfo updateTask = TaskInfoProvider.GetTaskInfo("MyNewTask", CMSContext.CurrentSiteID);

        if (updateTask != null)
        {
            // Update the properties
            updateTask.TaskDisplayName = updateTask.TaskDisplayName.ToLower();

            // Save the changes
            TaskInfoProvider.SetTaskInfo(updateTask);

            return(true);
        }

        return(false);
    }
    /// <summary>
    /// Shows warning message if score needs to be rebuilt.
    /// </summary>
    private void InitWarnings()
    {
        ScoreInfo info = ScoreInfoProvider.GetScoreInfo(ScoreId);

        // Do nothing if recalculation is already scheduled
        if (info.ScoreScheduledTaskID > 0)
        {
            TaskInfo taskInfo = TaskInfoProvider.GetTaskInfo(info.ScoreScheduledTaskID);
            if (taskInfo != null && taskInfo.TaskEnabled)
            {
                return;
            }
        }

        if (info.ScoreStatus == ScoreStatusEnum.RecalculationRequired)
        {
            ShowInformation(GetString(mRecalculationNeededResourceString));
        }
    }
Пример #19
0
    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;
    }
        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.GetTaskInfo(taskName, site.SiteID);

            if (scheduledTask != null)
            {
                return;
            }

            var currentServerName = WebFarmHelper.ServerName;
            var taskServerName    = mWebFarmService.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.DancingGoat.Samples",
                TaskClass               = "CMS.DancingGoat.Samples.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
            };

            TaskInfoProvider.SetTaskInfo(task);
        }
Пример #21
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get edited score
        ScoreInfo score = (ScoreInfo)EditForm.EditedObject;

        // Get scheduled task
        if (score.ScoreScheduledTaskID > 0)
        {
            task = TaskInfoProvider.GetTaskInfo(score.ScoreScheduledTaskID);
        }

        if (!RequestHelper.IsPostBack())
        {
            // Hide advanced properties when creating new score
            plcUpdate.Visible = (score.ScoreID > 0);

            chkSchedule.Checked = schedulerInterval.Visible = ((task != null) && task.TaskEnabled);

            if (schedulerInterval.Visible)
            {
                // Initialize interval control
                schedulerInterval.ScheduleInterval = task.TaskInterval;
            }
        }

        if (score.ScoreID > 0)
        {
            // Display info panel
            pnlInfo.Visible = true;

            // Display basic info about score
            InitInfoPanel(score);
        }

        // Set tab name of editing UI to refresh upon change
        EditForm.RefreshTab = GetString("general.general");

        // Allow multiple addresses in e-mail input control
        fEmail.EditingControl.SetValue("allowmultipleaddresses", true);
    }
Пример #22
0
    /// <summary>
    /// Synchronization of selected items.
    /// </summary>
    /// <param name="parameter">ArrayList of selected items</param>
    public void SynchronizeSelected(object parameter)
    {
        if (parameter == null)
        {
            return;
        }

        string result = string.Empty;

        eventCode = "SYNCSELECTEDDATA";
        ArrayList list = (ArrayList)parameter;

        CanceledString = GetString("Tasks.SynchronizationCanceled");
        try
        {
            AddLog(GetString("Synchronization.RunningTasks"));

            foreach (string taskIdString in list)
            {
                int taskId = ValidationHelper.GetInteger(taskIdString, 0);
                if (taskId > 0)
                {
                    // Synchronize the task
                    TaskInfo task = TaskInfoProvider.GetTaskInfo(taskId);
                    if (task != null)
                    {
                        AddLog(string.Format(ResHelper.GetAPIString("synchronization.running", "Processing '{0}' task"), HTMLHelper.HTMLEncode(task.TaskTitle)));
                        result += StagingHelper.RunSynchronization(taskId, serverId, true, currentSiteId);
                    }
                }
            }

            // Log possible error
            if (result != string.Empty)
            {
                CurrentError = GetString("Tasks.SynchronizationFailed");
                AddErrorLog(CurrentError, null);
            }
            else
            {
                CurrentInfo = GetString("Tasks.SynchronizationOK");
                AddLog(CurrentInfo);
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // Canceled by user
                CurrentInfo = CanceledString;
                AddLog(CurrentInfo);
            }
            else
            {
                CurrentError = GetString("Tasks.SynchronizationFailed");
                AddErrorLog(CurrentError, result);
            }
        }
        catch (Exception ex)
        {
            CurrentError = GetString("Tasks.SynchronizationFailed") + ": " + ex.Message;
            AddErrorLog(CurrentError);
        }
        finally
        {
            // Finalize log context
            FinalizeContext();
        }
    }
    /// <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(UrlResolver.ResolveUrl(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 taskInfo = TaskInfoProvider.GetTaskInfo(Convert.ToInt32(actionArgument));
            if (taskInfo != null)
            {
                SiteInfo siteInfo = SiteInfoProvider.GetSiteInfo(SiteID);
                if (!taskInfo.TaskEnabled)
                {
                    // Task is not enabled (won't be executed at the end of request), run it now
                    SchedulingExecutor.ExecuteTask(taskInfo, (siteInfo != null) ? siteInfo.SiteName : SiteContext.CurrentSiteName);
                }
                else
                {
                    if (!taskInfo.TaskIsRunning)
                    {
                        taskInfo.TaskNextRunTime = DateTime.Now;

                        // Update the task
                        TaskInfoProvider.SetTaskInfo(taskInfo);

                        // Run the task
                        SchedulingTimer.RunSchedulerImmediately = true;
                        if (siteInfo != null)
                        {
                            SchedulingTimer.SchedulerRunImmediatelySiteName = siteInfo.SiteName;
                        }
                    }
                    else
                    {
                        ShowWarning(GetString("ScheduledTask.TaskAlreadyrunning"));
                        return;
                    }
                }

                ShowConfirmation(GetString("ScheduledTask.WasExecuted"));
            }
        }
        break;
        }
    }
Пример #24
0
    /// <summary>
    /// Actions handler.
    /// </summary>
    protected void HeaderActions_ActionPerformed(object sender, CommandEventArgs e)
    {
        // Check modify permission
        CheckPermissions("cms.scoring", "modify");

        switch (e.CommandName.ToLower())
        {
        case "save":
            // Save changes in the contact group
            EditForm.SaveData(null);
            break;

        case "recalculate":
            if (EditForm.EditedObject != null)
            {
                ScoreInfo score = (ScoreInfo)EditForm.EditedObject;
                if (score != null)
                {
                    // Set 'Recalculating' status
                    score.ScoreStatus = ScoreStatusEnum.Recalculating;
                    // Ensure scheduled task
                    if (score.ScoreScheduledTaskID == 0)
                    {
                        // Create and initialize new scheduled task
                        task = GetScheduledTask(score);
                        task.TaskInterval    = schedulerInterval.ScheduleInterval;
                        task.TaskNextRunTime = TaskInfoProvider.NO_TIME;
                        task.TaskEnabled     = false;
                        TaskInfoProvider.SetTaskInfo(task);

                        // Update score info
                        score.ScoreScheduledTaskID = task.TaskID;
                    }
                    ScoreInfoProvider.SetScoreInfo(score);

                    // Recalculate the score
                    ScoreEvaluator evaluator = new ScoreEvaluator();
                    evaluator.ScoreID = score.ScoreID;
                    evaluator.Execute(null);

                    EditForm.InfoLabel.Text    = GetString("om.score.recalculationstarted");
                    EditForm.InfoLabel.Visible = true;

                    // Get scheduled task and update last run time
                    if (task == null)
                    {
                        task = TaskInfoProvider.GetTaskInfo(score.ScoreScheduledTaskID);
                    }
                    if (task != null)
                    {
                        task.TaskLastRunTime = DateTime.Now;
                        TaskInfoProvider.SetTaskInfo(task);
                    }

                    // Display basic info about score
                    InitInfoPanel(score);
                }
            }
            break;
        }
    }
Пример #25
0
    protected object grdElem_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName)
        {
        case "IssueVariantName":
        {
            DataRowView drv    = (DataRowView)parameter;
            string      result = ValidationHelper.GetString(drv["IssueVariantName"], string.Empty);

            // Issue has not been sent yet => get mail out time from scheduled task
            if (ValidationHelper.GetInteger(drv["IssueID"], 0) == WinnerIssueID)
            {
                result += " " + GetString("newsletterabtest.winner");
            }

            return(result);
        }

        case "MailoutTime":
        {
            string      result = null;
            DataRowView drv    = (DataRowView)parameter;
            DateTime    dt     = ValidationHelper.GetDateTime(drv["IssueMailoutTime"], DateTimeHelper.ZERO_TIME);

            if (dt == DateTimeHelper.ZERO_TIME)
            {
                // Issue has not been sent yet => get mail out time from scheduled task
                int      taskId = ValidationHelper.GetInteger(drv["IssueScheduledTaskID"], 0);
                TaskInfo task   = TaskInfoProvider.GetTaskInfo(taskId);
                if (task != null)
                {
                    if (task.TaskNextRunTime < DateTime.Now)
                    {
                        result = String.Format("{0} {1}", task.TaskNextRunTime.ToString(), GetString("newsletterissue_send.asap"));
                    }
                    else
                    {
                        result = task.TaskNextRunTime.ToString();
                    }
                    dt = task.TaskNextRunTime;
                }
                else
                {
                    result = GetString("general.na");
                }
            }
            else
            {
                result = dt.ToString();
            }

            if (mHighestMailoutTime < dt)
            {
                mHighestMailoutTime = dt;
            }

            return(result);
        }

        case "IssueStatus":
            IssueStatusEnum status = IssueStatusEnum.Idle;
            if ((parameter != DBNull.Value) && (parameter != null))
            {
                status = (IssueStatusEnum)parameter;
            }
            return(IssueHelper.GetStatusFriendlyName(status, null));

        case "IssueOpenedEmails":
            return(GetOpenedEmails(parameter as DataRowView));

        case "UniqueClicks":
            int issueId = ValidationHelper.GetInteger(parameter, 0);
            return(GetUniqueClicks(IssueHelper.GetIssueTotalUniqueClicks(issueId), issueId));
        }
        return(parameter);
    }
Пример #26
0
    /// <summary>
    /// Gets formatted score status. Score can be disabled, it can be scheduled to rebuild in the future or its status is one of <see cref="ScoreStatusEnum"/>.
    /// </summary>
    private void InitWarnings(int scoreID)
    {
        var info = ScoreInfoProvider.GetScoreInfo(scoreID);

        if (info == null)
        {
            return;
        }

        // "Recalculation scheduled" status
        if (info.ScoreScheduledTaskID > 0)
        {
            TaskInfo taskInfo = TaskInfoProvider.GetTaskInfo(info.ScoreScheduledTaskID);
            if (taskInfo != null && taskInfo.TaskEnabled)
            {
                ShowInformation(String.Format(GetString("om.score.recalculatescheduledat"), taskInfo.TaskNextRunTime.ToString()));
                mButtonRecalculate.Enabled = true;
                return;
            }
        }

        // Other statuses
        switch (info.ScoreStatus)
        {
        case ScoreStatusEnum.Ready:
            // Score should be up to date, no need to inform user about anything
            if (info.ScoreEnabled)
            {
                mButtonRecalculate.Tooltip = GetString(mRecalculationNotNeededTooltipResourceString);
            }
            else
            {
                mButtonRecalculate.Enabled = true;
            }
            break;

        case ScoreStatusEnum.RecalculationRequired:
            ShowInformation(GetString(mRecalculationNeededResourceString));
            mButtonRecalculate.Enabled = true;
            break;

        case ScoreStatusEnum.Recalculating:
            ShowInformation(GetString("om.score.recalculationstarted2"));
            gridElem.GridView.Enabled = false;
            break;

        case ScoreStatusEnum.RecalculationFailed:
            ShowInformation(GetString("om.score.recalcfailed"));
            mButtonRecalculate.Enabled = true;
            break;

        default:
        case ScoreStatusEnum.Unspecified:
            throw new Exception("[RuleList.InitInformation]: Score status not specified.");
        }

        if ((ModifyPermissions != null) && !ModifyPermissions.Value)
        {
            mButtonRecalculate.Enabled = false;
            mButtonRecalculate.Tooltip = GetString("general.modifynotallowed");
        }
    }
Пример #27
0
    /// <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);
            }
        }
    }
Пример #28
0
    /// <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;
        }
    }
Пример #29
0
    /// <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()));
        }
    }
Пример #30
0
    protected void Page_Load(object sender, EventArgs e)
    {
        rfvAssembly.ErrorMessage    = GetString("Task_Edit.EmptyAssembly");
        rfvDisplayName.ErrorMessage = GetString("general.requiresdisplayname");
        rfvName.ErrorMessage        = GetString("Task_Edit.EmptyName");
        rfvClass.ErrorMessage       = GetString("Task_Edit.EmptyClass");

        // Control initializations
        lblTaskAssemblyName.Text = GetString("Task_Edit.TaskAssemblyNameLabel");

        lblTaskClass.Text              = GetString("Task_Edit.TaskClassLabel");
        lblTaskData.Text               = GetString("Task_Edit.TaskDataLabel");
        lblTaskName.Text               = GetString("Task_Edit.TaskNameLabel");
        lblTaskEnabled.Text            = GetString("Task_Edit.TaskEnabledLabel");
        lblTaskInterval.Text           = GetString("Task_Edit.TaskIntervalLabel");
        lblTaskDisplayName.Text        = GetString("Task_Edit.TaskDisplayNameLabel");
        lblTaskDeleteAfterLastRun.Text = GetString("Task_Edit.TaskDeleteAfterLastRunLabel");
        lblServerName.Text             = GetString("Task_Edit.TaskServerNameLabel");
        chkAllServers.Text             = GetString("Task_Edit.TaskAllServers");

        plcDevelopment.Visible = developmentMode;
        // Show 'Allow run in external service' checkbox in development mode
        plcAllowExternalService.Visible = developmentMode;

        btnOk.Text = GetString("General.OK");

        string currentTask = GetString("Task_Edit.NewItemCaption");
        string title       = GetString("Task_Edit.HeaderCaption");

        taskId = ValidationHelper.GetInteger(Request.QueryString["taskname"], 0);
        if (taskId > 0)
        {
            taskObj = TaskInfoProvider.GetTaskInfo(taskId);
            if (taskObj != null)
            {
                // Global task and user is not global administrator and task's site id is different than current site id
                if (!CMSContext.CurrentUser.UserSiteManagerAdmin && ((taskObj.TaskSiteID == 0) || (taskObj.TaskSiteID != SiteID)))
                {
                    RedirectToAccessDenied(GetString("general.nopermission"));
                }

                currentTask = taskObj.TaskDisplayName;
                title       = GetString("Task_Edit.HeaderCaptionEdit");

                if (!RequestHelper.IsPostBack())
                {
                    ReloadData();

                    // Show that the task was created or updated successfully
                    if (Request.QueryString["saved"] == "1")
                    {
                        lblInfo.Visible = true;
                        lblInfo.Text    = GetString("General.ChangesSaved");
                    }
                }
            }
        }
        else
        {
            // Check "modify" permission
            if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.ScheduledTasks", "Modify"))
            {
                RedirectToAccessDenied("CMS.ScheduledTasks", "Modify");
            }

            if (WebFarmServerInfoProvider.UseWebFarmSynchronization())
            {
                if (!RequestHelper.IsPostBack())
                {
                    chkAllServers.Visible = true;
                }
                chkAllServers.Attributes.Add("onclick", "document.getElementById('" + txtServerName.ClientID + "').disabled = document.getElementById('" + chkAllServers.ClientID + "').checked;");
            }
        }

        siteID = 0;
        if (SiteID != 0)
        {
            cmsdesk = true;
            siteID  = SiteID;
        }

        if (SelectedSiteID != 0)
        {
            cmsdesk = false;
            if (Request.QueryString["selectedsiteid"] != "Global")
            {
                siteID = SelectedSiteID;
            }
        }

        // Get the site record
        if (siteID > 0)
        {
            si = SiteInfoProvider.GetSiteInfo(siteID);
        }

        // Initializes page title control
        string[,] tabs = new string[2, 3];
        tabs[0, 0]     = GetString("Task_Edit.ItemListLink");
        if (cmsdesk)
        {
            tabs[0, 1] = "~/CMSModules/Scheduler/Pages/Task_List.aspx?siteid=" + siteID;
        }
        else
        {
            tabs[0, 1] = "~/CMSModules/Scheduler/Pages/Task_List.aspx?selectedsiteid=" + siteID;
        }

        tabs[1, 0] = currentTask;
        tabs[1, 1] = "";
        tabs[1, 2] = "";
        this.CurrentMaster.Title.Breadcrumbs = tabs;

        // Setup page title text and image
        this.CurrentMaster.Title.TitleText     = title;
        this.CurrentMaster.Title.TitleImage    = GetImageUrl("Objects/CMS_ScheduledTask/new.png");
        this.CurrentMaster.Title.HelpTopicName = "newedit_task";
        this.CurrentMaster.Title.HelpName      = "helpTopic";
    }