Beispiel #1
0
 public static bool RunTaskScheduler(string taskName, string path, string arguments)
 {
     try {
         // List of Windows versions at: http://msdn.microsoft.com/library/windows/desktop/ms724832.aspx
         // Windows XP
         if (Environment.OSVersion.Version.Major < 6)
         {
             Process.Start(path, arguments);
         }
         else
         {
             using (TaskService ts = new TaskService()) {
                 TaskDefinition td = ts.NewTask();
                 td.Actions.Add(new ExecAction(path, arguments, null));
                 ts.RootFolder.RegisterTaskDefinition(taskName, td);
                 Microsoft.Win32.TaskScheduler.Task t = ts.FindTask(taskName);
                 if (t != null)
                 {
                     t.Run();
                 }
                 ts.RootFolder.DeleteTask(taskName);
             }
         }
     } catch (Exception e) {
         return(false);
     }
     return(true);
 }
Beispiel #2
0
        public static bool HasTaskEntry()
        {
            TaskService ts     = new TaskService();
            Task        tasker = ts.FindTask("RunDS4Windows");

            return(tasker != null);
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="TaskEditDialog"/> class.
		/// </summary>
		/// <param name="task">The task.</param>
		/// <param name="editable">If set to <c>true</c> the task will be editable in the dialog.</param>
		/// <param name="registerOnAccept">If set to <c>true</c> the task will be registered when Ok is pressed.</param>
		public TaskEditDialog(Task task, bool editable = true, bool registerOnAccept = true)
		{
			InitializeComponent();
			this.Editable = editable;
			this.Initialize(task);
			this.RegisterTaskOnAccept = registerOnAccept;
		}
Beispiel #4
0
        //extracts a routine path from a Registered Tasks. When tasks are registered the end of the description has the path appended.
        public string getRoutinePathFromTask(Microsoft.Win32.TaskScheduler.Task task)
        {
            string taskDesc        = task.Definition.RegistrationInfo.Description;
            string taskRoutinePath = taskDesc.Substring(taskDesc.IndexOf("PATH: ") + 5);

            return(taskRoutinePath);
        }
Beispiel #5
0
 public void deleteTask(Microsoft.Win32.TaskScheduler.Task task)
 {
     using (TaskService taskService = new TaskService())
     {
         taskService.RootFolder.DeleteTask(task.Name);
     }
 }
        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            using (TaskService ts = new TaskService())
            {
                Microsoft.Win32.TaskScheduler.Task t = ts.GetTask(taskName);
                if (t == null)
                {
                    return;
                }

                // In some cases you need Administrator permission

                /*
                 * // Check to make sure account privileges allow task deletion
                 * var identity = WindowsIdentity.GetCurrent();
                 * var principal = new WindowsPrincipal(identity);
                 *
                 *  if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
                 *  throw new Exception($"Cannot delete task with your current identity '{identity.Name}' permissions level." +
                 *  "You likely need to run this application 'as administrator' even if you are using an administrator account.");
                 */

                // Remove the task we just created
                ts.RootFolder.DeleteTask(taskName);
            }
        }
Beispiel #7
0
        static void ActOnTask(Task t, string search = "")
        {
            // Do something interesting here

            if (search != "")
            {
            }
            if (t.Path.Contains(search) || t.Definition.Principal.ToString().Contains(search))
            {
                Console.WriteLine("\r\n============================");
                Console.WriteLine("[+] Path: " + t.Path);
                Console.WriteLine("[+] Principal: " + t.Definition.Principal);

                foreach (Action action in t.Definition.Actions)
                {
                    Console.WriteLine("[+] Action: " + action.ToString());

                    if (t.Definition.Triggers.Count > 0)
                    {
                        foreach (Trigger trigger in t.Definition.Triggers)
                        {
                            Console.WriteLine(trigger.ToString());
                        }
                    }
                }
            }
        }
        private void AdvancedSettingsDialog_Load(object sender, EventArgs e)
        {
            if (!settings.UsingUsernameAsSisID)
            {
                userSisIDComboBox.SelectedIndex = 0;
            }
            else
            {
                userSisIDComboBox.SelectedIndex = 1;
            }

            using (TaskService ts = new TaskService())
            {
                Microsoft.Win32.TaskScheduler.Task t = ts.GetTask(@"ADSyncToolDaily");
                if (t != null)
                {
                    scheduledTaskCheckBox.Checked = true;
                }
            }

            schoolSisIDTextBox.Text = settings.DefaultSisID;

            if (settings.SmbCopyEnabled)
            {
                smbCopyCheckBox.Checked = true;
            }
            else
            {
                smbCopyCheckBox.Checked = false;
            }

            smbDriveLetterComboBox.SelectedItem = settings.SmbDriveLetter;
        }
