예제 #1
0
        public ComponentInfo(TaskInfo componentInfo)
        {
            this.id = componentInfo.ID;
            this.name = componentInfo.Name;
            this.creationName = componentInfo.CreationName;

            Assembly assembly = ComponentInfo.GetComponentAssembly(componentInfo);

            if (assembly != null)
            {
                Stream iconStream = assembly.GetManifestResourceStream(componentInfo.IconResource);
                if (iconStream != null)
                {
                    this.icon = new Icon(iconStream, new Size(16, 16));
                }
            }
            else
            {
                int index = 0;
                Int32.TryParse(componentInfo.IconResource, out index);
                this.icon = ExtractIcon(componentInfo.IconFile, index, false);
            }

            // Ensure we always have an icon
            if (this.icon == null)
            {
                this.icon = BIDSHelper.Resources.Common.NoIcon;
            }
        }
예제 #2
0
        public string Parse(TaskInfo info, string pattern)
        {
            if (info != null && !string.IsNullOrEmpty(pattern))
            {
                pattern = Parse(pattern);

                if (info.Result != null)
                {
                    string result = info.Result.ToString();

                    if (string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(info.FilePath))
                    {
                        result = info.FilePath;
                    }

                    pattern = pattern.Replace("$result", result ?? "");
                    pattern = pattern.Replace("$url", info.Result.URL ?? "");
                    pattern = pattern.Replace("$shorturl", info.Result.ShortenedURL ?? "");
                    pattern = pattern.Replace("$thumbnailurl", info.Result.ThumbnailURL ?? "");
                    pattern = pattern.Replace("$deletionurl", info.Result.DeletionURL ?? "");
                }

                pattern = pattern.Replace("$filenamenoext", !string.IsNullOrEmpty(info.FileName) ? Path.GetFileNameWithoutExtension(info.FileName) : "");
                pattern = pattern.Replace("$filename", info.FileName ?? "");
                pattern = pattern.Replace("$filepath", info.FilePath ?? "");
                pattern = pattern.Replace("$folderpath", !string.IsNullOrEmpty(info.FilePath) ? Path.GetDirectoryName(info.FilePath) : "");
                pattern = pattern.Replace("$foldername", !string.IsNullOrEmpty(info.FilePath) ? Path.GetFileName(Path.GetDirectoryName(info.FilePath)) : "");
                pattern = pattern.Replace("$thumbnailfilenamenoext", !string.IsNullOrEmpty(info.ThumbnailFilePath) ? Path.GetFileNameWithoutExtension(info.ThumbnailFilePath) : "");
                pattern = pattern.Replace("$thumbnailfilename", !string.IsNullOrEmpty(info.ThumbnailFilePath) ? Path.GetFileName(info.ThumbnailFilePath) : "");

                pattern = pattern.Replace("$uploadtime", ((int)info.UploadDuration.TotalMilliseconds).ToString());
            }

            return pattern;
        }
        /// <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);
        }
예제 #4
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <param name="ti">Task info</param>
        public string Execute(TaskInfo ti)
        {
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "MyTask", "Execute", null, "This task was executed from '~/App_Code/Global/CMS/CMSCustom.cs'.");

            return null;
        }
예제 #5
0
 private void LookForNexttask()
 {
     TaskInfo taskInfo = new TaskInfo();
     if (tasks.TryPop(out taskInfo))
     {
         CreateTask(taskInfo.ID, taskInfo.TileBounds);
     }
 }
예제 #6
0
        public BeforeUploadForm(TaskInfo info)
        {
            InitializeComponent();
            DialogResult = DialogResult.OK;

            ucBeforeUpload.InitCompleted += currentDestination =>
            {
                string title = string.IsNullOrEmpty(currentDestination) ? Resources.BeforeUploadForm_BeforeUploadForm_Please_choose_a_destination_ :
                    Resources.BeforeUploadForm_BeforeUploadForm__0__is_about_to_be_uploaded_to__1___You_may_choose_a_different_destination_;
                lblTitle.Text = string.Format(title, info.FileName, currentDestination);
                pbPreview.LoadImageFromFileAsync(info.FilePath);
            };

            ucBeforeUpload.Init(info);
        }
예제 #7
0
        public AfterUploadForm(TaskInfo info)
        {
            InitializeComponent();
            Info = info;
            if (Info.TaskSettings.AdvancedSettings.AutoCloseAfterUploadForm) tmrClose.Start();

            bool isFileExist = !string.IsNullOrEmpty(info.FilePath) && File.Exists(info.FilePath);

            if (info.DataType == EDataType.Image)
            {
                if (isFileExist)
                {
                    pbPreview.LoadImageFromFileAsync(info.FilePath);
                }
                else
                {
                    pbPreview.LoadImageFromURLAsync(info.Result.URL);
                }
            }

            Text = "ShareXYZ - " + (isFileExist ? info.FilePath : info.FileName);

            lvClipboardFormats.Groups.Add(lvgForums);
            lvClipboardFormats.Groups.Add(lvgHtml);
            lvClipboardFormats.Groups.Add(lvgWiki);
            lvClipboardFormats.Groups.Add(lvgLocal);
            lvClipboardFormats.Groups.Add(lvgCustom);

            foreach (LinkFormatEnum type in Helpers.GetEnums<LinkFormatEnum>())
            {
                if (!Helpers.IsImageFile(Info.Result.URL) &&
                    (type == LinkFormatEnum.HTMLImage || type == LinkFormatEnum.HTMLLinkedImage ||
                    type == LinkFormatEnum.ForumImage || type == LinkFormatEnum.ForumLinkedImage ||
                    type == LinkFormatEnum.WikiImage || type == LinkFormatEnum.WikiLinkedImage))
                    continue;

                AddFormat(type.GetLocalizedDescription(), GetUrlByType(type));
            }

            if (Helpers.IsImageFile(Info.Result.URL))
            {
                foreach (ClipboardFormat cf in Program.Settings.ClipboardContentFormats)
                {
                    AddFormat(cf.Description, parser.Parse(Info, cf.Format), lvgCustom);
                }
            }
        }
예제 #8
0
        public void addTaskView(TaskInfo task)
        {
            taskList.BeginUpdate();
            ListViewItem item = new ListViewItem();

            item.Text = "";

            item.SubItems.Add(task.id);
            item.SubItems.Add(task.name);
            item.SubItems.Add(task.estimate);
            item.SubItems.Add(task.consumed);
            item.SubItems.Add(task.left);
            item.SubItems.Add("").Tag = task.isDone;

            taskList.Items.Add(item);
            taskList.EndUpdate();
        }
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <param name="ti">Info object representing the scheduled task</param>
        public string Execute(TaskInfo task)
        {
            try
            {

                get_query_task(task);

                return null;

            }

            catch (Exception ex)
            {

                return (ex.Message);

            }
        }
        public void ProcessRequest(HttpContext context)
        {
            ResourceLevelingDataSource.ResourceInfo = new List<ASPNetGanttDemo.DataSources.ResourceInfo>()
               {
              new ASPNetGanttDemo.DataSources.ResourceInfo(){ ResourceID = 1, ResourceName = "Resource 1" },
              new ASPNetGanttDemo.DataSources.ResourceInfo(){ ResourceID = 2, ResourceName = "Resource 2", CustomScheduleString = "Mon 8:00:00 16:00:00;Tue 8:00:00 16:00:00;Wed 8:00:00 16:00:00" },
              new ASPNetGanttDemo.DataSources.ResourceInfo(){ ResourceID = 3, ResourceName = "Resource 3" }
            };

            List<TaskInfo> taskItems = new List<TaskInfo>();

            for (int i = 0; i <= 30; i++)
            {
                TaskInfo ti = new TaskInfo() { Name = "Task " + i, ID = i + 1, StartTime = DateTime.Today, Effort = TimeSpan.Parse("8:00:00").ToString(), Description = "Description of Task " + i };
                if (Decimal.Remainder(i, 8) == 0)
                    ti.Resources = ResourceInfo[0].ResourceID + "," + ResourceInfo[1].ResourceID + "[50%]";
                else if (Decimal.Remainder(i, 4) == 0)
                    ti.Resources = ResourceInfo[0].ResourceID + "," + ResourceInfo[1].ResourceID;
                else if (Decimal.Remainder(i, 2) == 0)
                    ti.Resources = ResourceInfo[1].ResourceID.ToString();
                else
                    ti.Resources = ResourceInfo[0].ResourceID.ToString();

                if (Decimal.Remainder(i, 6) == 0)
                {
                    ti.IndentLevel = 0;
                    ti.Resources = String.Empty;
                }
                else
                    ti.IndentLevel = 1;

                if (Decimal.Remainder(i, 5) == 0)
                {
                    ti.PredecessorIndices = (i - 4).ToString() + " + 4";
                }

                taskItems.Add(ti);
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            context.Response.Write(serializer.Serialize(taskItems));
        }
예제 #11
0
파일: PeriodTask.cs 프로젝트: bfbd/MiniWeb
		private void ExecuteTask(TaskInfo task, object param)
		{
			Debug.Assert(task != null);
			try
			{
				task.Action(param);
			}
			catch (Exception ex)
			{
				Logger.Exception(ex);
				if (OnException != null)
				{
					try { OnException(this, new TaskExceptionArgs(task.Name, param, ex)); }
					catch (Exception) { }
				}
			}
			finally
			{
				task.LastEndTime = DateTime.Now;
			}
		}
예제 #12
0
    /// <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;
    }
예제 #13
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string url = "Frameset.aspx?groupid={%EditedObject.ID%}&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);
        }
    }
예제 #14
0
 public TaskContainer(ParameterizedThreadSStart parameterizedThreadSStart, object o, TaskInfo threadInfo = null)
 {
     this.parameterizedThreadSStart = parameterizedThreadSStart;
     this.o            = o;
     this.taskInfo     = threadInfo;
     this.threadSStart = null;
     this.is_void_func = false;
 }
예제 #15
0
    /// <summary>
    /// OnAfterSave event handler.
    /// </summary>
    protected void EditForm_OnAfterSave(object sender, EventArgs e)
    {
        // Get edited contact group
        ContactGroupInfo cgi = (ContactGroupInfo)EditForm.EditedObject;

        if (chkDynamic.Checked)
        {
            // Set info for scheduled task
            task = GetScheduledTask(cgi);

            // Update scheduled task
            if (chkSchedule.Checked)
            {
                if (!schedulerInterval.CheckOneDayMinimum())
                {
                    // If problem occurred while setting schedule interval
                    EditForm.ErrorLabel.Text = GetString("Newsletter_Edit.NoDaySelected");
                    EditForm.ErrorLabel.Visible = true;
                    EditForm.StopProcessing = true;
                    return;
                }

                if (!IsValidDate(SchedulingHelper.DecodeInterval(scheduleInterval).StartTime))
                {
                    // Start date is not in valid format
                    EditForm.ErrorLabel.Text = GetString("Newsletter.IncorrectDate");
                    EditForm.ErrorLabel.Visible = true;
                    EditForm.StopProcessing = true;
                    return;
                }

                task.TaskInterval = scheduleInterval;
                task.TaskNextRunTime = SchedulingHelper.GetNextTime(task.TaskInterval, new DateTime(), new DateTime());
                task.TaskEnabled = true;
            }
            else
            {
                task.TaskInterval = scheduleInterval;
                task.TaskNextRunTime = TaskInfoProvider.NO_TIME;
                task.TaskEnabled = false;
            }
            TaskInfoProvider.SetTaskInfo(task);

            cgi.ContactGroupScheduledTaskID = task.TaskID;
            pnlInfo.Visible = true;
            InitInfoPanel(cgi, true);
        }
        else
        {
            if (cgi.ContactGroupScheduledTaskID > 0)
            {
                // Store task ID for deletion
                deleteScheduledTaskId = cgi.ContactGroupScheduledTaskID;
            }
            cgi.ContactGroupScheduledTaskID = 0;
            cgi.ContactGroupStatus = ContactGroupStatusEnum.Unspecified;
            schedulerInterval.Visible = false;
            pnlInfo.Visible = false;
        }

        // Update contact group
        ContactGroupInfoProvider.SetContactGroupInfo(cgi);

        if (deleteScheduledTaskId > 0)
        {
            // Delete scheduled task if schedule evaluation was unchecked
            TaskInfoProvider.DeleteTaskInfo(deleteScheduledTaskId);
        }

        InitHeaderActions(false);
        ((CMSPage)Page).CurrentMaster.HeaderActions.ReloadData();

        // Refresh breadcrumbs after data are loaded
        ScriptHelper.RefreshTabHeader(Page, null);
    }
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Check "configure" permission
        if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.newsletter", "configure"))
        {
            RedirectToCMSDeskAccessDenied("cms.newsletter", "configure");
        }

        string errorMessage = ValidateNewsletterValues();

        if (!string.IsNullOrEmpty(errorMessage))
        {
            ShowError(errorMessage);
            return;
        }

        Newsletter newsletterObj = NewsletterProvider.GetNewsletter(txtNewsletterName.Text.Trim(), CMSContext.CurrentSiteID);

        // Newsletter's code name must be unique
        if (newsletterObj != null && newsletterObj.NewsletterID != newsletterId)
        {
            ShowError(GetString("Newsletter_Edit.NewsletterNameExists"));
            return;
        }

        if (newsletterObj == null)
        {
            newsletterObj = NewsletterProvider.GetNewsletter(newsletterId);
        }

        SetNewsletterValues(newsletterObj);

        // Check if subscription template was selected
        int subscriptionTemplateValue = ValidationHelper.GetInteger(subscriptionTemplate.Value, 0);

        if (subscriptionTemplateValue == 0)
        {
            ShowError(GetString("Newsletter_Edit.NoSubscriptionTemplateSelected"));
            return;
        }
        newsletterObj.NewsletterSubscriptionTemplateID = subscriptionTemplateValue;

        // Check if double opt-in template was selected
        int optInTemplateValue = ValidationHelper.GetInteger(optInSelector.Value, 0);

        if (newsletterObj.NewsletterEnableOptIn && optInTemplateValue == 0)
        {
            ShowError(GetString("Newsletter_Edit.NoOptInTemplateSelected"));
            return;
        }
        newsletterObj.NewsletterOptInTemplateID = optInTemplateValue;

        // 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.NewsletterType           = NewsletterType.Dynamic;
            newsletterObj.NewsletterDynamicURL     = txtNewsletterDynamicURL.Text.Trim();
            newsletterObj.NewsletterDynamicSubject = radFollowing.Checked ? txtSubject.Text : string.Empty;

            if (chkSchedule.Checked)
            {
                // Set info for scheduled task
                TaskInfo task = GetDynamicNewsletterTask(newsletterObj);

                if (!schedulerInterval.CheckOneDayMinimum())
                {
                    // If problem occurred while setting schedule interval
                    ShowError(GetString("Newsletter_Edit.NoDaySelected"));
                    return;
                }

                if (!IsValidDate(SchedulingHelper.DecodeInterval(schedulerInterval.ScheduleInterval).StartTime))
                {
                    ShowError(GetString("Newsletter.IncorrectDate"));
                    return;
                }

                task.TaskInterval = schedulerInterval.ScheduleInterval;

                task.TaskNextRunTime = SchedulingHelper.GetNextTime(task.TaskInterval, new DateTime(), new DateTime());
                task.TaskDisplayName = GetString("DynamicNewsletter.TaskName") + newsletterObj.NewsletterDisplayName;
                task.TaskName        = "DynamicNewsletter_" + newsletterObj.NewsletterName;
                // Set task for processing in external service
                task.TaskAllowExternalService = true;
                task.TaskUseExternalService   = (SchedulingHelper.UseExternalService && NewsletterProvider.UseExternalServiceForDynamicNewsletters(CMSContext.CurrentSiteName));
                TaskInfoProvider.SetTaskInfo(task);
                newsletterObj.NewsletterDynamicScheduledTaskID = task.TaskID;
            }
            else
            {
                if (newsletterObj.NewsletterDynamicScheduledTaskID > 0)
                {
                    // Store task ID for deletion
                    deleteScheduledTaskId = newsletterObj.NewsletterDynamicScheduledTaskID;
                }
                newsletterObj.NewsletterDynamicScheduledTaskID = 0;
                schedulerInterval.Visible = false;
            }
        }
        else
        {
            newsletterObj.NewsletterType = NewsletterType.TemplateBased;

            // Check if issue template was selected
            int issueTemplateValue = ValidationHelper.GetInteger(issueTemplate.Value, 0);
            if (issueTemplateValue == 0)
            {
                ShowError(GetString("Newsletter_Edit.NoEmailTemplateSelected"));
                return;
            }
            newsletterObj.NewsletterTemplateID = issueTemplateValue;
        }

        // Save changes to DB
        NewsletterProvider.SetNewsletter(newsletterObj);
        if (deleteScheduledTaskId > 0)
        {
            // Delete scheduled task if schedule mail-outs were unchecked
            TaskInfoProvider.DeleteTaskInfo(deleteScheduledTaskId);
        }

        ShowInformation(GetString("General.ChangesSaved"));

        // Refresh header with display name
        ScriptHelper.RefreshTabHeader(Page, GetString("Newsletter_Header.Configuration"));
    }