Beispiel #9
0
 //Check if schtask exists
 //0Unknown/1Exists/2DoesNotExist/3Invalid
 int CheckTask()
 {
     try
     {
         Debug.WriteLine("Checking the admin task.");
         using (TaskService taskService = new TaskService())
         {
             using (Microsoft.Win32.TaskScheduler.Task task = taskService.GetTask(SchTask_Name))
             {
                 if (task == null)
                 {
                     Debug.WriteLine("The task does not exist.");
                     return(2);
                 }
                 else
                 {
                     //Check if the application path has changed
                     if (!task.Definition.Actions.ToString().Contains(SchTask_FilePath))
                     {
                         Debug.WriteLine("Application path has changed.");
                         return(3);
                     }
                     else
                     {
                         Debug.WriteLine("The task should be working.");
                         return(1);
                     }
                 }
             }
         }
     }
     catch { return(0); }
 }
 public void TaskSchedulerTest()
 {
     AppSettings conf = new AppSettings();
     conf.Hourpattern = "*";
     conf.Minutepattern = "00,30";
     Schedule schedule = new Schedule(conf);
     Win32ScheduleInstaller uut = new Win32ScheduleInstaller(schedule);
     uut.deleteTaskAndTriggers();
     using (TaskService ts = new TaskService())
     {
         Assert.IsNull(ts.GetTask("BBCIngest"));
     }
     uut.installTask(@"C:\WINDOWS\system32\cmd.exe", "");
     using (TaskService ts = new TaskService())
     {
         Microsoft.Win32.TaskScheduler.Task t = ts.GetTask("BBCIngest");
         Assert.IsNotNull(t);
         DateTime sod = DateTime.UtcNow.Date;
         // getruntimes is exclusive of the start time
         DateTime[] runtimes = t.GetRunTimes(sod.AddMilliseconds(-1), sod.AddMilliseconds(-1).AddDays(1));
         Assert.AreEqual(48, runtimes.Length);
         DateTime[] events = schedule.events(sod);
         Assert.AreEqual(48, events.Length);
         for (int i = 0; i < 48; i++)
         {
             Assert.AreEqual(events[i], runtimes[i]);
         }
     }
     uut.deleteTaskAndTriggers();
     using (TaskService ts = new TaskService())
     {
         Assert.IsNull(ts.GetTask("BBCIngest"));
     }
 }
Beispiel #11
0
        /// <summary>
        /// Crea una tarea mas especifica
        /// </summary>
        /// <param name="name"></param>
        /// <param name="description"></param>
        /// <param name="pathExe"></param>
        /// <param name="startHour"></param>
        /// <param name="daysInterval"></param>
        /// <param name="allowRun"></param>
        /// <param name="argum"></param>
        /// <returns></returns>
        public static string CreateTask(string name, string description, string pathExe, double startHour, short daysInterval, bool allowRun = false, string argum = "")
        {
            string response = "";

            // Get the service on the local machine
            using (TaskService ts = new TaskService())
            {
                string taskName = name;

                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = description;

                DailyTrigger dTrigger = td.Triggers.Add(new DailyTrigger());

                if (startHour != 0)
                {
                    dTrigger.StartBoundary = DateTime.Today + TimeSpan.FromHours(startHour);
                }

                if (daysInterval != 0)
                {
                    dTrigger.DaysInterval = daysInterval;
                }

                if (allowRun)
                {
                    dTrigger.Repetition.Interval = TimeSpan.FromSeconds(60);
                }

                td.Settings.MultipleInstances = TaskInstancesPolicy.StopExisting;

                td.Actions.Add(new ExecAction(pathExe, argum));

                ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken, null);

                //SHOW ALL INFORAMTION OF NEW TASKs
                TaskFolder tf = ts.RootFolder;
                Microsoft.Win32.TaskScheduler.Task runningTask = tf.Tasks[taskName];

                response  = "==============================" + Environment.NewLine;
                response += "New task:" + taskName + Environment.NewLine;
                response += "Triggers:";

                for (int i = 0; i < runningTask.Definition.Triggers.Count; i++)
                {
                    response += string.Format("{0}", runningTask.Definition.Triggers[i]) + Environment.NewLine;
                }

                response += "Actions:" + Environment.NewLine;

                for (int i = 0; i < runningTask.Definition.Actions.Count; i++)
                {
                    response += string.Format("{0}", runningTask.Definition.Actions[i]) + Environment.NewLine;
                    response += Environment.NewLine;
                }

                return(response);
            }
        }
Beispiel #12
0
 public bool isStartOnBoot()
 {
     using (TaskService ts = new TaskService())
     {
         Microsoft.Win32.TaskScheduler.Task task = ts.FindTask("ListaryWithWinKey", false);
         return(task != null);
     }
 }
Beispiel #13
0
 public static bool IsStartupEnabled()
 {
     using (TaskService taskService = new TaskService())
     {
         Task task = taskService.GetTask(_taskName);
         return(task != null);
     }
 }
Beispiel #14
0
 public static string GetNextRunTimeString(Microsoft.Win32.TaskScheduler.Task t)
 {
     if (t.State == TaskState.Disabled || t.NextRunTime < DateTime.Now)
     {
         return(string.Empty);
     }
     return(t.NextRunTime.ToString("G"));
 }
Beispiel #15
0
 public static bool IsAutostart()
 {
     using (TaskService ts = new TaskService())
     {
         Microsoft.Win32.TaskScheduler.Task task = ts.GetTask("Touchmote");
         return(task != null);
     }
 }