예제 #17
0
        public TaskDto AcceptTask(byte type, uint level, byte slot)
        {
            //Logger.Debug($"Claimed mission {TaskLevel}");
            var TaskList  = GameServer.Instance.ResourceCache.GetTasks();
            var constants = type == 1;

            var tasks = from t in TaskList
                        where t.Value.constant == constants &&
                        t.Value.Level == level
                        select t.Value;

            if (tasks.Any())
            {
                TaskInfo task = null;
                var      rand = new Random();

                while (task == null)
                {
                    foreach (var tt in tasks)
                    {
                        if (tt.GetChance(Player) < rand.Next(100) ||
                            _tasksR.ContainsKey(tt.Id))
                        {
                            continue;
                        }

                        task = tt;

                        break;
                    }
                }

                if (constants)
                {
                    _rMRunning++;
                }
                else
                {
                    _wMRunning++;
                }

                var rt     = (task.RewardExp != 0) ? rand.Next(1, 2) : 1;
                var reward = (rt == 1 ? task.RewardPen : task.RewardExp);

                _tasksR.Add(task.Id, new PlayerMissionsDto
                {
                    TaskId     = task.Id,
                    PlayerId   = Player.Account.Id,
                    Progress   = 0,
                    Date       = DateTime.Now.ToBinary(),
                    Slot       = slot,
                    RewardType = (byte)rt,
                    Reward     = (ushort)reward
                });
                Logger.ForAccount(Player)
                .Debug($"Added Mission {task.Id} - {task.Level} - {task.Name}");
                return(new TaskDto
                {
                    Id = task.Id,
                    Unk1 = slot, //Slot?
                    Progress = 0,
                    Reward = reward,
                    RewardType = (MissionRewardType)rt
                });
            }

            return(null);
        }
예제 #18
0
		public static async void Update (ProjectFile file, bool force)
		{
			ISingleFileCustomTool tool;
			ProjectFile genFile;
			if (!ShouldRunGenerator (file, force, out tool, out genFile)) {
				return;
			}
			
			TaskService.Errors.ClearByOwner (file);
			
			TaskInfo runningTask;
			TaskCompletionSource<bool> newTask = new TaskCompletionSource<bool> ();
			var result = new SingleFileCustomToolResult ();
			Task existingTask = null;
			CancellationTokenSource cs = new CancellationTokenSource ();

			// if this file is already being run, cancel it

			lock (runningTasks) {
				if (runningTasks.TryGetValue (file.FilePath, out runningTask)) {
					runningTask.CancellationTokenSource.Cancel ();
					runningTasks.Remove (file.FilePath);
					existingTask = runningTask.Task;
				}
				runningTask = new TaskInfo { Task = newTask.Task, CancellationTokenSource = cs, Result = result };
				runningTasks.Add (file.FilePath, runningTask);
			}

			// If a task was already running, wait for it to finish. Running the same task in parallel may lead
			// to file sharing violation errors

			if (existingTask != null) {
				try {
					await existingTask;
				} catch {
					// Ignore exceptions, they are handled elsewhere
				}
			}

			// Maybe I was cancelled while I was waiting. In that case, the task has already been removed from
			// the runningTasks collection

			if (cs.IsCancellationRequested)
				return;

			// Execute the generator

			Exception error = null;
			var monitor = IdeApp.Workbench.ProgressMonitors.GetToolOutputProgressMonitor (false).WithCancellationSource (cs);

			try {
				monitor.BeginTask (GettextCatalog.GetString ("Running generator '{0}' on file '{1}'...", file.Generator, file.Name), 1);

				try {
					await tool.Generate (monitor, file, result);
				} catch (Exception ex) {
					error = ex;
					result.UnhandledException = ex;
				}

				// Generation has finished. Remove the task from the runningTasks collection

				lock (runningTasks) {
					TaskInfo registeredTask;
					if (runningTasks.TryGetValue (file.FilePath, out registeredTask) && registeredTask == runningTask) {
						runningTasks.Remove (file.FilePath);
						UpdateCompleted (monitor, file, genFile, result, false);
					} else {
						// it was cancelled because another was run for the same file, so just clean up
						monitor.EndTask ();
						monitor.ReportWarning (GettextCatalog.GetString ("Cancelled because generator ran again for the same file"));
						monitor.Dispose ();
					}
				}
			} catch (Exception ex) {
				result.UnhandledException = ex;
				UpdateCompleted (monitor, file, genFile, result, false);
			} finally {
				if (error == null)
					newTask.SetResult (true);
				else {
					newTask.SetException (error);
				}
			}
		}
예제 #19
0
    /// <summary>
    /// Gets and bulk updates scheduled tasks. Called when the "Get and bulk update tasks" button is pressed.
    /// Expects the CreateScheduledTask method to be run first.
    /// </summary>
    private bool GetAndBulkUpdateScheduledTasks()
    {
        // Get the data
        DataSet tasks = TaskInfoProvider.GetAllTasks();
        if (!DataHelper.DataSourceIsEmpty(tasks))
        {
            // Loop through the individual items
            foreach (DataRow taskDr in tasks.Tables[0].Rows)
            {
                // Create object from DataRow
                TaskInfo modifyTask = new TaskInfo(taskDr);

                // Update the properties
                modifyTask.TaskDisplayName = modifyTask.TaskDisplayName.ToUpper();

                // Save the changes
                TaskInfoProvider.SetTaskInfo(modifyTask);
            }

            return true;
        }

        return false;
    }
예제 #20
0
 public void Init(TaskInfo info)
 {
     taskInfo = info;
     RefreshData();
 }
예제 #21
0
    /// <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 (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.NewsletterType           = NewsletterType.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)
            {
                // Set info for scheduled task
                TaskInfo task = GetDynamicNewsletterTask(newsletterObj);

                if (!schedulerInterval.CheckOneDayMinimum())
                {
                    // If problem occurred while setting schedule interval
                    ShowError(GetString("Newsletter_Edit.NoDaySelected"));
                    return;
                }

                if (!DataTypeManager.IsValidDate(SchedulingHelper.DecodeInterval(scheduledInterval).StartTime))
                {
                    ShowError(GetString("Newsletter.IncorrectDate"));
                    return;
                }

                if ((newsletterObj.NewsletterDynamicScheduledTaskID == task.TaskID) && (task.TaskInterval == scheduledInterval))
                {
                    // No need to update anything, nothing has changed
                }
                else
                {
                    // Scheduled task either doesn't exist or was updated to new interval
                    task.TaskInterval    = scheduledInterval;
                    task.TaskNextRunTime = SchedulingHelper.GetNextTime(task.TaskInterval, new DateTime(), new DateTime());
                    task.TaskDisplayName = GetString("DynamicNewsletter.TaskName") + newsletterObj.NewsletterDisplayName;
                    task.TaskName        = "DynamicNewsletter_" + newsletterObj.NewsletterName;
                    // Set task for processing in external service
                    task.TaskAllowExternalService = true;
                    task.TaskUseExternalService   = (SchedulingHelper.UseExternalService && NewsletterHelper.UseExternalServiceForDynamicNewsletters(SiteContext.CurrentSiteName));
                    TaskInfoProvider.SetTaskInfo(task);
                    newsletterObj.NewsletterDynamicScheduledTaskID = task.TaskID;
                }
            }
            else
            {
                if (newsletterObj.NewsletterDynamicScheduledTaskID > 0)
                {
                    // Store task ID for deletion
                    deleteScheduledTaskId = newsletterObj.NewsletterDynamicScheduledTaskID;
                }
                newsletterObj.NewsletterDynamicScheduledTaskID = 0;
                schedulerInterval.Visible = false;
            }
        }
        else
        {
            newsletterObj.NewsletterType = NewsletterType.TemplateBased;

            // Check if issue template was selected
            int issueTemplateValue = ValidationHelper.GetInteger(issueTemplate.Value, 0);
            if (issueTemplateValue == 0)
            {
                ShowError(GetString("Newsletter_Edit.NoEmailTemplateSelected"));
                return;
            }
            newsletterObj.NewsletterTemplateID = issueTemplateValue;
        }

        // 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);
    }
예제 #22
0
        private void buttonSendText_Click(object sender, EventArgs e)
        {
            string text = this.textBoxSendText.Text;

            taskThread.SendTask(TaskInfo.Create(TaskType.InputText, text));
        }
 public static void SetTaskInfo(TaskInfo taskInfo, UIConstants uIConstants)
 {
     taskInfo.Height = uIConstants.Height;
     taskInfo.Width  = uIConstants.Width;
 }
예제 #24
0
 protected void PublishTaskInfo()
 {
     FillDistributedTask();
     TaskInfo.PublishChanges();
 }
예제 #25
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                SetProgress(5, "Setup tenant");

                TenantManager.SetCurrentTenant(CurrentTenant);

                SetProgress(10, "Setup user");

                SecurityContext.AuthenticateMe(CurrentUser); //Core.Configuration.Constants.CoreSystem);

                SetProgress(15, "Find user data");

                var currentUser = UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

                SetProgress(20, "Create mime message");

                var toAddress = new MailboxAddress(currentUser.UserName, currentUser.Email);

                var fromAddress = new MailboxAddress(SmtpSettings.SenderDisplayName, SmtpSettings.SenderAddress);

                var mimeMessage = new MimeMessage
                {
                    Subject = messageSubject
                };

                mimeMessage.From.Add(fromAddress);

                mimeMessage.To.Add(toAddress);

                var bodyBuilder = new BodyBuilder
                {
                    TextBody = messageBody
                };

                mimeMessage.Body = bodyBuilder.ToMessageBody();

                mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");

                using var client = GetSmtpClient();
                SetProgress(40, "Connect to host");

                client.Connect(SmtpSettings.Host, SmtpSettings.Port.GetValueOrDefault(25),
                               SmtpSettings.EnableSSL ? SecureSocketOptions.Auto : SecureSocketOptions.None, cancellationToken);

                if (SmtpSettings.EnableAuth)
                {
                    SetProgress(60, "Authenticate");

                    client.Authenticate(SmtpSettings.CredentialsUserName,
                                        SmtpSettings.CredentialsUserPassword, cancellationToken);
                }

                SetProgress(80, "Send test message");

                client.Send(FormatOptions.Default, mimeMessage, cancellationToken);
            }
            catch (AuthorizingException authError)
            {
                Error = Resource.ErrorAccessDenied; // "No permissions to perform this action";
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (SocketException ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            catch (AuthenticationException ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            catch (Exception ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();

                    SecurityContext.Logout();
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("LdapOperation finalization problem. {0}", ex);
                }
            }
        }
예제 #26
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

                SecurityContext.AuthenticateMe(Core.Configuration.Constants.CoreSystem);

                Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo(_culture);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(_culture);

                Logger = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Log4Net, "MailOperation");

                //TODO: Check any settings
                switch (OperationType)
                {
                case MailOperationType.RecalculateFolders:
                    break;

                case MailOperationType.RemoveMailbox:
                    break;

                default:
                    throw new InvalidOperationException();
                }

                Do();
            }
            catch (AuthorizingException authError)
            {
                Error = "ErrorAccessDenied";
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (TenantQuotaException e)
            {
                Error = "TenantQuotaSettled";
                Logger.Error("TenantQuotaException. {0}", e);
            }
            catch (FormatException e)
            {
                Error = "CantCreateUsers";
                Logger.Error("FormatException error. {0}", e);
            }
            catch (Exception e)
            {
                Error = "InternalServerError";
                Logger.Error("Internal server error. {0}", e);
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();
                }
                catch
                {
                    /* ignore */
                }
            }
        }