Beispiel #16
0
        public static void LaunchOldTask()
        {
            TaskService ts     = new TaskService();
            Task        tasker = ts.FindTask("RunDS4Windows");

            if (tasker != null)
            {
                tasker.Run("");
            }
        }
Beispiel #17
0
        public static void DeleteTaskEntry()
        {
            TaskService ts     = new TaskService();
            Task        tasker = ts.FindTask("RunDS4Windows");

            if (tasker != null)
            {
                ts.RootFolder.DeleteTask("RunDS4Windows");
            }
        }
Beispiel #18
0
        private void DisableUser_Click(object sender, EventArgs e)
        {
            String           sSelectedUserName = "";
            PrincipalContext pctxLocalMachine;
            UserPrincipal    usrpSelectedUser;

            try
            {
                sSelectedUserName        = cmbUserList.SelectedItem.ToString();
                pctxLocalMachine         = new PrincipalContext(ContextType.Machine);
                usrpSelectedUser         = UserPrincipal.FindByIdentity(pctxLocalMachine, IdentityType.SamAccountName, sSelectedUserName);
                usrpSelectedUser.Enabled = false;

                usrpSelectedUser.Save();

                cmbSunFromTime.Enabled = false;
                cmbSunToTime.Enabled   = false;
                cmbMonFromTime.Enabled = false;
                cmbMonToTime.Enabled   = false;
                cmbTueFromTime.Enabled = false;
                cmbTueToTime.Enabled   = false;
                cmbWedFromTime.Enabled = false;
                cmbWedToTime.Enabled   = false;
                cmbThuFromTime.Enabled = false;
                cmbThuToTime.Enabled   = false;
                cmbFriFromTime.Enabled = false;
                cmbFriToTime.Enabled   = false;
                cmbSatFromTime.Enabled = false;
                cmbSatToTime.Enabled   = false;
                btnSave.Enabled        = false;

                // Disable triggers for scheduled tasks in the Task Scheduler
                using (TaskService ts = new TaskService(@"\"))
                {
                    TaskFolder myFolder = ts.GetFolder("Karthik's Custom Tasks");

                    var myTasks = myFolder.Tasks.Where(t => t.Name.Equals(sSelectedUserName + " Force Logoff", StringComparison.OrdinalIgnoreCase));
                    Microsoft.Win32.TaskScheduler.Task myTask = myTasks.ElementAt(0);
                    //myTask.Enabled = false;
                    myTask.Definition.Settings.Enabled = false;
                    myTask.RegisterChanges();
                }

                MessageBox.Show(sSelectedUserName + " has been disabled now!");
                usrpSelectedUser.Dispose();
                pctxLocalMachine.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.WriteLine(ex.StackTrace);
            }
            btnEnableUser.Enabled  = true;
            btnDisableUser.Enabled = false;
        }
Beispiel #19
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            const int MAX_RETRIES = 15;

            // This loop tries to avoid an unknown task state, thinking it's transient
            Task task = null;

            for (int i = 0; i <= MAX_RETRIES; i++)
            {
                System.Threading.Thread.Sleep(100);
                task = GetScheduledTask(request.DataStore.GetValue("TaskName"));
                if (task == null)
                {
                    return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "SccmTaskNotFound"));
                }

                if (task.State == TaskState.Unknown)
                {
                    continue;
                }
                else
                {
                    break;
                }
            }

            // Let it run
            if (task.State == TaskState.Queued || task.State == TaskState.Running)
            {
                return(new ActionResponse(ActionStatus.InProgress));
            }

            // If we're here, the task completed
            if (task.LastTaskResult == 0)
            {
                return(new ActionResponse(ActionStatus.Success));
            }

            // there was an error since we haven't exited above
            uploadLogs(request);
            if (NTHelper.IsCredentialGuardEnabled())
            {
                return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "CredentialGuardEnabled"));
            }

            // azurebcp exits with 0, 1, 2, the powershell script might return 1 - anything else must be a Windows error
            Exception e = (uint)task.LastTaskResult > 2 ?
                          new Exception($"Scheduled task exited with code {task.LastTaskResult}", new System.ComponentModel.Win32Exception(task.LastTaskResult)) :
                          new Exception($"Scheduled task exited with code {task.LastTaskResult}");

            ActionResponse response = new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), e, "TaskSchedulerRunFailed");

            response.ExceptionDetail.LogLocation = FileUtility.GetLocalTemplatePath(request.Info.AppName);
            return(response);
        }
Beispiel #20
0
 private ScheduledTaskAutoStartEntry GetAutoStartEntry(Microsoft.Win32.TaskScheduler.Task task)
 {
     return(new ScheduledTaskAutoStartEntry()
     {
         Date = DateTime.Now,
         Category = Category,
         Path = task.Path,
         Value = task.Definition.Actions.ToString(),
         IsEnabled = task.Enabled,
     });
 }
Beispiel #21
0
        private void MigrationTask(string connectionString)
        {
            //Если хотим, чтобы что-то сделалось, то надо убрать return

            using (TaskService fromTaskService = new TaskService("offdc", "runer", "analit", "zcxvcb")) {
                TaskFolder _reportsFolder = fromTaskService.GetFolder("Отчеты");

                using (TaskService toTaskService = new TaskService("fms", "runer", "analit", "zcxvcb")) {
                    TaskFolder newFolder = toTaskService.GetFolder("Отчеты");

                    int allCount = 0, emptyTriggerCount = 0, standartTriggerCount = 0, anotherTriggerCount = 0, existsCount = 0;
                    foreach (Task task in _reportsFolder.Tasks)
                    {
                        int generalReportCode = 0;
                        if (task.Name.StartsWith("GR") && (task.Name.Length > 2) &&
                            int.TryParse(task.Name.Substring(2), out generalReportCode))
                        {
                            allCount++;

                            if (MySqlHelper.ExecuteScalar(
                                    connectionString,
                                    "select GeneralReportCode from reports.general_reports g WHERE g.GeneralReportCode = ?GeneralReportCode",
                                    new MySqlParameter("?GeneralReportCode", generalReportCode)) != null)
                            {
                                existsCount++;

                                //Console.WriteLine("taskName: {0}\r\n{1}\r\n{2}", task.Name, task.Xml, task.Definition.XmlText);

                                // Create a new task definition and assign properties
                                TaskDefinition newTaskDefinition = toTaskService.NewTask();
                                newTaskDefinition.XmlText = task.Definition.XmlText;

                                Task newTask =
                                    newFolder.RegisterTaskDefinition(
                                        task.Name,
                                        newTaskDefinition,
                                        TaskCreation.Create,
                                        "analit\\runer",
                                        "zcxvcb",
                                        TaskLogonType.Password,
                                        null);
                                newTask.Enabled = task.Enabled;
                            }
                            else
                            {
                                Console.WriteLine("not exists : {0}", task.Name);
                            }
                        }
                    }

                    Console.WriteLine("statistic allCount = {0}, emptyTriggerCount = {1}, standartTriggerCount = {2}, anotherTriggerCount = {3}, existsCount = {4}", allCount, emptyTriggerCount, standartTriggerCount, anotherTriggerCount, existsCount);
                }
            }
        }
Beispiel #22
0
 void DisableTask()
 {
     using (TaskService ts = new TaskService())
     {
         Microsoft.Win32.TaskScheduler.Task task = ts.FindTask(m_programName);
         if (task != null)
         {
             ts.RootFolder.DeleteTask(m_programName);
         }
     }
 }
Beispiel #23
0
        public void EditTask(string taskName = defaultTaskName)
        {
            Microsoft.Win32.TaskScheduler.Task t = TaskService.Instance.GetTask(taskName);
            if (t == null)
            {
                return;
            }

            TaskEditDialog editorForm = new TaskEditDialog(t, true, true);

            editorForm.ShowDialog();
        }
        public static bool TaskExists()
        {
            bool exists = false;

            using (TaskService ts = new TaskService())
            {
                Task t = ts.GetTask("GPDWin2XTUManager");
                exists = (t != null);
            }

            return(exists);
        }
        public static string GetTaskParameter()
        {
            string profile = "";

            using (TaskService ts = new TaskService())
            {
                Task t = ts.GetTask(Shared.APP_NAME_VALUE);
                profile = ((ExecAction)t.Definition.Actions[0]).Arguments;
            }

            return(profile);
        }
        internal TaskEntry(string name, string command, string commandFilename, Microsoft.Win32.TaskScheduler.Task task)
        {
            ProgramName     = name;
            Command         = command;
            CommandFilePath = Environment.ExpandEnvironmentVariables(commandFilename);
            SourceTask      = task;

            ParentLongName = Localisation.Startup_ShortName_Task + task.Path;
            EntryLongName  = task.Name;

            FillInformationFromFile(CommandFilePath);
        }
Beispiel #27
0
        internal TaskEntry(string name, string command, string commandFilename, Microsoft.Win32.TaskScheduler.Task task)
        {
            ProgramName     = name;
            Command         = command;
            CommandFilePath = commandFilename;
            SourceTask      = task;

            ParentLongName = task.Path;
            EntryLongName  = task.Name;

            FillInformationFromFile(commandFilename);
        }
Beispiel #28
0
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                if (args[0] == "add")
                {
                    TaskService.Instance.AddTask("Telekom Aidat Cron", QuickTriggerType.Logon, Assembly.GetExecutingAssembly().Location);
                }
                else if (args[0] == "del")
                {
                    Microsoft.Win32.TaskScheduler.Task task = TaskService.Instance.FindTask("Telekom Aidat Cron");
                    if (task != null)
                    {
                        task.Enabled = false;
                    }
                }
            }
            else
            {
                Database db      = new Database();
                var      kontrol = db.DataOkuTek("select tarih from cron", "tarih");
                db.Kapat();


                db = new Database();
                if (DateTime.Today.ToString() != kontrol)
                {
                    mailServer.EnableSsl   = true;
                    mailServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "telekom123");

                    List <Gonderi> gonderiler = TarihKontrol();

                    foreach (Gonderi gonderi in gonderiler)
                    {
                        MailTekliGonder(gonderi.mail, gonderi.baslik, gonderi.icerik);
                    }
                    gonderiler.Clear();

                    List <Gonderi> dogumGunuGonderiler = dogumGunuTarihKontrol();

                    foreach (Gonderi gonderi in dogumGunuGonderiler)
                    {
                        MailTekliGonder(gonderi.mail, gonderi.baslik, gonderi.icerik);
                    }

                    db.Sorgu("update cron set tarih=@0", DateTime.Today); // sona koydukki tamamlanınca işaret koysun
                }



                //db.Sorgu("update cron set tarih=@0", DateTime.Today.AddDays(-1));
            }
        }