예제 #27
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script for pendingCallbacks repair
        ScriptHelper.FixPendingCallbacks(Page);

        // Initialize current user for the async actions
        currentUser = CMSContext.CurrentUser;

        HeaderActions.ActionPerformed += HeaderActions_ActionPerformed;

        if (!RequestHelper.IsCallback())
        {
            // Check 'Manage object tasks' permission
            if (!currentUser.IsAuthorizedPerResource("cms.staging", "ManageObjectsTasks"))
            {
                RedirectToAccessDenied("cms.staging", "ManageObjectsTasks");
            }

            siteId = QueryHelper.GetInteger("siteid", 0);
            currentSiteId = CMSContext.CurrentSiteID;
            currentSiteName = CMSContext.CurrentSiteName;
            serverId = QueryHelper.GetInteger("serverid", 0);

            ucDisabledModule.SettingsKeys = "CMSStagingLogStagingChanges;CMSStagingLogObjectChanges";
            ucDisabledModule.InfoTexts.Add(GetString("StagingChanges.NotLogged") + "<br/>");
            ucDisabledModule.ParentPanel = pnlNotLogged;

            if (siteId == -1)
            {
                ucDisabledModule.InfoTexts.Add(GetString("objectstaging.globalandsitenotlogged"));
                ucDisabledModule.SiteObjects = "CMSStagingLogObjectChanges";
                ucDisabledModule.GlobalObjects = "CMSStagingLogObjectChanges";
            }
            else if (siteId == 0)
            {
                ucDisabledModule.InfoTexts.Add(GetString("objectstaging.globalnotlogged"));
                ucDisabledModule.GlobalObjects = "CMSStagingLogObjectChanges";
            }
            else
            {
                ucDisabledModule.InfoTexts.Add(GetString("ObjectStaging.SiteNotLogged"));
                ucDisabledModule.SiteObjects = "CMSStagingLogObjectChanges";
            }

            // Check logging
            if (!ucDisabledModule.Check())
            {
                plcContent.Visible = false;
                return;
            }

            // Get object type
            objectType = QueryHelper.GetString("objecttype", string.Empty);
            if (!String.IsNullOrEmpty(objectType) && (objectType != PredefinedObjectType.MEDIAFOLDER))
            {
                // Create "synchronize current" header action
                HeaderActions.AddAction(new HeaderAction()
                {
                    Text = GetString("ObjectTasks.SyncCurrent"),
                    ImageUrl = GetImageUrl("CMSModules/CMS_Staging/syncsubtree.png"),
                    EventName = SYNCHRONIZE_CURRENT
                });
            }

            // Setup title
            titleElem.TitleText = GetString("Synchronization.Title");
            titleElem.TitleImage = GetImageUrl("/CMSModules/CMS_Staging/synchronization.png");

            // Get the selected types
            ObjectTypeTreeNode selectedNode = TaskInfoProvider.ObjectTree.FindNode(objectType, (siteId > 0));
            objectType = (selectedNode != null) ? selectedNode.GetObjectTypes(true) : string.Empty;
            if (!RequestHelper.CausedPostback(HeaderActions, btnSyncSelected, btnSyncAll))
            {
                // Register the dialog script
                ScriptHelper.RegisterDialogScript(this);

                // Initialize images
                viewImage = GetImageUrl("Design/Controls/UniGrid/Actions/View.png");
                deleteImage = GetImageUrl("Design/Controls/UniGrid/Actions/Delete.png");
                syncImage = GetImageUrl("Design/Controls/UniGrid/Actions/Synchronize.png");

                // Initialize tooltips
                syncTooltip = GetString("general.synchronize");
                deleteTooltip = GetString("general.delete");
                viewTooltip = GetString("general.view");

                plcContent.Visible = true;

                // Initialize buttons
                btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;");
                btnCancel.Text = GetString("General.Cancel");
                btnDeleteAll.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("Tasks.ConfirmDeleteAll")) + ");";
                btnDeleteSelected.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("general.confirmdelete")) + ");";
                btnSyncSelected.OnClientClick = "return !" + gridTasks.GetCheckSelectionScript();

                // Initialize grid
                gridTasks.ZeroRowsText = GetString("Tasks.NoTasks");
                gridTasks.OnAction += gridTasks_OnAction;
                gridTasks.OnDataReload += gridTasks_OnDataReload;
                gridTasks.OnExternalDataBound += gridTasks_OnExternalDataBound;
                gridTasks.ShowActionsMenu = true;
                gridTasks.Columns = "TaskID, TaskSiteID, TaskDocumentID, TaskNodeAliasPath, TaskTitle, TaskTime, TaskType, TaskObjectType, TaskObjectID, TaskRunning, (SELECT COUNT(*) FROM Staging_Synchronization WHERE SynchronizationTaskID = TaskID AND SynchronizationErrorMessage IS NOT NULL AND (SynchronizationServerID = @ServerID OR (@ServerID = 0 AND (@TaskSiteID = 0 OR SynchronizationServerID IN (SELECT ServerID FROM Staging_Server WHERE ServerSiteID = @TaskSiteID AND ServerEnabled=1))))) AS FailedCount";
                TaskInfo ti = new TaskInfo();
                gridTasks.AllColumns = SqlHelperClass.MergeColumns(ti.ColumnNames);

                pnlLog.Visible = false;
            }
        }

        ctlAsync.OnFinished += ctlAsync_OnFinished;
        ctlAsync.OnError += ctlAsync_OnError;
        ctlAsync.OnRequestLog += ctlAsync_OnRequestLog;
        ctlAsync.OnCancel += ctlAsync_OnCancel;
    }
예제 #28
0
    protected void LoadData()
    {
        if (!EditedNewsletter.CheckPermissions(PermissionsEnum.Modify, CurrentSiteName, CurrentUser))
        {
            RedirectToAccessDenied(EditedNewsletter.TypeInfo.ModuleName, "Configure");
        }

        int siteId = EditedNewsletter.NewsletterSiteID;

        // Initialize template selectors
        string whereTemplate = "TemplateType='{0}' AND TemplateSiteID=" + siteId;

        subscriptionTemplate.WhereCondition   = String.Format(whereTemplate, EmailTemplateType.Subscription);
        unsubscriptionTemplate.WhereCondition = String.Format(whereTemplate, EmailTemplateType.Unsubscription);
        optInSelector.WhereCondition          = String.Format(whereTemplate, EmailTemplateType.DoubleOptIn);

        issueTemplate.WhereCondition = String.Format(whereTemplate, EmailTemplateType.Issue);

        issueTemplate.WhereCondition = SqlHelper.AddWhereCondition(issueTemplate.WhereCondition, String.Format("TemplateID={0}", EditedNewsletter.NewsletterTemplateID), "OR");

        // Check if the newsletter is dynamic and adjust config dialog
        isDynamic = EditedNewsletter.NewsletterType.EqualsCSafe(NewsletterType.Dynamic, StringComparison.InvariantCultureIgnoreCase);

        // Display template/dynamic based newsletter config and online marketing config
        plcDynamic.Visible  = isDynamic;
        plcTemplate.Visible = !isDynamic;
        plcTracking.Visible = TrackingEnabled;
        plcOM.Visible       = OnlineMarketingEnabled;

        if (!RequestHelper.IsPostBack())
        {
            if (QueryHelper.GetBoolean("saved", false))
            {
                // If user was redirected from newsletter_new.aspx, display the 'Changes were saved' message
                ShowChangesSaved();
            }

            // Fill config dialog with newsletter data
            GetNewsletterValues(EditedNewsletter);

            if (!isDynamic)
            {
                // Initialize issue template selector
                issueTemplate.Value = EditedNewsletter.NewsletterTemplateID.ToString();
            }
            else
            {
                // Check if dynamic newsletter subject is empty
                bool subjectEmpty = string.IsNullOrEmpty(EditedNewsletter.NewsletterDynamicSubject);
                radPageTitle.Checked = subjectEmpty;
                radFollowing.Checked = !subjectEmpty;
                txtSubject.Enabled   = radFollowing.Checked;

                if (!subjectEmpty)
                {
                    txtSubject.Text = EditedNewsletter.NewsletterDynamicSubject;
                }

                txtNewsletterDynamicURL.Value = EditedNewsletter.NewsletterDynamicURL;

                TaskInfo task = TaskInfoProvider.GetTaskInfo(EditedNewsletter.NewsletterDynamicScheduledTaskID);
                if (task != null)
                {
                    chkSchedule.Checked                = true;
                    schedulerInterval.Visible          = true;
                    schedulerInterval.ScheduleInterval = task.TaskInterval;
                }
                else
                {
                    chkSchedule.Checked       = false;
                    schedulerInterval.Visible = false;
                }
            }
        }
    }
예제 #29
0
        static int TriggerTask(EDXTask t)
        {
            /*
            Completed   0   The task has completed successfully. (same as 6)
            Waiting     1   The task is waiting to be executed.
            Running     2   The task is running
            Aborting    3   The task is aborting the execution.
            Failed      4   The task failed.
            Warning     5   The task completed with a warning.
            Completed   6   The task has completed successfully.
            Error       9   An unknown error occured
            Exception   10  Catch exception error
            */

            var exitCode = 0;

            LogProperties logProperties = new LogProperties {TaskNameOrId = t.TaskNameOrId, ExecId = "-1"};

            try
            {
                // Create a QMS API client
                IQMS apiClient = String.IsNullOrEmpty(t.ServiceAddress) ? new QMSClient() : new QMSClient("BasicHttpBinding_IQMS", t.ServiceAddress);

                // Retrieve a time limited service key
                ServiceKeyClientMessageInspector.ServiceKey = apiClient.GetTimeLimitedServiceKey();

                TaskInfo taskInfo = new TaskInfo();

                if (!IsGuid(t.TaskNameOrId))
                {
                    List<TaskInfo> taskList = apiClient.FindEDX(t.TaskNameOrId);

                    // Find correct task with support for multiple qds
                    if (taskList.Count > 0)
                    {
                        int i = 0;

                        for (i = 0; i < taskList.Count; i++)
                        {
                            if (taskList[i].Name == t.TaskNameOrId)
                                break;
                        }

                        taskInfo = new TaskInfo
                                       {
                                           Name = taskList[i].Name,
                                           ID = taskList[i].ID,
                                           QDSID = taskList[i].QDSID,
                                           Enabled = taskList[i].Enabled
                                       };
                    }
                }
                else
                {
                    taskInfo = apiClient.GetTask(Guid.Parse(t.TaskNameOrId));
                }

                if (taskInfo.Name != null)
                {
                    // Trigger the task
                    TriggerEDXTaskResult result = apiClient.TriggerEDXTask(Guid.Empty, taskInfo.Name, t.Password, t.VariableName, t.VariableValues);

                    if (result.EDXTaskStartResult == EDXTaskStartResult.Success)
                    {
                        logProperties.ExecId = result.ExecId.ToString();

                        if (t.Verbosity > 0)
                        {
                            LogHelper.Log(LogLevel.Info, String.Format("Name: {0}, ID: {1}, Enabled: {2}, Sleep: {3} seconds, Timeout: {4}", taskInfo.Name, taskInfo.ID, taskInfo.Enabled ? "Yes" : "No", t.Sleep / 1000, t.TimeOut == -1 ? "Indefinitely" : t.TimeOut / 60000 + " minutes"), logProperties);
                        }

                        LogHelper.Log(LogLevel.Info, "Started", logProperties);

                        EDXStatus executionStatus = null;

                        if(t.TimeOut != 0)
                        {
                            // Wait until the task is completed or TIMEOUT has passed.
                            SpinWait.SpinUntil(() =>
                            {
                                Thread.Sleep(t.Sleep);

                                // Retrieve a new service key if sleep time is above 18 minutes to be safe (timeout is 20 minutes in QV11)
                                if (t.Sleep > 18 * 60 * 1000)
                                {
                                    if (t.Verbosity > 1)
                                        LogHelper.Log(LogLevel.Info, "GetTimeLimitedServiceKey()", logProperties);

                                    ServiceKeyClientMessageInspector.ServiceKey = apiClient.GetTimeLimitedServiceKey();
                                }

                                // Get the current state of the task.
                                try
                                {
                                    executionStatus = apiClient.GetEDXTaskStatus(Guid.Empty, result.ExecId);
                                }
                                catch (Exception ex)
                                {
                                    LogHelper.Log(LogLevel.Warn, String.Format("{0}", ex.Message.Replace(Environment.NewLine, " ")), logProperties);
                                }

                                if (executionStatus != null && t.Verbosity > 1 && executionStatus.TaskStatus != TaskStatusValue.Running)
                                    LogHelper.Log(LogLevel.Info, executionStatus.TaskStatus.ToString(), logProperties);

                                // Return true if the task has completed.
                                return executionStatus != null && (executionStatus.TaskStatus != TaskStatusValue.Running && executionStatus.TaskStatus != TaskStatusValue.Waiting);
                            }, t.TimeOut);

                            // Write the result
                            if (executionStatus != null)
                            {
                                if (executionStatus.TaskStatus == TaskStatusValue.Completed)
                                {
                                    // datetime parsing needs culture formatting, catch it for now and avoid...
                                    try
                                    {
                                        TimeSpan span = DateTime.Parse(executionStatus.FinishTime).Subtract(DateTime.Parse(executionStatus.StartTime));
                                        LogHelper.Log(LogLevel.Info, String.Format("{0} (Duration: {1})", executionStatus.TaskStatus, span), logProperties);

                                    }
                                    catch (Exception)
                                    {
                                        LogHelper.Log(LogLevel.Info, String.Format("{0}", executionStatus.TaskStatus), logProperties);
                                    }
                                }
                                else
                                {
                                    // If something went wrong, point to the logfile for the task execution
                                    exitCode = (Int32)executionStatus.TaskStatus;
                                    LogHelper.Log(LogLevel.Error, String.Format("{0} (Error code: {1})", executionStatus.TaskStatus, exitCode), logProperties);
                                    LogHelper.Log(LogLevel.Error, "Logfile: " + executionStatus.LogFileFullPath, logProperties);
                                }
                            }
                            else
                            {
                                exitCode = 9;
                                LogHelper.Log(LogLevel.Error, String.Format("Failed to get execution status (Error code: {0})", exitCode), logProperties);
                            }
                        }
                    }
                    else
                    {
                        exitCode = 9;
                        LogHelper.Log(LogLevel.Error, String.Format("{0} (Error code: {1})", result.EDXTaskStartResult, exitCode), logProperties);
                    }
                }
                else
                {
                    exitCode = 9;
                    LogHelper.Log(LogLevel.Error, "TaskNotFound (Error code: 9)", logProperties);
                }
            }
            catch (Exception ex)
            {
                exitCode = 10;
                LogHelper.Log(LogLevel.Error, String.Format("{0} (Error code: {1})", ex.Message.Replace(Environment.NewLine, " "), exitCode), logProperties);
            }

            return exitCode;
        }