Beispiel #29
0
        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.Checked)
            {
                if (checkBox3.Checked == false)
                {
                    rkApp.SetValue("Stop_High_CPU_usage", Application.ExecutablePath);
                }
                else
                {
                }
            }
            else
            {
                if (checkBox3.Checked)
                {
                    using (ts = new TaskService())
                    {
                        try
                        {
                            ts.RootFolder.DeleteTask("Stop_High_CPU_usage");

                            try
                            {
                                Microsoft.Win32.TaskScheduler.Task get_task = ts.GetTask("Stop_High_CPU_usage");

                                if (get_task.Enabled)
                                {
                                    checkBox3.Checked = true;
                                    checkBox2.Checked = true;
                                }
                            }
                            catch (Exception)
                            {
                                checkBox3.Checked = false;
                            }
                        }
                        catch (Exception)
                        {
                            checkBox3.Checked   = true;
                            checkBox2.Checked   = true;
                            checkBox3.Enabled   = false;
                            checkBox2.Enabled   = false;
                            checkBox3.Text      = lang_error_04;
                            checkBox3.BackColor = Color.FromArgb(10, 218, 142, 61);
                            checkBox2.BackColor = Color.FromArgb(10, 218, 142, 61);
                        }
                    }
                }
                rkApp.DeleteValue("Stop_High_CPU_usage", false);
            }
        }
 /// <summary>
 /// Закончили работу с TaskService
 /// </summary>
 private void CloseTaskService()
 {
     if (currentTask != null)
     {
         currentTask.Dispose();
         currentTask = null;
     }
     if (taskService != null)
     {
         taskService.Dispose();
         taskService = null;
     }
 }
Beispiel #31
0
 private void DeleteButton_Click(object sender, RoutedEventArgs e)
 {
     using (TaskService ts = new TaskService())
     {
         Microsoft.Win32.TaskScheduler.Task t = ts.GetTask(Task);
         if (t == null)
         {
             return;
         }
         ts.RootFolder.DeleteTask(Task);
         taskList.Items.Remove(Task);
     }
 }
		public string ToCronExpression(Task task)
		{
			TaskDefinition definition = task.Definition;

			if (definition.Triggers.Any())
			{
				var lines = new List<string>();

				foreach (Trigger trigger in definition.Triggers)
				{
					// Windows has many-to-many for actions and triggers, cron doesn't.
					// So map them all into rows - 2 triggers and 2 actions are 4 rows.
					foreach (Action action in definition.Actions)
					{
						var cronRow = new CronRow()
						{
							Name = task.Name
						};
						cronRow.Command = GetCommandText(action);

						DateTime startDate = trigger.StartBoundary;

						cronRow.SetStartFromDate(startDate);

						if (trigger.Repetition.IsSet())
						{
							TimeSpan interval = trigger.Repetition.Interval;
							SetRepeatItems(cronRow, interval);
						}

						Helper.WriteConsoleColor($"[{cronRow.Name}] ", ConsoleColor.Green);

						if (_listOptions.Explain)
						{
							_writer.WriteLine();
							_writer.WriteLine("{0}", cronRow.Explain());
						}
						else
						{
							_writer.WriteLine("{0}", cronRow.CronString());
						}

						Helper.WriteConsoleColor(cronRow.ShortnedCommand, ConsoleColor.DarkGray);
						_writer.WriteLine();
					}
				}
			}

			return "";
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="TaskRunTimesDialog"/> class.
		/// </summary>
		/// <param name="task">The task to display.</param>
		/// <param name="startDate">The date to begin looking for run times.</param>
		/// <param name="endDate">The date to end looking for run times.</param>
		public TaskRunTimesDialog(Task task, DateTime startDate, DateTime endDate)
		{
			InitializeComponent();
			Initialize(task, startDate, endDate);
		}
Beispiel #34
0
 void RegisterTaskDefinition(TaskDefinition definition)
 {
     if (!Report.SchedulesWithCurrentUser)
     {
         definition.Principal.RunLevel = TaskRunLevel.Highest;
         _task = Report.TaskFolder.RegisterTaskDefinition(TaskName, definition, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount);
     }
     else
     {
         //default user
         _task = Report.TaskFolder.RegisterTaskDefinition(TaskName, definition);
     }
 }
        private void taskListView_TaskSelected(object sender, Microsoft.Win32.TaskScheduler.TaskListView.TaskSelectedEventArgs e)
        {
            if (itemMenuStrip.Enabled != (e.Task != null))
                itemMenuStrip.Enabled = (e.Task != null);
            bool hasValidTask = true;
            try { var d = e.Task.Definition; } catch { hasValidTask = false; }
            if (!hasValidTask)
            {
                TaskPropertiesControl.Hide();
                selTask = null;
            }
            else
            {
                TaskPropertiesControl.Show();
                TaskPropertiesControl.Initialize(e.Task);
                selTask = e.Task;

                endMenuItem.Enabled = endMenuItem2.Enabled = (selTask.State == TaskState.Running);
                disableMenuItem.Enabled = disableMenuItem2.Enabled = (selTask.Enabled);
            }
        }
Beispiel #36
0
        private Dictionary<String, String> filter(Task task)
        {
            /* Available filters:
             *      name
             *      trigger (definition.triggers)
             *      nextRunTime
             *      enable
             *      lastRunTime
             *      lastRunReturn
             *      lastRun (lastRunTime + lastRunReturn)
             *      path
             *      status
             *      command (definition.action)
             *      author (definition.registrationinfo.author
             *      description (definition.registrationinfo.descrition)
             *      executionTimeLimit (definition.settings.executionTimeLimit)
             *      priority (definition.settings.priority)
             */
            Dictionary<String, String> r = new Dictionary<String, String>();

            if (this.filters == null)
            {// default filter:
                if (this.verbose)
                    this.filters = new string[] {
                        "name", "trigger", "nextruntime", "enable", "lastRun",
                        "path", "status", "command", "author",
                        "description", "executiontimelimit", "priority"
                    };
                else
                    this.filters = new string[] {
                        "name", "description", "trigger", "enable"
                    };
            }

            foreach (String filter in this.filters)
            {
                switch(filter.ToLower()) {
                    case "name":
                        r.Add(filter.ToLower(), task.Name);
                        break;
                    case "trigger":
                        r.Add(filter.ToLower(), task.Definition.Triggers.ToString());
                        break;
                    case "lastrun":
                        r.Add(filter.ToLower(), task.LastRunTime.ToString() + " (Return: " + task.LastTaskResult.ToString() + ")");
                        break;
                    case "enable":
                        r.Add(filter.ToLower(), (task.Enabled) ? "true" : "false");
                        break;
                    case "nextruntime":
                        r.Add(filter.ToLower(), task.LastRunTime.ToString());
                        break;
                    case "lastrunreturn":
                        r.Add(filter.ToLower(), task.LastTaskResult.ToString());
                        break;
                    case "path":
                        r.Add(filter.ToLower(), task.Path);
                        break;
                    case "status":
                        r.Add(filter.ToLower(), task.State.ToString());
                        break;
                    case "command":
                        r.Add(filter.ToLower(), task.Definition.Actions.ToString());
                        break;
                    case "author":
                        r.Add(filter.ToLower(), task.Definition.RegistrationInfo.Author);
                        break;
                    case "description":
                        r.Add(filter.ToLower(), task.Definition.RegistrationInfo.Description);
                        break;
                    case "executiontimelimit":
                        r.Add(filter.ToLower(), task.Definition.Settings.ExecutionTimeLimit.ToString());
                        break;
                    case "priority":
                        r.Add(filter.ToLower(), task.Definition.Settings.Priority.ToString());
                        break;
                }
            }
            return r;
        }
		/// <summary>
		/// Initializes the control for the editing of an existing <see cref="Task"/>.
		/// </summary>
		/// <param name="task">A <see cref="Task"/> instance.</param>
		public void Initialize(Task task)
		{
			this.Task = task;
			this.wizardControl1.RestartPages();
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="TaskOptionsEditor"/> class.
		/// </summary>
		/// <param name="task">The task.</param>
		/// <param name="editable">If set to <c>true</c> the task will be editable in the dialog.</param>
		/// <param name="registerOnAccept">If set to <c>true</c> the task will be registered when Ok is pressed.</param>
		public TaskOptionsEditor(Task task, bool editable = true, bool registerOnAccept = true) : this()
		{
			this.Editable = editable;
			this.Initialize(task);
			this.RegisterTaskOnAccept = registerOnAccept;
		}
 /// <summary>
 /// Initializes an instance of the <see cref="TaskRunTimesDialog"/> class.
 /// </summary>
 /// <param name="task">The task to display.</param>
 /// <param name="startDate">The date to begin looking for run times.</param>
 /// <param name="endDate">The date to end looking for run times.</param>
 public void Initialize(Task task = null, DateTime? startDate = null, DateTime? endDate = null)
 {
     BeginInit();
     if (startDate.HasValue)
         this.StartDate = startDate.Value;
     if (endDate.HasValue)
         this.EndDate = endDate.Value;
     this.Task = task;
     EndInit();
 }
 static string WriteXml(Task t)
 {
     string fn = GetTempXmlFile(t.Name);
     t.Export(fn);
     return fn;
 }
 static TaskDefinition DisplayTask(Task t, bool editable)
 {
     if (editorForm == null)
         editorForm = new TaskEditDialog();
     editorForm.Editable = editable;
     editorForm.Initialize(t);
     editorForm.RegisterTaskOnAccept = true;
     editorForm.AvailableTabs = AvailableTaskTabs.All;
     return (editorForm.ShowDialog() == System.Windows.Forms.DialogResult.OK) ? editorForm.TaskDefinition : null;
 }
 internal void Persist(Task task, AccessControlSections includeSections = AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner)
 {
     base.WriteLock();
     try
     {
         AccessControlSections accessControlSectionsFromChanges = this.GetAccessControlSectionsFromChanges();
         if (accessControlSectionsFromChanges != AccessControlSections.None)
         {
             task.SetSecurityDescriptorSddlForm(this.GetSecurityDescriptorSddlForm(includeSections), TaskSecurity.Convert(includeSections));
             base.OwnerModified = base.GroupModified = base.AccessRulesModified = base.AuditRulesModified = false;
         }
     }
     finally
     {
         base.WriteUnlock();
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="TaskSecurity" /> class with the specified sections of the access control security rules from the specified task.
 /// </summary>
 /// <param name="task">The task.</param>
 /// <param name="sections">The sections of the ACL to retrieve.</param>
 public TaskSecurity(Task task, AccessControlSections sections = System.Security.AccessControl.AccessControlSections.Access | System.Security.AccessControl.AccessControlSections.Owner | System.Security.AccessControl.AccessControlSections.Group)
     : base(false)
 {
     this.SetSecurityDescriptorSddlForm(task.GetSecurityDescriptorSddlForm(TaskSecurity.Convert(sections)));
 }
		/// <summary>
		/// Initializes the control for the editing of a new <see cref="TaskDefinition"/>.
		/// </summary>
		/// <param name="service">A <see cref="TaskService"/> instance.</param>
		/// <param name="td">An optional <see cref="TaskDefinition"/>. Leaving null creates a new task.</param>
		public void Initialize(TaskService service, TaskDefinition td = null)
		{
			if (service == null)
				throw new ArgumentNullException("service");
			if (!titleSet)
				this.Text = string.Format(EditorProperties.Resources.TaskEditDlgTitle, "New Task", TaskEditDialog.GetServerString(service));
			this.TaskService = service;
			this.task = null;
			if (!this.IsDesignMode())
			{
				if (td == null)
					this.TaskDefinition = service.NewTask();
				else
					this.TaskDefinition = td;
			}
		}
		/// <summary>
		/// Initializes the control for the editing of an existing <see cref="Task"/>.
		/// </summary>
		/// <param name="task">A <see cref="Task"/> instance.</param>
		public void Initialize(Task task)
		{
			if (task == null)
				throw new ArgumentNullException("task");
			if (!titleSet)
				this.Text = string.Format(EditorProperties.Resources.TaskEditDlgTitle, task.Name, TaskEditDialog.GetServerString(task.TaskService));
			this.Task = task;
		}
 public IDev2Task CreateTask(Task task)
 {
     return new Dev2Task(this, task);
 }
 /// <summary>
 /// Initializes the control for the editing of a new <see cref="TaskDefinition"/>.
 /// </summary>
 /// <param name="service">A <see cref="TaskService"/> instance.</param>
 /// <param name="td">An optional <see cref="TaskDefinition"/>. Leaving null creates a new task.</param>
 public void Initialize(TaskService service, TaskDefinition td = null)
 {
     this.TaskService = service;
     this.task = null;
     if (!this.IsDesignMode())
     {
         if (td == null)
             this.TaskDefinition = service.NewTask();
         else
             this.TaskDefinition = td;
     }
 }
		/// <summary>
		/// Initializes the control for the editing of a new <see cref="TaskDefinition"/>.
		/// </summary>
		/// <param name="service">A <see cref="TaskService"/> instance.</param>
		/// <param name="td">An optional <see cref="TaskDefinition"/>. Leaving null creates a new task.</param>
		public void Initialize(TaskService service, TaskDefinition td = null)
		{
			this.TaskService = service;
			this.task = null;
			if (td == null)
				this.TaskDefinition = service.NewTask();
			else
			{
				if (td.Triggers.Count > 1)
					throw new ArgumentException("Only tasks with a single trigger can be used to initialize the wizard.");
				this.TaskDefinition = td;
			}
			this.wizardControl1.RestartPages();
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="TaskSelectedEventArgs"/> class.
 /// </summary>
 /// <param name="task">The task.</param>
 internal TaskSelectedEventArgs(Task task = null)
 {
     this.Task = task;
 }
 private ListViewItem LVIFromTask(Task task)
 {
     bool disabled = task.State == TaskState.Disabled;
     TaskDefinition td = null;
     try { td = task.Definition; } catch { }
     ListViewItem lvi = new ListViewItem(new string[] {
         task.Name,
         TaskEnumGlobalizer.GetString(task.State),
         td == null ? "" : task.Definition.Triggers.ToString(),
         disabled || task.NextRunTime < DateTime.Now ? string.Empty : task.NextRunTime.ToString("G"),
         task.LastRunTime == DateTime.MinValue ? EditorProperties.Resources.Never :  task.LastRunTime.ToString("G"),
         task.LastRunTime == DateTime.MinValue ? string.Empty : task.State == TaskState.Running ? string.Format(EditorProperties.Resources.LastResultRunning, task.LastTaskResult) : ((task.LastTaskResult == 0 ? EditorProperties.Resources.LastResultSuccessful : string.Format("(0x{0:X})", task.LastTaskResult))),
         td == null ? "" : task.Definition.RegistrationInfo.Author,
         string.Empty
         }, 0) { Tag = task };
     return lvi;
 }
 /// <summary>
 /// Initializes the control for the editing of an existing <see cref="Task"/>.
 /// </summary>
 /// <param name="task">A <see cref="Task"/> instance.</param>
 public void Initialize(Task task)
 {
     this.Task = task;
 }
		/// <summary>
		/// Initializes the dialog with the specified task.
		/// </summary>
		/// <param name="task">The task.</param>
		/// <param name="startDate">The start date.</param>
		/// <param name="endDate">The end date.</param>
		protected void Initialize(Task task, DateTime? startDate, DateTime? endDate)
		{
			taskRunTimesControl1.Initialize(task, startDate, endDate);
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="TaskSchedulerWizard"/> class.
		/// </summary>
		/// <param name="task">A <see cref="Task"/> instance.</param>
		/// <param name="registerOnFinish">If set to <c>true</c> the task will be registered when Finish is pressed.</param>
		public TaskSchedulerWizard(Task task, bool registerOnFinish = false)
			: this()
		{
			Initialize(task);
			RegisterTaskOnFinish = registerOnFinish;
		}
Beispiel #54
0
 public void Run()
 {
     m_task = CreateNewScheduledTask();
     this.Status = TaskStatus.QueuedForRunning;
     m_task.Run();
     this.StartTime = DateTime.Now;
     m_taskMonitor = new TaskMonitor(this);
     m_taskMonitor.Start();
 }
        public void SynchronizeTask()
        {
            string description = string.Format("Schedule for the Tasks. Report '{0}'", Report.FilePath);
            if (!IsTasksSchedule) description = string.Format("Schedule for the output '{0}'. Report '{1}'", Output.Name, Report.FilePath);

            TaskDefinition definition = Task.Definition;
            if (definition.RegistrationInfo.Source != TaskSource || definition.RegistrationInfo.Description != description || TaskName != Task.Name)
            {
                definition.RegistrationInfo.Source = TaskSource;
                definition.RegistrationInfo.Description = description;
                //If name has changed, we have to delete then insert it again...
                if (!string.IsNullOrEmpty(Task.Name) && TaskName != Task.Name)
                {
                    Report.TaskFolder.DeleteTask(Task.Name);
                    _task = Report.TaskFolder.RegisterTaskDefinition(TaskName, definition, TaskCreation.CreateOrUpdate, null);
                }
                else
                {
                    _task.RegisterChanges();
                }
            }
        }
 /// <summary>
 /// Gets the task with the specified path.
 /// </summary>
 /// <param name="taskPath">The task path.</param>
 /// <returns>The task.</returns>
 public Task GetTask(string taskPath)
 {
     Task t = null;
     if (v2)
     {
         V2Interop.IRegisteredTask iTask = GetTask(this.v2TaskService, taskPath);
         if (iTask != null)
             t = new Task(this, iTask);
     }
     else
     {
         V1Interop.ITask iTask = GetTask(this.v1TaskScheduler, taskPath);
         if (iTask != null)
             t = new Task(this, iTask);
     }
     return t;
 }
 public Dev2Task(ITaskServiceConvertorFactory taskServiceConvertorFactory, Task nativeObject)
 {
     _nativeObject = nativeObject;
     _taskServiceConvertorFactory = taskServiceConvertorFactory;
 }
		private void wizardControl1_Finished(object sender, System.EventArgs e)
		{
			bool myTS = false;

			if (this.TaskService == null)
			{
				this.TaskService = new TaskService();
				myTS = true;
			}

			td.Data = TaskName;
			td.RegistrationInfo.Description = descText.Text;
			td.Triggers.Clear();
			td.Triggers.Add(trigger);
			td.Actions.Clear();
			td.Actions.Add(action);
			if (openDlgAfterCheck.Checked)
			{
				TaskEditDialog dlg = new TaskEditDialog();
				dlg.Editable = true;
				dlg.Initialize(this.TaskService, td);
				dlg.RegisterTaskOnAccept = false;
				dlg.TaskName = TaskName;
				if (dlg.ShowDialog(this.ParentForm) == System.Windows.Forms.DialogResult.OK)
					this.td = dlg.TaskDefinition;
			}
			if (RegisterTaskOnFinish)
			{
				TaskFolder fld = this.TaskService.RootFolder;
				if (!string.IsNullOrEmpty(this.TaskFolder) && TaskService.HighestSupportedVersion.CompareTo(new Version(1, 1)) != 0)
					fld = this.TaskService.GetFolder(this.TaskFolder);
				task = fld.RegisterTaskDefinition(TaskName, td, TaskCreation.CreateOrUpdate, td.Principal.ToString(), Password, td.Principal.LogonType);
			}

			if (myTS)
				this.TaskService = null;
		}