예제 #30
0
 private void ExecuteCopyTask(object parameter)
 {
     _copiedTask = this.SelectedTask;
 }
예제 #31
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script for pendingCallbacks repair
        ScriptHelper.FixPendingCallbacks(Page);

        // Get site info
        currentSiteId = CMSContext.CurrentSiteID;
        currentSiteName = CMSContext.CurrentSiteName;

        // Initialize current user for the async actions
        currentUser = CMSContext.CurrentUser;
        serverId = QueryHelper.GetInteger("serverid", 0);

        HeaderActions.ActionPerformed += HeaderActions_ActionPerformed;

        if (RequestHelper.CausedPostback(btnSyncComplete))
        {
            SyncComplete();
        }
        else
        {
            if (!RequestHelper.IsCallback())
            {
                int nodeId = QueryHelper.GetInteger("nodeid", 0);

                aliasPath = "/";

                // Get the document node
                if (nodeId > 0)
                {
                    TreeProvider tree = new TreeProvider(currentUser);
                    TreeNode node = tree.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES);
                    if (node != null)
                    {
                        aliasPath = node.NodeAliasPath;
                    }
                }

                // Setup title
                titleElem.TitleText = GetString("Synchronization.Title");
                titleElem.TitleImage = GetImageUrl("CMSModules/CMS_Staging/synchronization.png");

                ucDisabledModule.SettingsKeys = "CMSStagingLogChanges;CMSStagingLogStagingChanges;";
                ucDisabledModule.InfoTexts.Add(GetString("ContentStaging.TaskSeparator") + "<br/>");
                ucDisabledModule.InfoTexts.Add(GetString("StagingChanges.NotLogged"));
                ucDisabledModule.ParentPanel = pnlNotLogged;

                // Check logging
                if (!ucDisabledModule.Check())
                {
                    plcContent.Visible = false;
                    pnlFooter.Visible = false;
                    return;
                }

                // Create header actions
                HeaderActions.AddAction(new HeaderAction()
                {
                    Text = GetString("Tasks.SyncCurrent"),
                    ImageUrl = GetImageUrl("CMSModules/CMS_Staging/synccurrent_16.png"),
                    EventName = SYNCHRONIZE_CURRENT
                });

                HeaderActions.AddAction(new HeaderAction()
                {
                    Text = GetString("Tasks.SyncSubtree"),
                    ImageUrl = GetImageUrl("CMSModules/CMS_Staging/syncsubtree.png"),
                    EventName = SYNCHRONIZE_SUBTREE
                });

                if (!RequestHelper.CausedPostback(HeaderActions, btnSyncSelected, btnSyncAll))
                {
                    // Check 'Manage servers' permission
                    if (!currentUser.IsAuthorizedPerResource("cms.staging", "ManageDocumentsTasks"))
                    {
                        RedirectToAccessDenied("cms.staging", "ManageDocumentsTasks");
                    }

                    // Register the dialog script
                    ScriptHelper.RegisterDialogScript(this);

                    ltlScript.Text +=
                        ScriptHelper.GetScript("function ConfirmDeleteTask(taskId) { return confirm(" +
                                               ScriptHelper.GetString(GetString("Tasks.ConfirmDelete")) + "); }");
                    ltlScript.Text +=
                        ScriptHelper.GetScript("function CompleteSync(){" +
                                               Page.ClientScript.GetPostBackEventReference(btnSyncComplete, null) + "}");

                    // Initialize grid
                    tasksUniGrid.OnExternalDataBound += tasksUniGrid_OnExternalDataBound;
                    tasksUniGrid.OnAction += tasksUniGrid_OnAction;
                    tasksUniGrid.OnDataReload += tasksUniGrid_OnDataReload;
                    tasksUniGrid.ShowActionsMenu = true;
                    tasksUniGrid.Columns = "TaskID, TaskSiteID, TaskDocumentID, TaskNodeAliasPath, TaskTitle, TaskTime, TaskType, TaskObjectType, TaskObjectID, TaskRunning, (SELECT COUNT(*) FROM Staging_Synchronization WHERE SynchronizationTaskID = TaskID AND SynchronizationErrorMessage IS NOT NULL AND (SynchronizationServerID = @ServerID OR (@ServerID = 0 AND (@TaskSiteID = 0 OR SynchronizationServerID IN (SELECT ServerID FROM Staging_Server WHERE ServerSiteID = @TaskSiteID AND ServerEnabled=1))))) AS FailedCount";
                    TaskInfo ti = new TaskInfo();
                    tasksUniGrid.AllColumns = SqlHelperClass.MergeColumns(ti.ColumnNames);

                    // Initialize images
                    viewImage = GetImageUrl("Design/Controls/UniGrid/Actions/View.png");
                    deleteImage = GetImageUrl("Design/Controls/UniGrid/Actions/Delete.png");
                    syncImage = GetImageUrl("Design/Controls/UniGrid/Actions/Synchronize.png");

                    // Initialize tooltips
                    syncTooltip = GetString("general.synchronize");
                    deleteTooltip = GetString("general.delete");
                    viewTooltip = GetString("general.view");

                    plcContent.Visible = true;

                    // Initialize buttons
                    btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;");
                    btnCancel.Text = GetString("General.Cancel");
                    btnDeleteAll.Text = GetString("Tasks.DeleteAll");
                    btnDeleteSelected.Text = GetString("Tasks.DeleteSelected");
                    btnSyncAll.Text = GetString("Tasks.SyncAll");
                    btnSyncSelected.Text = GetString("Tasks.SyncSelected");
                    btnSyncSelected.OnClientClick = "return !" + tasksUniGrid.GetCheckSelectionScript();
                    btnDeleteAll.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("Tasks.ConfirmDeleteAll")) + ");";
                    btnDeleteSelected.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("general.confirmdelete")) + ");";

                    pnlLog.Visible = false;
                }
            }
        }

        ctlAsync.OnFinished += ctlAsync_OnFinished;
        ctlAsync.OnError += ctlAsync_OnError;
        ctlAsync.OnRequestLog += ctlAsync_OnRequestLog;
        ctlAsync.OnCancel += ctlAsync_OnCancel;
    }
예제 #32
0
 void Run(TaskInfo taskInfo)
 {
     taskInfo.task           = new Task(taskInfo.c);
     taskInfo.task.Finished += OnFinish;
 }
예제 #33
0
    void FlyTo()
    {
        GameCenter.mainPlayerMng.isStartingFlyEffect = false;
        GameCenter.curMainPlayer.ClearFlyEffect();

        for (int i = 0; i < flyExRefList.Count; i++)
        {
            if (flyExRefList[i].flyScence == sceneId)
            {
                sceneId = flyExRefList[i].goScence;
                point   = new Vector3(flyExRefList[i].goScenceXZ.x, 0, flyExRefList[i].goScenceXZ.y);
            }
        }
        if (point != Vector3.zero)
        {
            TaskInfo taskInfo = GameCenter.taskMng.CurfocusTask;
            if (sceneId == 0)
            {
                GameCenter.curMainPlayer.CancelCommands();
                GameCenter.curMainPlayer.StopForFly();
                Command_FlyTo flyTo = new Command_FlyTo();
                flyTo.targetScene = GameCenter.mainPlayerMng.MainPlayerInfo.SceneID;
                flyTo.targetPos   = point;
                flyTo.targetID    = targetID;
                GameCenter.curMainPlayer.commandMng.PushCommand(flyTo);

                if (taskInfo != null && taskInfo.TargetPos.x == point.x && taskInfo.TargetPos.y == point.y)
                {
                    GameCenter.taskMng.CurTaskNeedFly = true;
                }
                else
                {
                    GameCenter.taskMng.CurTaskNeedFly = false;
                }

                GameCenter.taskMng.CurTargetSceneID = 0;
                GameCenter.taskMng.CurTargetPoint   = Vector3.zero;
                GameCenter.taskMng.CurTargetID      = 0;
                //GameCenter.curMainPlayer.GoNormal();
                //Debug.Log("结束后ID为" + GameCenter.taskMng.CurTargetID);
            }
            else
            {
                GameCenter.curMainPlayer.CancelCommands();
                GameCenter.curMainPlayer.StopForFly();

                Command_FlyTo flyTo = new Command_FlyTo();
                flyTo.targetScene = sceneId;
                flyTo.targetPos   = point;
                flyTo.targetID    = targetID;
                GameCenter.curMainPlayer.commandMng.PushCommand(flyTo);

                if (taskInfo != null && taskInfo.TargetPos.x == point.x && taskInfo.TargetPos.y == point.y && taskInfo.ContentValue == sceneId)
                {
                    GameCenter.taskMng.CurTaskNeedFly = true;
                }
                else
                {
                    GameCenter.taskMng.CurTaskNeedFly = false;
                }

                GameCenter.taskMng.CurTargetSceneID = 0;
                GameCenter.taskMng.CurTargetPoint   = Vector3.zero;
                GameCenter.taskMng.CurTargetID      = 0;
                //GameCenter.curMainPlayer.GoNormal();
                //Debug.Log("结束后ID为" + GameCenter.taskMng.CurTargetID);
            }
        }
    }
예제 #34
0
    protected void btnOk_Click(object sender, EventArgs e)
    {
        // Validate date/time (blank date/time textbox is allowed)
        if ((dtpMailout.SelectedDateTime == DateTimeHelper.ZERO_TIME) && !String.IsNullOrEmpty(dtpMailout.DateTimeTextBox.Text.Trim()))
        {
            ShowErrorInternal(GetString("newsletterissue_send.invaliddatetime"));
            return;
        }

        // Get variants (IDs) to set
        List <string> selItems = null;

        if (drpAllSelected.SelectedValue == DDLIST_SETALL)
        {
            var issueIDs = IssueInfoProvider.GetIssues().Where(GetWhereCondition(ParentIssueID, true)).Column("IssueID");
            if (issueIDs.Any())
            {
                selItems = new List <string>();
                foreach (var issue in issueIDs)
                {
                    selItems.Add(issue.IssueID.ToString());
                }
            }
        }
        else if (drpAllSelected.SelectedValue == DDLIST_SETSELECTED)
        {
            selItems = grdElem.SelectedItems;
        }
        else
        {
            selItems = new List <string>();
            selItems.Add(drpAllSelected.SelectedValue);
        }

        // Check selected variants
        if ((selItems == null) || (selItems.Count <= 0))
        {
            if (drpAllSelected.SelectedValue != DDLIST_SETALL)
            {
                ShowErrorInternal(GetString("newsletterissue_send.novariantsselected"));
            }
            else
            {
                pMOut.Visible = false;
            }
            return;
        }

        DateTime when = (dtpMailout.SelectedDateTime == DateTimeHelper.ZERO_TIME) ? DateTime.Now : dtpMailout.SelectedDateTime;

        foreach (string itemId in selItems)
        {
            var issue = IssueInfoProvider.GetIssueInfo(ValidationHelper.GetInteger(itemId, 0));
            if (issue == null)
            {
                continue;
            }
            TaskInfo task = NewsletterTasksManager.EnsureMailoutTask(issue, DateTime.Now, false);
            task.TaskNextRunTime = when;
            TaskInfoProvider.SetTaskInfo(task);
            if (issue.IssueScheduledTaskID != task.TaskID)
            {
                issue.IssueScheduledTaskID = task.TaskID;
                IssueInfoProvider.SetIssueInfo(issue);
            }
        }

        mHighestMailoutTime = DateTime.MinValue;
        grdElem.ClearSelectedItems();
        grdElem.ReloadData();

        if (OnChanged != null)
        {
            OnChanged(this, EventArgs.Empty);
        }
    }
    protected void LoadData()
    {
        // Get newsletter object and check if exists
        Newsletter newsletterObj = NewsletterProvider.GetNewsletter(newsletterId);

        EditedObject = newsletterObj;

        // Initialize issue selectors
        int siteId = newsletterObj.NewsletterSiteID;

        subscriptionTemplate.WhereCondition   = "TemplateType='S' AND TemplateSiteID=" + siteId;
        unsubscriptionTemplate.WhereCondition = "TemplateType='U' AND TemplateSiteID=" + siteId;
        issueTemplate.WhereCondition          = "TemplateType='I' AND TemplateSiteID=" + siteId;
        optInSelector.WhereCondition          = "TemplateType='D' AND TemplateSiteID=" + siteId;

        // Check if the newsletter is dynamic and adjust config dialog
        isDynamic = newsletterObj.NewsletterType == NewsletterType.Dynamic;

        lblDynamic.Visible = pnlDynamic.Visible = lblNewsletterDynamicURL.Visible =
            txtNewsletterDynamicURL.Visible = plcUrl.Visible = chkSchedule.Visible =
                lblSchedule.Visible         = plcInterval.Visible = isDynamic;

        lblTemplateBased.Visible = lblIssueTemplate.Visible = issueTemplate.Visible = !isDynamic;

        if (RequestHelper.IsPostBack())
        {
            if (isDynamic)
            {
                schedulerInterval.Visible = chkSchedule.Checked;
            }
            else
            {
                plcInterval.Visible = false;
            }

            return;
        }

        // Fill config dialog with newsletter data
        GetNewsletterValues(newsletterObj);

        if (!isDynamic)
        {
            issueTemplate.Value = newsletterObj.NewsletterTemplateID.ToString();
            return;
        }

        // Check if dynamic newsletter subject is empty
        bool subjectEmpty = string.IsNullOrEmpty(newsletterObj.NewsletterDynamicSubject);

        radPageTitle.Checked = subjectEmpty;
        radFollowing.Checked = !subjectEmpty;
        radPageTitle_CheckedChanged(null, null);
        if (!subjectEmpty)
        {
            txtSubject.Text = newsletterObj.NewsletterDynamicSubject;
        }

        txtNewsletterDynamicURL.Text = newsletterObj.NewsletterDynamicURL;

        TaskInfo task = TaskInfoProvider.GetTaskInfo(newsletterObj.NewsletterDynamicScheduledTaskID);

        if (task != null)
        {
            chkSchedule.Checked = plcInterval.Visible = true;
            schedulerInterval.ScheduleInterval = task.TaskInterval;
        }
        else
        {
            chkSchedule.Checked       = false;
            schedulerInterval.Visible = false;
        }
    }
예제 #36
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(HTMLHelper.HTMLEncode(result));
        }

        case "MailoutTime":
        {
            string      result;
            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(HTMLHelper.HTMLEncode(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);
    }
예제 #37
0
 public void Execute(TaskInfo task = null)
 {
     LoggerFactory.GetLogger().Error($"执行取消订单第{i}次");
     i++;
 }
예제 #38
0
 public TaskInfoNodeFactory(TaskInfo taskInfo)
 {
     _taskInfo = taskInfo;
 }
예제 #39
0
        public async Task <string[]> GetFiles(string path, bool recursive)
        {
            await Connect();

            List <string> list   = new List <string>();
            DatastorePath dsPath = new DatastorePath(path);

            RetrievePropertiesResponse response = await _vim.RetrievePropertiesAsync(
                _props, FilterFactory.DatastoreFilter(_res));

            ObjectContent[] oc = response.returnval;

            foreach (ObjectContent obj in oc)
            {
                ManagedObjectReference dsBrowser = (ManagedObjectReference)obj.propSet[0].val;
                string dsName = ((DatastoreSummary)obj.propSet[1].val).name;
                if (dsName == dsPath.Datastore)
                {
                    ManagedObjectReference task = null;
                    TaskInfo info = null;
                    HostDatastoreBrowserSearchSpec spec = new HostDatastoreBrowserSearchSpec
                    {
                        matchPattern = new string[] { dsPath.File }
                    };
                    List <HostDatastoreBrowserSearchResults> results = new List <HostDatastoreBrowserSearchResults>();
                    if (recursive)
                    {
                        task = await _vim.SearchDatastoreSubFolders_TaskAsync(
                            dsBrowser, dsPath.FolderPath, spec);

                        info = await WaitForVimTask(task);

                        if (info.result != null)
                        {
                            results.AddRange((HostDatastoreBrowserSearchResults[])info.result);
                        }
                    }
                    else
                    {
                        task = await _vim.SearchDatastore_TaskAsync(
                            dsBrowser, dsPath.FolderPath, spec);

                        info = await WaitForVimTask(task);

                        if (info.result != null)
                        {
                            results.Add((HostDatastoreBrowserSearchResults)info.result);
                        }
                    }

                    foreach (HostDatastoreBrowserSearchResults result in results)
                    {
                        if (result != null && result.file != null && result.file.Length > 0)
                        {
                            string fp = result.folderPath;
                            if (!fp.EndsWith("/"))
                            {
                                fp += "/";
                            }

                            list.AddRange(result.file.Select(o => fp + o.path));
                        }
                    }
                }
            }
            return(list.ToArray());
        }
예제 #40
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script for pendingCallbacks repair
        ScriptHelper.FixPendingCallbacks(Page);

        // Initialize current user for the async actions
        currentUser = CMSContext.CurrentUser;

        if (!RequestHelper.IsCallback())
        {
            // Check 'Manage object tasks' permission
            if (!currentUser.IsAuthorizedPerResource("cms.staging", "ManageAllTasks"))
            {
                RedirectToAccessDenied("cms.staging", "ManageAllTasks");
            }

            currentSiteId = CMSContext.CurrentSiteID;
            currentSiteName = CMSContext.CurrentSiteName;

            // Register the dialog script
            ScriptHelper.RegisterDialogScript(this);
            serverId = QueryHelper.GetInteger("serverid", 0);

            // Get the selected types
            ObjectTypeTreeNode selectedNode = TaskInfoProvider.ObjectTree.FindNode(objectType, (siteId > 0));
            objectType = (selectedNode != null) ? selectedNode.GetObjectTypes(true) : string.Empty;

            // Setup title
            titleElem.TitleImage = GetImageUrl("/CMSModules/CMS_Staging/synchronization.png");

            if (!RequestHelper.CausedPostback(btnSyncSelected, btnSyncAll))
            {
                // Initialize images
                viewImage = GetImageUrl("Design/Controls/UniGrid/Actions/View.png");
                deleteImage = GetImageUrl("Design/Controls/UniGrid/Actions/Delete.png");
                syncImage = GetImageUrl("Design/Controls/UniGrid/Actions/Synchronize.png");

                // Initialize tooltips
                syncTooltip = GetString("general.synchronize");
                deleteTooltip = GetString("general.delete");
                viewTooltip = GetString("general.view");
                syncCurrent = GetString("ObjectTasks.SyncCurrent");

                plcContent.Visible = true;

                // Initialize buttons
                btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;");
                btnCancel.Text = GetString("General.Cancel");
                btnDeleteAll.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("Tasks.ConfirmDeleteAll")) + ");";
                btnDeleteSelected.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("general.confirmdelete")) + ");";
                btnSyncSelected.OnClientClick = "return !" + gridTasks.GetCheckSelectionScript();

                // Initialize grid
                gridTasks.ZeroRowsText = GetString("Tasks.NoTasks");
                gridTasks.OnAction += gridTasks_OnAction;
                gridTasks.OnDataReload += gridTasks_OnDataReload;
                gridTasks.OnExternalDataBound += gridTasks_OnExternalDataBound;
                gridTasks.ShowActionsMenu = true;
                gridTasks.Columns = "TaskID, TaskSiteID, TaskDocumentID, TaskNodeAliasPath, TaskTitle, TaskTime, TaskType, TaskObjectType, TaskObjectID, TaskRunning, (SELECT COUNT(*) FROM Staging_Synchronization WHERE SynchronizationTaskID = TaskID AND SynchronizationErrorMessage IS NOT NULL AND (SynchronizationServerID = @ServerID OR (@ServerID = 0 AND (@TaskSiteID = 0 OR SynchronizationServerID IN (SELECT ServerID FROM Staging_Server WHERE ServerSiteID = @TaskSiteID AND ServerEnabled=1))))) AS FailedCount";
                TaskInfo ti = new TaskInfo();
                gridTasks.AllColumns = SqlHelperClass.MergeColumns(ti.ColumnNames.ToArray());

                pnlLog.Visible = false;
            }
        }

        ctlAsync.OnFinished += ctlAsync_OnFinished;
        ctlAsync.OnError += ctlAsync_OnError;
        ctlAsync.OnRequestLog += ctlAsync_OnRequestLog;
        ctlAsync.OnCancel += ctlAsync_OnCancel;
    }
예제 #41
0
    /// <summary>
    /// Actions handler.
    /// </summary>
    protected void HeaderActions_ActionPerformed(object sender, CommandEventArgs e)
    {
        if (ContactGroupHelper.AuthorizedModifyContactGroup(SiteID, true))
        {
            switch (e.CommandName.ToLowerCSafe())
            {
                case "save":
                    if (chkDynamic.Checked)
                    {
                        // Get scheduled interval string
                        scheduleInterval = schedulerInterval.ScheduleInterval;
                    }

                    // Save changes in the contact group
                    if (EditForm.SaveData(null))
                    {
                        mBtnEvaluate.Visible = chkDynamic.Checked;
                        ScriptHelper.RefreshTabHeader(Page, 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);

                                    // Initialize interval control
                                    schedulerInterval.ScheduleInterval = task.TaskInterval;
                                    schedulerInterval.ReloadData();
                                }
                            }

                            // Display basic info about dynamic contact group
                            InitInfoPanel(cgi, false);
                        }
                    }
                    break;
            }
        }
    }
예제 #42
0
 private bool TryGetTransferValue(UUID textureID, out TaskInfo task)
 {
     lock (_Transfers)
         return _Transfers.TryGetValue(textureID, out task);
 }
예제 #43
0
        //id, feature (iso, net, boot, guest), label, value
        public async Task <Vm> ReconfigureVm(string id, string feature, string label, string newvalue)
        {
            await Connect();

            Vm vm = _vmCache[id];
            RetrievePropertiesResponse response = await _vim.RetrievePropertiesAsync(
                _props,
                FilterFactory.VmFilter(vm.AsVim(), "config"));

            ObjectContent[] oc = response.returnval;

            VirtualMachineConfigInfo config = (VirtualMachineConfigInfo)oc[0].GetProperty("config");
            VirtualMachineConfigSpec vmcs   = new VirtualMachineConfigSpec();

            switch (feature)
            {
            case "iso":
                VirtualCdrom cdrom = (VirtualCdrom)((label.HasValue())
                        ? config.hardware.device.Where(o => o.deviceInfo.label == label).SingleOrDefault()
                        : config.hardware.device.OfType <VirtualCdrom>().FirstOrDefault());

                if (cdrom != null)
                {
                    if (cdrom.backing.GetType() != typeof(VirtualCdromIsoBackingInfo))
                    {
                        cdrom.backing = new VirtualCdromIsoBackingInfo();
                    }

                    ((VirtualCdromIsoBackingInfo)cdrom.backing).fileName = newvalue;
                    cdrom.connectable = new VirtualDeviceConnectInfo
                    {
                        connected      = true,
                        startConnected = true
                    };

                    vmcs.deviceChange = new VirtualDeviceConfigSpec[] {
                        new VirtualDeviceConfigSpec {
                            device             = cdrom,
                            operation          = VirtualDeviceConfigSpecOperation.edit,
                            operationSpecified = true
                        }
                    };
                }
                break;

            case "net":
            case "eth":
                VirtualEthernetCard card = (VirtualEthernetCard)((label.HasValue())
                        ? config.hardware.device.Where(o => o.deviceInfo.label == label).SingleOrDefault()
                        : config.hardware.device.OfType <VirtualEthernetCard>().FirstOrDefault());

                if (card != null)
                {
                    _netman.UpdateEthernetCardBacking(card, newvalue);

                    vmcs.deviceChange = new VirtualDeviceConfigSpec[] {
                        new VirtualDeviceConfigSpec {
                            device             = card,
                            operation          = VirtualDeviceConfigSpecOperation.edit,
                            operationSpecified = true
                        }
                    };
                }
                break;

            case "boot":
                int delay = 0;
                if (Int32.TryParse(newvalue, out delay))
                {
                    vmcs.AddBootOption(delay);
                }
                break;

            case "guest":
                if (newvalue.HasValue() && !newvalue.EndsWith("\n"))
                {
                    newvalue += "\n";
                }
                vmcs.annotation = config.annotation + newvalue;
                if (vm.State == VmPowerState.Running && vmcs.annotation.HasValue())
                {
                    vmcs.AddGuestInfo(Regex.Split(vmcs.annotation, "\r\n|\r|\n"));
                }
                break;

            default:
                throw new Exception("Invalid change request.");
                //break;
            }

            ManagedObjectReference task = await _vim.ReconfigVM_TaskAsync(vm.AsVim(), vmcs);

            TaskInfo info = await WaitForVimTask(task);

            if (info.state == TaskInfoState.error)
            {
                throw new Exception(info.error.localizedMessage);
            }
            return(await GetVirtualMachine(vm.AsVim()));
        }
예제 #44
0
    public void AddProviderEvents(ITraceParserServices source, Action<TraceEvent> callback)
    {
        if (error != null)
            return;
        if (!inited)
            Init();
        try
        {
            Dictionary<string, int> opcodes = new Dictionary<string, int>();
            opcodes.Add("win:Info", 0);
            opcodes.Add("win:Start", 1);
            opcodes.Add("win:Stop", 2);
            opcodes.Add("win:DC_Start", 3);
            opcodes.Add("win:DC_End", 4);
            opcodes.Add("win:Extension", 5);
            opcodes.Add("win:Reply", 6);
            opcodes.Add("win:Resume", 7);
            opcodes.Add("win:Suspend", 8);
            opcodes.Add("win:Send", 9);
            opcodes.Add("win:Receive", 240);
            Dictionary<string, TaskInfo> tasks = new Dictionary<string, TaskInfo>();
            Dictionary<string, DynamicTraceEventData> templates = new Dictionary<string, DynamicTraceEventData>();
            while (reader.Read())
            {
                // TODO I currently require opcodes,and tasks BEFORE events BEFORE templates.
                // Can be fixed by going multi-pass.
                switch (reader.Name)
                {
                    case "event":
                        {
                            int taskNum = 0;
                            Guid taskGuid = Guid;
                            string taskName = reader.GetAttribute("task");
                            if (taskName != null)
                            {
                                TaskInfo taskInfo;
                                if (tasks.TryGetValue(taskName, out taskInfo))
                                {
                                    taskNum = taskInfo.id;
                                    taskGuid = taskInfo.guid;
                                }
                            }
                            else
                                taskName = "";

                            int opcode = 0;
                            string opcodeName = reader.GetAttribute("opcode");
                            if (opcodeName != null)
                            {
                                opcode = opcodes[opcodeName];
                                // Strip off any namespace prefix (TODO is this a good idea?
                                int colon = opcodeName.IndexOf(':');
                                if (colon >= 0)
                                    opcodeName = opcodeName.Substring(colon + 1);
                            }
                            else
                            {
                                // TODO: Improve this.
                                // If we don't have an opcode (which is bad, since it does not work on XP),
                                opcodeName = reader.GetAttribute("name");
                                if (taskName != null && opcodeName.StartsWith(taskName))
                                    opcodeName = opcodeName.Substring(taskName.Length);
                            }

                            int eventID = int.Parse(reader.GetAttribute("value"));

                            DynamicTraceEventData eventTemplate = new DynamicTraceEventData(
                            callback, eventID, taskNum, taskName, taskGuid, opcode, opcodeName, Guid, Name);

                            string templateName = reader.GetAttribute("template");
                            if (templateName != null)
                                templates[templateName] = eventTemplate;
                            else
                            {
                                eventTemplate.payloadNames = new string[0];
                                eventTemplate.payloadFetches = new DynamicTraceEventData.PayloadFetch[0];
                                source.RegisterEventTemplate(eventTemplate);
                            }
                        } break;
                    case "template":
                        {
                            string templateName = reader.GetAttribute("tid");
                            Debug.Assert(templateName != null);
                            DynamicTraceEventData eventTemplate = templates[templateName];
                            try
                            {
                                ComputeFieldInfo(eventTemplate, reader.ReadSubtree());
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("Error: Exception during processing template {0}: {1}", templateName, e.ToString());
                                throw;
                            }
                            source.RegisterEventTemplate(eventTemplate);
                            templates.Remove(templateName);
                        } break;
                    case "opcode":
                        opcodes.Add(reader.GetAttribute("name"), int.Parse(reader.GetAttribute("value")));
                        break;
                    case "task":
                        {
                            TaskInfo info = new TaskInfo();
                            info.id = int.Parse(reader.GetAttribute("value"));
                            string guidString = reader.GetAttribute("eventGUID");
                            if (guidString != null)
                                info.guid = new Guid(guidString);
                            tasks.Add(reader.GetAttribute("name"), info);
                        } break;
                }
            }

            // TODO Register any events with undefined templates as having empty payloads (can rip out after 1/2009)
            foreach (DynamicTraceEventData eventTemplate in templates.Values)
            {
                eventTemplate.payloadNames = new string[0];
                eventTemplate.payloadFetches = new DynamicTraceEventData.PayloadFetch[0];
                source.RegisterEventTemplate(eventTemplate);
            }
        }
        catch (Exception e)
        {
            Debug.Assert(false, "Exception during manifest parsing");
            Console.WriteLine("Error: Exception during processing of in-log manifest for provider {0}.  Symbolic information may not be complete.", Name);
            error = e;
        }
        inited = false;     // If we call it again, start over from the begining.
    }
    /// <summary>
    /// Create schedule task.
    /// </summary>
    private void CreateTask()
    {
        try
        {
            var editedObject = TypedEditedObject;

            TaskInfo task = new TaskInfo();
            task.TaskAssemblyName = "CMS.Newsletters";
            task.TaskClass = "CMS.Newsletters.DynamicNewsletterSender";
            task.TaskDisplayName = GetString("DynamicNewsletter.TaskName") + editedObject.NewsletterDisplayName;
            task.TaskEnabled = true;
            task.TaskInterval = ScheduleInterval.ScheduleInterval;
            task.TaskLastResult = string.Empty;
            task.TaskName = "DynamicNewsletter." + ValidationHelper.GetCodeName(editedObject.NewsletterName, "_");
            task.TaskSiteID = SiteContext.CurrentSiteID;
            task.TaskNextRunTime = SchedulingHelper.GetNextTime(task.TaskInterval, new DateTime(), new DateTime());
            task.TaskData = editedObject.NewsletterGUID.ToString();
            // Set task for processing in external service
            task.TaskAllowExternalService = true;
            task.TaskUseExternalService = (SchedulingHelper.UseExternalService && NewsletterHelper.UseExternalServiceForDynamicNewsletters(SiteContext.CurrentSiteName));
            task.TaskType = ScheduledTaskTypeEnum.System;

            TaskInfoProvider.SetTaskInfo(task);

            editedObject.NewsletterDynamicScheduledTaskID = task.TaskID;
            NewsletterInfoProvider.SetNewsletterInfo(editedObject);

            Redirect();
        }
        catch (Exception ex)
        {
            ShowError(GetString(ex.Message));
        }
    }
예제 #46
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 = ScoreInfo.Provider.Get(scoreID);

        if (info == null)
        {
            return;
        }

        // "Recalculation scheduled" status
        if (info.ScoreScheduledTaskID > 0)
        {
            TaskInfo taskInfo = TaskInfo.Provider.Get(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 (!CurrentUser.IsAuthorizedPerResource(ModuleNameForPermissionCheck, PermissionsEnum.Modify.ToString()))
        {
            mButtonRecalculate.Enabled = false;
            mButtonRecalculate.Tooltip = GetString("general.modifynotallowed");
        }
    }
예제 #47
0
        public bool PushEventToClients(BaseEvent baseEvent)
        {
            bool result = false;
            subscribers.ForEach(delegate(IMainGateCallback callback) {
                                    if (((ICommunicationObject) callback).State != CommunicationState.Opened) {
                                        InstantLogger.log(
                                            callback.ToString() + " is \"" +
                                            ((ICommunicationObject) callback).State.ToString() + "\"",
                                            "Dead callback is removed", InstantLogger.TypeMessage.warning);
                                        subscribers.Remove(callback);
                                    }
                                });
            try {
                bool firstLoop = true;
                foreach (var callback in subscribers) {
                    if (((ICommunicationObject) callback).State == CommunicationState.Opened) {
                        TaskInfo ti = new TaskInfo(baseEvent, callback);
                        result = System.Threading.ThreadPool.QueueUserWorkItem(new WaitCallback(OnEventTask), ti);
                        if (firstLoop) {
                            InstantLogger.log(baseEvent.ToString(),
                                              "message is delivered -- OnEvent processing initiated",
                                              InstantLogger.TypeMessage.unimportant);
                            firstLoop = false;
                        }
                        //callback.OnEvent(baseEvent);
                        result = true;
                    }
                    else {
                        InstantLogger.log(baseEvent.ToString(), "message is not delivered",
                                          InstantLogger.TypeMessage.important);
                        //subscribers.Remove(callback);
                    }
                }
            }
            catch (Exception e) {
                InstantLogger.err("source exception:\n{0}", e.ToString());
                result = false;
            }
            //subscribers.ForEach(delegate(IMainGateCallback callback)
            //{
            //    if (((ICommunicationObject)callback).State == CommunicationState.Opened)
            //    {
            //        InstantLogger.log(baseEvent.ToString(), "message is delivered", InstantLogger.TypeMessage.unimportant);
            //        callback.OnEvent(baseEvent);
            //        result = true;
            //    }
            //    else
            //    {
            //        InstantLogger.log(baseEvent.ToString(), "message is not delivered", InstantLogger.TypeMessage.important);
            //        //subscribers.Remove(callback);
            //    }

            //});

            return result;
        }
예제 #48
0
        public void GetVirtualDiskFilesForHost()
        {
            try
            {
                _service = ecb.getConnection().Service;
                _sic     = ecb.getConnection().ServiceContent;

                ArrayList supportedVersions = VersionUtil.getSupportedVersions(ecb.get_option("url"));
                ManagedObjectReference hmor = _service.FindByIp(ecb.getConnection().ServiceContent.searchIndex, null, ecb.get_option("hostip"), false);
                if (hmor == null)
                {
                    Console.WriteLine("Unable to find host with IP : " + ecb.get_option("hostip") + " in Inventory");
                }
                else
                {
                    if (VersionUtil.isApiVersionSupported(supportedVersions, "2.5"))
                    {
                        Object[] datastores = getProperties(hmor, new String[] { "datastore" });
                        Console.WriteLine("Searching The Datastores");
                        ManagedObjectReference[] dstoreArr = datastores[0] as ManagedObjectReference[];
                        foreach (ManagedObjectReference dstore in dstoreArr)
                        {
                            ManagedObjectReference dsBrowser =
                                ecb.getServiceUtil().GetMoRefProp(dstore, "browser");
                            ObjectContent[]  objary = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, dstore, new String[] { "summary" });
                            DatastoreSummary ds     = objary[0].propSet[0].val as DatastoreSummary;
                            String           dsName = ds.name;
                            Console.WriteLine("");
                            Console.WriteLine("Searching The Datastore " + dsName);
                            VmDiskFileQueryFilter vdiskFilter = new VmDiskFileQueryFilter();
                            String[] type = { "VirtualIDEController" };
                            vdiskFilter.controllerType = type;
                            Boolean flag = VersionUtil.isApiVersionSupported(supportedVersions, "4.0");
                            if (flag)
                            {
                                vdiskFilter.thin = true;
                            }
                            VmDiskFileQuery fQuery = new VmDiskFileQuery();
                            fQuery.filter = vdiskFilter;

                            HostDatastoreBrowserSearchSpec searchSpec = new HostDatastoreBrowserSearchSpec();

                            FileQuery[] arr = { fQuery };
                            searchSpec.query = arr;
                            //searchSpec.setMatchPattern(matchPattern);

                            ManagedObjectReference taskmor = _service.SearchDatastoreSubFolders_Task(dsBrowser, "[" + dsName + "]", searchSpec);

                            object[] result = ecb.getServiceUtil().WaitForValues(taskmor, new string[] { "info.state", "info.result" },
                                                                                 new string[] { "state" }, // info has a property - state for state of the task
                                                                                 new object[][] { new object[] { TaskInfoState.success, TaskInfoState.error } }
                                                                                 );

                            // Wait till the task completes.
                            if (result[0].Equals(TaskInfoState.success))
                            {
                                ObjectContent[] objTaskInfo = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, taskmor, new String[] { "info" });
                                TaskInfo        tInfo       = (TaskInfo)objTaskInfo[0].propSet[0].val;;
                                HostDatastoreBrowserSearchResults[] searchResult = (HostDatastoreBrowserSearchResults[])tInfo.result;

                                int len = searchResult.Length;
                                for (int j = 0; j < len; j++)
                                {
                                    HostDatastoreBrowserSearchResults sres
                                        = searchResult[j];
                                    FileInfo[] fileArray = sres.file;
                                    if (fileArray != null)
                                    {
                                        for (int z = 0; z < fileArray.Length; z++)
                                        {
                                            Console.WriteLine("Virtual Disks Files " + fileArray[z].path);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("No Thin-provisioned Virtual Disks Files found");
                                    }
                                }
                            }
                            else
                            {
                                Console.WriteLine("SearchDatastoreSubFolders Task couldn't be completed successfully");
                            }
                        }
                    }
                    else
                    {
                        Object[] datastores = getProperties(hmor, new String[] { "datastore" });
                        Console.WriteLine("Searching The Datastores");
                        ManagedObjectReference[] dstoreArr = datastores[0] as ManagedObjectReference[];
                        foreach (ManagedObjectReference dstore in dstoreArr)
                        {
                            ManagedObjectReference dsBrowser = (ManagedObjectReference)
                                                               ecb.getServiceUtil().GetMoRefProp(dstore, "browser");
                            ObjectContent[]  objary = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, dstore, new String[] { "summary" });
                            DatastoreSummary ds     = objary[0].propSet[0].val as DatastoreSummary;

                            String dsName = ds.name;
                            Console.WriteLine("");
                            Console.WriteLine("Searching The Datastore " + dsName);
                            HostDatastoreBrowserSearchSpec searchSpec = new HostDatastoreBrowserSearchSpec();
                            ManagedObjectReference         taskmor    = _service.SearchDatastoreSubFolders_Task(dsBrowser, "[" + dsName + "]", searchSpec);
                            object[] result = ecb.getServiceUtil().WaitForValues(taskmor, new string[] { "info.state", "info.result" },
                                                                                 new string[] { "state" }, // info has a property - state for state of the task
                                                                                 new object[][] { new object[] { TaskInfoState.success, TaskInfoState.error } }
                                                                                 );
                            // Wait till the task completes.
                            if (result[0].Equals(TaskInfoState.success))
                            {
                                ObjectContent[] objTaskInfo = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, taskmor, new String[] { "info" });
                                TaskInfo        tInfo       = (TaskInfo)objTaskInfo[0].propSet[0].val;;
                                HostDatastoreBrowserSearchResults[] searchResult = (HostDatastoreBrowserSearchResults[])tInfo.result;
                                int len = searchResult.Length;
                                for (int j = 0; j < len; j++)
                                {
                                    HostDatastoreBrowserSearchResults sres
                                        = searchResult[j];
                                    FileInfo[] fileArray = sres.file;
                                    for (int z = 0; z < fileArray.Length; z++)
                                    {
                                        Console.WriteLine("Virtual Disks Files " + fileArray[z].path);
                                    }
                                }
                            }
                            else
                            {
                                Console.WriteLine("SearchDatastoreSubFolders Task couldn't be completed successfully");
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ecb.log.LogLine("VirtualDiskFiles : Failed Connect");
                throw e;
            }
            finally
            {
                ecb.log.LogLine("Ended VirtualDiskFiles");
                ecb.log.Close();
            }
        }
    /// <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")).Result;

        if ((errorMessage == String.Empty) && !schedInterval.CheckIntervalPreceedings())
        {
            errorMessage = GetString("Task_Edit.BetweenIntervalPreceedingsError");
        }

        if ((errorMessage == String.Empty) && !schedInterval.CheckOneDayMinimum())
        {
            errorMessage = GetString("Task_Edit.AtLeastOneDayError");
        }

        if ((errorMessage == String.Empty) && !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.GetNextTime(TaskInfo.TaskInterval, new DateTime(), new DateTime());

            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()));
        }
    }
        private void EditGroupBoardFirst_SearchBoxTextChanged(object sender, EventArgs e)
        {
            _currentTask?.CancelTask();

            _currentTask = new TaskInfo(SearchGroup, sender);
        }
        private void getdata()
        {
            DataTable table = dbOperation.GetDbHelper().GetDataSet(string.Format("call p_task_report_country('{0}','{1}','{2}')",
                                Sj,DeptId,ItemId)).Tables[0];
            currenttable = table;
            list.Clear();
            for (int i = 0; i < table.Rows.Count; i++)
            {
                TaskInfo info = new TaskInfo();
                //info.DeptId = table.Rows[i][0].ToString();
                info.DeptName = table.Rows[i][1].ToString();
                //info.ItemId = table.Rows[i][2].ToString();
                info.ItemName = table.Rows[i][3].ToString();
                info.TaskTheory = table.Rows[i][4].ToString();
                info.TaskActual = table.Rows[i][5].ToString();
                info.TaskPercent = table.Rows[i][6].ToString();
                info.SumTheory = table.Rows[i][7].ToString();
                info.SumActual = table.Rows[i][8].ToString();
                info.SumPercent = table.Rows[i][9].ToString();
                list.Add(info);
            }

            //得到行和列标题 及数量            
            string[] DeptNames = list.Select(t => t.DeptName).Distinct().ToArray();
            string[] ItemNames = list.Select(t => t.ItemName).Distinct().ToArray();

            //创建DataTable
            DataTable tabledisplay = new DataTable();

            //表中第一行第一列交叉处一般显示为第1列标题
            tabledisplay.Columns.Add(new DataColumn("序号"));
            MyColumns.Add("序号", new MyColumn("序号", "序号") { BShow = true, Width = 5 });
            tabledisplay.Columns.Add(new DataColumn("区县名称"));
            MyColumns.Add("区县名称", new MyColumn("区县名称", "区县名称") { BShow = true, Width = 16 });
                   

            //表中后面每列的标题其实是列分组的关键字
            for (int i = 0; i < ItemNames.Length; i++)
            {
                DataColumn column = new DataColumn(ItemNames[i]);
                tabledisplay.Columns.Add(column);
                MyColumns.Add(ItemNames[i].ToString(), new MyColumn(ItemNames[i].ToString(), ItemNames[i].ToString()) { BShow = true, Width = 10 });
                tabledisplay.Columns.Add(new DataColumn("任务完成率" + i));
                MyColumns.Add("任务完成率" + i, new MyColumn("任务完成率" + i, "任务完成率") { BShow = true, Width = 10 });
            }

            //当选择了检测项目作为查询条件时,不显示任务完成总量和任务总完成率
            bool flag;
            if (ItemId == "")
            {
                flag = true;
            }
            else
            {
                flag = false;
            }
            //表格后面为合计列
            tabledisplay.Columns.Add(new DataColumn("任务完成总量"));
            MyColumns.Add("任务完成总量", new MyColumn("任务完成总量", "任务完成总量") { BShow = flag, Width = 10 });
            tabledisplay.Columns.Add(new DataColumn("任务总完成率"));
            MyColumns.Add("任务总完成率", new MyColumn("任务总完成率", "任务总完成率") { BShow = flag, Width = 10 });

            //为表中各行生成数据
            for (int i = 0; i < DeptNames.Length; i++)
            {
                var row = tabledisplay.NewRow();
                //每行第0列为行分组关键字
                row[0] = i + 1;
                row[1] = DeptNames[i];
                //每行的其余列为行列交叉对应的汇总数据
                for (int j = 0; j < ItemNames.Length; j++)
                {
                    string num = list.Where(t => t.DeptName == DeptNames[i] && t.ItemName == ItemNames[j]).Select(t => t.TaskActual).FirstOrDefault();

                    if (num == null || num == "")
                    {
                        num = '0'.ToString();
                    }
                    row[ItemNames[j]] = num;

                    string percent = list.Where(t => t.DeptName == DeptNames[i] && t.ItemName == ItemNames[j]).Select(t => t.TaskPercent).FirstOrDefault();

                    if (percent == null || percent == "")
                    {
                        percent = '0'.ToString();
                    }
                    else
                    {
                        percent = percent + "%";
                    }
                    row[3 + 2 * j] = percent;
                }
                row[ItemNames.Length * 2 + 2] = list.Where(t => t.DeptName == DeptNames[i]).Select(t => t.SumActual).FirstOrDefault();

                string sumpercent = list.Where(t => t.DeptName == DeptNames[i]).Select(t => t.SumPercent).FirstOrDefault();

                if (sumpercent == null || sumpercent == "")
                {
                    sumpercent = '0'.ToString();
                }
                else
                {
                    sumpercent = sumpercent + "%";
                }
                row[ItemNames.Length * 2 + 3] = sumpercent;


                tabledisplay.Rows.Add(row);
            }
            _tableview.MyColumns = MyColumns;
            _tableview.BShowDetails = true;
            _tableview.Table = tabledisplay;
        }
예제 #52
0
        private void _query_Click(object sender, RoutedEventArgs e)
        {
            item_id = _detect_item.SelectedIndex < 1 ? "" : (_detect_item.SelectedItem as Label).Tag.ToString();

            grid_info.Children.Clear();
            grid_info.Children.Add(_tableview);
            MyColumns.Clear();

            DataTable table = dbOperation.GetDbHelper().GetDataSet(string.Format("call p_task_report('{0}','{1}','{2}','{3}')",
                                                                                 (Application.Current.Resources["User"] as UserInfo).ID,
                                                                                 _year.Text,
                                                                                 _detect_dept.SelectedIndex < 1 ? "" : (_detect_dept.SelectedItem as Label).Tag,
                                                                                 item_id)).Tables[0];

            currenttable = table;
            list.Clear();
            for (int i = 0; i < table.Rows.Count; i++)
            {
                TaskInfo info = new TaskInfo();
                //info.DeptId = table.Rows[i][0].ToString();
                info.DeptName = table.Rows[i][1].ToString();
                //info.ItemId = table.Rows[i][2].ToString();
                info.ItemName    = table.Rows[i][3].ToString();
                info.TaskTheory  = table.Rows[i][4].ToString();
                info.TaskActual  = table.Rows[i][5].ToString();
                info.TaskPercent = table.Rows[i][6].ToString();
                info.SumTheory   = table.Rows[i][7].ToString();
                info.SumActual   = table.Rows[i][8].ToString();
                info.SumPercent  = table.Rows[i][9].ToString();
                list.Add(info);
            }

            //得到行和列标题 及数量
            string[] DeptNames = list.Select(t => t.DeptName).Distinct().ToArray();
            string[] ItemNames = list.Select(t => t.ItemName).Distinct().ToArray();

            //创建DataTable
            DataTable tabledisplay = new DataTable();

            //表中第一行第一列交叉处一般显示为第1列标题
            tabledisplay.Columns.Add(new DataColumn("序号"));
            MyColumns.Add("序号", new MyColumn("序号", "序号")
            {
                BShow = true, Width = 5
            });
            //switch (user_flag_tier)
            //{
            //    case "0": tabledisplay.Columns.Add(new DataColumn("省名称"));
            //        MyColumns.Add("省名称", new MyColumn("省名称", "省名称") { BShow = true, Width = 16 });
            //        break;
            //    case "1": tabledisplay.Columns.Add(new DataColumn("市(州)单位名称"));
            //        MyColumns.Add("市(州)单位名称", new MyColumn("市(州)单位名称", "市(州)单位名称") { BShow = true, Width = 16 });
            //        break;
            //    case "2": tabledisplay.Columns.Add(new DataColumn("区县名称"));
            //        MyColumns.Add("区县名称", new MyColumn("区县名称", "区县名称") { BShow = true, Width = 16 });
            //        break;
            //    case "3": tabledisplay.Columns.Add(new DataColumn("检测单位名称"));
            //        MyColumns.Add("检测单位名称", new MyColumn("检测单位名称", "检测单位名称") { BShow = true, Width = 16 });
            //        break;
            //    case "4": tabledisplay.Columns.Add(new DataColumn("检测单位名称"));
            //        MyColumns.Add("检测单位名称", new MyColumn("检测单位名称", "检测单位名称") { BShow = true, Width = 16 });
            //        break;
            //    default: break;
            //}
            tabledisplay.Columns.Add(new DataColumn("部门名称"));
            MyColumns.Add("部门名称", new MyColumn("部门名称", "部门名称")
            {
                BShow = true, Width = 16
            });

            //表中后面每列的标题其实是列分组的关键字
            for (int i = 0; i < ItemNames.Length; i++)
            {
                DataColumn column = new DataColumn(ItemNames[i]);
                tabledisplay.Columns.Add(column);
                MyColumns.Add(ItemNames[i].ToString().ToLower(), new MyColumn(ItemNames[i].ToString().ToLower(), ItemNames[i].ToString())
                {
                    BShow = true, Width = 10
                });
                tabledisplay.Columns.Add(new DataColumn("任务完成率" + i));
                MyColumns.Add("任务完成率" + i, new MyColumn("任务完成率" + i, "任务完成率")
                {
                    BShow = true, Width = 10
                });
            }

            //当选择了检测项目作为查询条件时,不显示任务完成总量和任务总完成率
            bool flag;

            if (item_id == "")
            {
                flag = true;
            }
            else
            {
                flag = false;
            }

            //表格后面为合计列
            tabledisplay.Columns.Add(new DataColumn("任务完成总量"));
            MyColumns.Add("任务完成总量", new MyColumn("任务完成总量", "任务完成总量")
            {
                BShow = flag, Width = 10
            });
            tabledisplay.Columns.Add(new DataColumn("任务总完成率"));
            MyColumns.Add("任务总完成率", new MyColumn("任务总完成率", "任务总完成率")
            {
                BShow = flag, Width = 10
            });

            //为表中各行生成数据
            for (int i = 0; i < DeptNames.Length; i++)
            {
                var row = tabledisplay.NewRow();
                //每行第0列为行分组关键字
                row[0] = i + 1;
                row[1] = DeptNames[i];
                //每行的其余列为行列交叉对应的汇总数据
                for (int j = 0; j < ItemNames.Length; j++)
                {
                    string num = list.Where(t => t.DeptName == DeptNames[i] && t.ItemName == ItemNames[j]).Select(t => t.TaskActual).FirstOrDefault();

                    if (num == null || num == "")
                    {
                        num = '0'.ToString();
                    }
                    row[ItemNames[j]] = num;

                    string percent = list.Where(t => t.DeptName == DeptNames[i] && t.ItemName == ItemNames[j]).Select(t => t.TaskPercent).FirstOrDefault();

                    if (percent == null || percent == "")
                    {
                        percent = '0'.ToString();
                    }
                    else
                    {
                        percent = percent + "%";
                    }
                    row[3 + 2 * j] = percent;
                }
                row[ItemNames.Length * 2 + 2] = list.Where(t => t.DeptName == DeptNames[i]).Select(t => t.SumActual).FirstOrDefault();

                string sumpercent = list.Where(t => t.DeptName == DeptNames[i]).Select(t => t.SumPercent).FirstOrDefault();

                if (sumpercent == null || sumpercent == "")
                {
                    sumpercent = '0'.ToString();
                }
                else
                {
                    sumpercent = sumpercent + "%";
                }
                row[ItemNames.Length * 2 + 3] = sumpercent;


                tabledisplay.Rows.Add(row);
            }

            _tableview.MyColumns    = MyColumns;
            _tableview.BShowDetails = true;
            _tableview.Table        = tabledisplay;
            //_sj.Visibility = Visibility.Visible;
            //_hj.Visibility = Visibility.Visible;
            //_title.Text = tabledisplay.Rows.Count.ToString();

            if (tabledisplay.Rows.Count == 0)
            {
                Toolkit.MessageBox.Show("没有查询到数据!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
        }
예제 #53
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //官方插件
        var plugins = new Collection <IPlugin>()
        {
            new AcFunPlugin(),
            new YoukuPlugin(),
            new YouTubePlugin(),
            new LetvPlugin(),
            new QiyiPlugin(),
            new QQPlugin(),
            new SinaPlugin(),
            new NicoPlugin(),
            new BilibiliPlugin(),
            new TudouPlugin(),
            new ImanhuaPlugin(),
            new TiebaAlbumPlugin(),
            new SfAcgPlugin(),
            new TucaoPlugin(),
            new FlvcdPlugin()
        };

        //初始化核心
        CoreManager.Initialize(
            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Kaedei\AcDown\"),
            new UIDelegateContainer(null, null, null, null, null, null, null, null),
            plugins);

        string url;

        if (Request.QueryString["url"] == null)
        {
            url = "http://v.youku.com/v_show/id_XNDE5NjE4NjI0.html";
            //url = "http://v.youku.com/v_show/id_XNDQyMDQ5Mzg0.html";
            //url = "http://www.tudou.com/albumplay/T32z2sgr3Uk";
            //url = "http://www.tudou.com/programs/view/ShtKrHZ5O_8/?fr=rec2";
            //url = "http://www.tudou.com/albumplay/zA8Duvz4eUg/8_KTqOUSonI.html";
            //url = "http://www.tudou.com/listplay/69gOmmDlugI/JJKorVrTgPk.html";
            //url = "http://www.tudou.com/listplay/axxbYWyQhT8/fzaY9-d0Stw.html";
            //url = "http://www.letv.com/ptv/pplay/79146/98.html";
            //url = "http://www.letv.com/ptv/vplay/1696569.html";
            //url = "http://v.youku.com/v_show/id_XMjI3MDI1NTM2.html";
            //url = "cache.video.qiyi.com/vd/231669/07f84458488542a2b41f79db3422b335/"; // <-- already broken
            //url = "cache.video.qiyi.com/vd/88373/ce7d6a8f76b1484faa17c8ccaaae225d/";
            //url = "/vkp.tc.qq.com/K00102hDRZB.";
            //url = "/v_play.php?vid=84716144&";
            //url = "http://www.56.com/w99/play_album-aid-10025226_vid-Njk4MDkzOTQ.html";
        }
        else
        {
            url = Request.QueryString["url"].ToString();
        }

        IPlugin plugin = null;

        //查找所有候选插件
        foreach (var item in CoreManager.PluginManager.Plugins)
        {
            if (item.CheckUrl(url))
            {
                plugin = item;
                break;
            }
        }

        if (plugin != null)
        {
            TaskInfo task = new TaskInfo();
            task.Url        = url;
            task.SourceUrl  = url;
            task.BasePlugin = plugin;

            task.AutoAnswer = new List <AutoAnswer>();

            if (task.BasePlugin.Feature.ContainsKey("AutoAnswer"))
            {
                task.AutoAnswer = (List <AutoAnswer>)task.BasePlugin.Feature["AutoAnswer"];
            }
            task.SaveDirectory = new DirectoryInfo("/");

            IDownloader resourceDownloader = task.BasePlugin.CreateDownloader();
            resourceDownloader.delegates = new DelegateContainer(empty_delegate, empty_delegate, empty_delegate, empty_delegate);
            resourceDownloader.Info      = task;

            if (resourceDownloader.Download() && task.videos != null)
            {
                foreach (string fp in task.videos)
                {
                    Response.Write(fp + "\n");
                }
            }
            else
            {
                Response.Write("Sorry");
            }
        }
        else
        {
            Response.Write("NoSuitablePlugin");
        }

        //Response.Write(url);
    }
예제 #54
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Register script for pendingCallbacks repair
        ScriptHelper.FixPendingCallbacks(Page);

        // Initialize current user for the async actions
        currentUser   = CMSContext.CurrentUser;
        currentSiteId = CMSContext.CurrentSiteID;
        serverId      = QueryHelper.GetInteger("serverid", 0);

        HeaderActions.ActionPerformed += HeaderActions_ActionPerformed;

        if (RequestHelper.CausedPostback(btnSyncComplete))
        {
            SyncComplete();
        }
        else
        {
            if (!RequestHelper.IsCallback())
            {
                // Check 'Manage object tasks' permission
                if (!currentUser.IsAuthorizedPerResource("cms.staging", "ManageDataTasks"))
                {
                    RedirectToAccessDenied("cms.staging", "ManageDataTasks");
                }

                ucDisabledModule.SettingsKeys = "CMSStagingLogDataChanges";
                ucDisabledModule.InfoTexts.Add(GetString("DataStaging.TaskSeparator") + "<br />");
                ucDisabledModule.InfoTexts.Add(GetString("stagingchanges.notlogged"));
                ucDisabledModule.ParentPanel = pnlNotLogged;

                // Check logging
                if (!ucDisabledModule.Check())
                {
                    pnlFooter.Visible  = false;
                    plcContent.Visible = false;
                    return;
                }

                // Register the dialog script
                ScriptHelper.RegisterDialogScript(this);

                // Get object type
                objectType = QueryHelper.GetString("objecttype", string.Empty);
                if (!String.IsNullOrEmpty(objectType))
                {
                    // Create header action
                    HeaderActions.AddAction(new HeaderAction()
                    {
                        Text      = GetString("ObjectTasks.SyncCurrent"),
                        ImageUrl  = GetImageUrl("CMSModules/CMS_Staging/syncsubtree.png"),
                        EventName = SYNCHRONIZE_CURRENT
                    });
                }

                // Setup title
                titleElem.TitleText  = GetString("Synchronization.Title");
                titleElem.TitleImage = GetImageUrl("/CMSModules/CMS_Staging/synchronization.png");

                if (!RequestHelper.CausedPostback(HeaderActions, btnSyncSelected, btnSyncAll))
                {
                    // Initialize images
                    viewImage   = GetImageUrl("Design/Controls/UniGrid/Actions/View.png");
                    deleteImage = GetImageUrl("Design/Controls/UniGrid/Actions/Delete.png");
                    syncImage   = GetImageUrl("Design/Controls/UniGrid/Actions/Synchronize.png");

                    // Initialize tooltips
                    syncTooltip   = GetString("general.synchronize");
                    deleteTooltip = GetString("general.delete");
                    viewTooltip   = GetString("general.view");

                    plcContent.Visible = true;

                    // Initialize buttons
                    btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;");
                    btnCancel.Text                  = GetString("General.Cancel");
                    btnDeleteAll.OnClientClick      = "return confirm(" + ScriptHelper.GetString(GetString("Tasks.ConfirmDeleteAll")) + ");";
                    btnDeleteSelected.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("general.confirmdelete")) + ");";
                    btnSyncSelected.OnClientClick   = "return !" + gridTasks.GetCheckSelectionScript();

                    ltlScript.Text += ScriptHelper.GetScript("function CompleteSync(){" + Page.ClientScript.GetPostBackEventReference(btnSyncComplete, null) + "}");

                    // Initialize grid
                    gridTasks.OrderBy              = "TaskTime";
                    gridTasks.ZeroRowsText         = GetString("Tasks.NoTasks");
                    gridTasks.OnAction            += gridTasks_OnAction;
                    gridTasks.OnDataReload        += gridTasks_OnDataReload;
                    gridTasks.OnExternalDataBound += gridTasks_OnExternalDataBound;
                    gridTasks.ShowActionsMenu      = true;
                    gridTasks.Columns              = "TaskID, TaskSiteID, TaskDocumentID, TaskNodeAliasPath, TaskTitle, TaskTime, TaskType, TaskObjectType, TaskObjectID, TaskRunning, (SELECT COUNT(*) FROM Staging_Synchronization WHERE SynchronizationTaskID = TaskID AND SynchronizationErrorMessage IS NOT NULL AND (SynchronizationServerID = @ServerID OR (@ServerID = 0 AND (@TaskSiteID = 0 OR SynchronizationServerID IN (SELECT ServerID FROM Staging_Server WHERE ServerSiteID = @TaskSiteID AND ServerEnabled=1))))) AS FailedCount";
                    TaskInfo ti = new TaskInfo();
                    gridTasks.AllColumns = SqlHelperClass.MergeColumns(ti.ColumnNames);

                    pnlLog.Visible = false;
                }
            }
        }

        ctlAsync.OnFinished   += ctlAsync_OnFinished;
        ctlAsync.OnError      += ctlAsync_OnError;
        ctlAsync.OnRequestLog += ctlAsync_OnRequestLog;
        ctlAsync.OnCancel     += ctlAsync_OnCancel;
    }
예제 #55
0
        /// <summary>
        /// Request a texture asset from the simulator using the <see cref="TexturePipeline"/> system to 
        /// manage the requests and re-assemble the image from the packets received from the simulator
        /// </summary>
        /// <param name="textureID">The <see cref="UUID"/> of the texture asset to download</param>
        /// <param name="imageType">The <see cref="ImageType"/> of the texture asset. 
        /// Use <see cref="ImageType.Normal"/> for most textures, or <see cref="ImageType.Baked"/> for baked layer texture assets</param>
        /// <param name="priority">A float indicating the requested priority for the transfer. Higher priority values tell the simulator
        /// to prioritize the request before lower valued requests. An image already being transferred using the <see cref="TexturePipeline"/> can have
        /// its priority changed by resending the request with the new priority value</param>
        /// <param name="discardLevel">Number of quality layers to discard.
        /// This controls the end marker of the data sent</param>
        /// <param name="packetStart">The packet number to begin the request at. A value of 0 begins the request
        /// from the start of the asset texture</param>
        /// <param name="callback">The <see cref="TextureDownloadCallback"/> callback to fire when the image is retrieved. The callback
        /// will contain the result of the request and the texture asset data</param>
        /// <param name="progressive">If true, the callback will be fired for each chunk of the downloaded image. 
        /// The callback asset parameter will contain all previously received chunks of the texture asset starting 
        /// from the beginning of the request</param>
        public void RequestTexture(UUID textureID, ImageType imageType, float priority, int discardLevel, uint packetStart, TextureDownloadCallback callback, bool progressive)
        {
            if (textureID == UUID.Zero)
                return;

            if (callback != null)
            {
                if (_Client.Assets.Cache.HasAsset(textureID))
                {
                    ImageDownload image = new ImageDownload();
                    image.ID = textureID;
                    image.AssetData = _Client.Assets.Cache.GetCachedAssetBytes(textureID);
                    image.Size = image.AssetData.Length;
                    image.Transferred = image.AssetData.Length;
                    image.ImageType = imageType;
                    image.AssetType = AssetType.Texture;
                    image.Success = true;

                    callback(TextureRequestState.Finished, new AssetTexture(image.ID, image.AssetData));

                    _Client.Assets.FireImageProgressEvent(image.ID, image.Transferred, image.Size);
                }
                else
                {
                    lock (_Transfers)
                    {
                        TaskInfo request;

                        if (_Transfers.TryGetValue(textureID, out request))
                        {
                            request.Callbacks.Add(callback);
                        }
                        else
                        {
                            request = new TaskInfo();
                            request.State = TextureRequestState.Pending;
                            request.RequestID = textureID;
                            request.ReportProgress = progressive;
                            request.RequestSlot = -1;
                            request.Type = imageType;

                            request.Callbacks = new List<TextureDownloadCallback>();
                            request.Callbacks.Add(callback);

                            ImageDownload downloadParams = new ImageDownload();
                            downloadParams.ID = textureID;
                            downloadParams.Priority = priority;
                            downloadParams.ImageType = imageType;
                            downloadParams.DiscardLevel = discardLevel;

                            request.Transfer = downloadParams;
#if DEBUG_TIMING
                            request.StartTime = DateTime.UtcNow;
#endif
                            _Transfers.Add(textureID, request);
                        }
                    }
                }
            }
        }
예제 #56
0
        /// <summary>
        /// Request a texture asset from the simulator using the <see cref="TexturePipeline"/> system to
        /// manage the requests and re-assemble the image from the packets received from the simulator
        /// </summary>
        /// <param name="textureID">The <see cref="UUID"/> of the texture asset to download</param>
        /// <param name="imageType">The <see cref="ImageType"/> of the texture asset.
        /// Use <see cref="ImageType.Normal"/> for most textures, or <see cref="ImageType.Baked"/> for baked layer texture assets</param>
        /// <param name="priority">A float indicating the requested priority for the transfer. Higher priority values tell the simulator
        /// to prioritize the request before lower valued requests. An image already being transferred using the <see cref="TexturePipeline"/> can have
        /// its priority changed by resending the request with the new priority value</param>
        /// <param name="discardLevel">Number of quality layers to discard.
        /// This controls the end marker of the data sent</param>
        /// <param name="packetStart">The packet number to begin the request at. A value of 0 begins the request
        /// from the start of the asset texture</param>
        /// <param name="callback">The <see cref="TextureDownloadCallback"/> callback to fire when the image is retrieved. The callback
        /// will contain the result of the request and the texture asset data</param>
        /// <param name="progressive">If true, the callback will be fired for each chunk of the downloaded image.
        /// The callback asset parameter will contain all previously received chunks of the texture asset starting
        /// from the beginning of the request</param>
        public void RequestTexture(UUID textureID, ImageType imageType, float priority, int discardLevel, uint packetStart, TextureDownloadCallback callback, bool progressive)
        {
            if (textureID.IsZero())
            {
                return;
            }

            if (callback != null)
            {
                if (_Client.Assets.Cache.HasAsset(textureID))
                {
                    ImageDownload image = new ImageDownload();
                    image.ID          = textureID;
                    image.AssetData   = _Client.Assets.Cache.GetCachedAssetBytes(textureID);
                    image.Size        = image.AssetData.Length;
                    image.Transferred = image.AssetData.Length;
                    image.ImageType   = imageType;
                    image.AssetType   = AssetType.Texture;
                    image.Success     = true;

                    callback(TextureRequestState.Finished, new AssetTexture(image.ID, image.AssetData));

                    _Client.Assets.FireImageProgressEvent(image.ID, image.Transferred, image.Size);
                }
                else
                {
                    lock (_Transfers)
                    {
                        TaskInfo request;

                        if (_Transfers.TryGetValue(textureID, out request))
                        {
                            request.Callbacks.Add(callback);
                        }
                        else
                        {
                            request                = new TaskInfo();
                            request.State          = TextureRequestState.Pending;
                            request.RequestID      = textureID;
                            request.ReportProgress = progressive;
                            request.RequestSlot    = -1;
                            request.Type           = imageType;

                            request.Callbacks = new List <TextureDownloadCallback>();
                            request.Callbacks.Add(callback);

                            ImageDownload downloadParams = new ImageDownload();
                            downloadParams.ID           = textureID;
                            downloadParams.Priority     = priority;
                            downloadParams.ImageType    = imageType;
                            downloadParams.DiscardLevel = discardLevel;

                            request.Transfer = downloadParams;
#if DEBUG_TIMING
                            request.StartTime = DateTime.UtcNow;
#endif
                            _Transfers.Add(textureID, request);
                        }
                    }
                }
            }
        }
예제 #57
0
        private void MyTask2(string woord)
        {
            var taskInfo = new TaskInfo
                               {
                                   TaskStarted = Environment.TickCount,
                                   TaskStarted2 = Stopwatch.GetTimestamp()
                               };
            Thread.Sleep(10);// Console.WriteLine(woord)

            taskInfo.TaskEnded = Environment.TickCount;
            taskInfo.TaskEnded2 = Stopwatch.GetTimestamp();
            var elapsed = taskInfo.TaskEnded - taskInfo.TaskStarted;

            //Tree<string>.Queue.Enqueue(woord + elapsed);

            taskInfo.TaskDescription = woord + " ;elapsed " + elapsed;
            Tree<TaskInfo>.Queue.Enqueue(taskInfo);
        }
예제 #58
0
        /// <summary>
        /// Master Download Thread, Queues up downloads in the threadpool
        /// </summary>
        private void DownloadThread()
        {
            int slot;

            while (_Running)
            {
                // find free slots
                int pending = 0;
                int active  = 0;

                TaskInfo nextTask = null;

                lock (_Transfers)
                {
                    foreach (KeyValuePair <UUID, TaskInfo> request in _Transfers)
                    {
                        if (request.Value.State == TextureRequestState.Pending)
                        {
                            nextTask = request.Value;
                            ++pending;
                        }
                        else if (request.Value.State == TextureRequestState.Progress)
                        {
                            ++active;
                        }
                    }
                }

                if (pending > 0 && active <= maxTextureRequests)
                {
                    slot = -1;
                    // find available slot for reset event
                    lock (lockerObject)
                    {
                        for (int i = 0; i < threadpoolSlots.Length; i++)
                        {
                            if (threadpoolSlots[i] == -1)
                            {
                                // found a free slot
                                threadpoolSlots[i] = 1;
                                slot = i;
                                break;
                            }
                        }
                    }

                    // -1 = slot not available
                    if (slot != -1 && nextTask != null)
                    {
                        nextTask.State       = TextureRequestState.Started;
                        nextTask.RequestSlot = slot;

                        //Logger.DebugLog(String.Format("Sending Worker thread new download request {0}", slot));
                        WorkPool.QueueUserWorkItem(TextureRequestDoWork, nextTask);
                        continue;
                    }
                }

                // Queue was empty or all download slots are inuse, let's give up some CPU time
                Thread.Sleep(500);
            }

            Logger.Log("Texture pipeline shutting down", Helpers.LogLevel.Info);
        }
예제 #59
0
파일: HelpCommand.cs 프로젝트: rh/mix
        private static string Aliases(TaskInfo info)
        {
            if (info.Aliases.Length > 0)
            {
                return string.Format(" ({0})", string.Join(", ", info.Aliases));
            }

            return string.Empty;
        }
예제 #60
0
 private bool TryGetTransferValue(UUID textureID, out TaskInfo task)
 {
     lock (_Transfers)
         return(_Transfers.TryGetValue(textureID, out task));
 }