private void AddStartupTask()
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    using (Microsoft.Win32.TaskScheduler.TaskService tastService = new Microsoft.Win32.TaskScheduler.TaskService())
                    {
                        Microsoft.Win32.TaskScheduler.TaskDefinition task  = tastService.NewTask();
                        Microsoft.Win32.TaskScheduler.LogonTrigger trigger = new Microsoft.Win32.TaskScheduler.LogonTrigger()
                        {
                            Delay = TimeSpan.FromSeconds(10)
                        };

                        task.Principal.RunLevel = Microsoft.Win32.TaskScheduler.TaskRunLevel.Highest;
                        task.Settings.DisallowStartIfOnBatteries = false;
                        task.Settings.StopIfGoingOnBatteries     = false;
                        task.Settings.RunOnlyIfNetworkAvailable  = false; // Always start up regardless of network availability as the application can handle itself when there is no network connection.
                        task.Settings.RunOnlyIfIdle      = false;
                        task.Settings.ExecutionTimeLimit = TimeSpan.Zero;
                        task.Triggers.Add(trigger);
                        task.Actions.Add(
                            new ExecAction($"\"{Assembly.GetExecutingAssembly().Location}\"", null, $"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}"));
                        task.RegistrationInfo.Description = $"{BrandName} automatic startup.";
                        tastService.RootFolder.RegisterTaskDefinition(BrandName, task);
                    }
                }
                catch (Exception ex)
                {
                    _logger.Debug(ex, "Unable to add the startup task ");
                }
            });
        }
Example #2
0
        /// <summary>
        /// Creates the windows scheduled task
        /// </summary>
        /// <param name="domains"></param>
        /// <param name="taskName"></param>
        public static void CreateScheduledTask(string taskName, List <string> domains)
        {
            if (taskName == null)
            {
                return;
            }
            try {
                using (TS.TaskService ts = new TS.TaskService()) {
                    // Create a new task definition and assign properties
                    TS.TaskDefinition td = ts.NewTask();
                    td.RegistrationInfo.Description = "Manages certificate using ACME";

                    // We need to run as SYSTEM user
                    td.Principal.UserId = @"NT AUTHORITY\SYSTEM";

                    // Create a trigger that will fire the task at this time every other day
                    td.Triggers.Add(new TS.DailyTrigger {
                        DaysInterval = 2
                    });

                    // Create an action that will launch Notepad whenever the trigger fires
                    td.Actions.Add(new TS.ExecAction("WinCertes.exe", "-d " + String.Join(" -d ", domains), Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));

                    // Register the task in the root folder
                    ts.RootFolder.RegisterTaskDefinition($"WinCertes - {taskName}", td);
                }
                logger.Info($"Scheduled Task \"WinCertes - {taskName}\" created successfully");
            } catch (Exception e) {
                logger.Error("Unable to create Scheduled Task" + e.Message);
            }
        }
Example #3
0
        private void setupTask(string tskName)
        {
            using (Scheduler.TaskService tsrv = new Scheduler.TaskService()) {
                Scheduler.TaskDefinition tskDef = tsrv.FindTask(tskName).Definition;

                tskDef.Settings.DisallowStartIfOnBatteries = false;
                tskDef.Settings.RunOnlyIfNetworkAvailable  = true;
                tskDef.RegistrationInfo.Author             = _taskAuthor;
                tskDef.RegistrationInfo.Documentation      = "TimeSharp time keeper utility";
                tskDef.Principal.RunLevel         = Scheduler.TaskRunLevel.Highest;
                tskDef.Settings.MultipleInstances = Scheduler.TaskInstancesPolicy.IgnoreNew;
                tskDef.Settings.WakeToRun         = false;
                tskDef.Settings.Compatibility     = Scheduler.TaskCompatibility.V2_1;

                //add auxiliary triggers
                Scheduler.SessionStateChangeTrigger unlockSessionTrigger = new Scheduler.SessionStateChangeTrigger(Scheduler.TaskSessionStateChangeType.SessionUnlock)
                {
                    Enabled = true
                };
                Scheduler.LogonTrigger logonTrigger = new Scheduler.LogonTrigger()
                {
                    Enabled            = true,
                    Delay              = TimeSpan.FromMinutes(1),
                    StartBoundary      = DateTime.Now,
                    ExecutionTimeLimit = TimeSpan.FromMinutes(5)
                };
                tskDef.Triggers.AddRange(new Scheduler.Trigger[] { unlockSessionTrigger, logonTrigger });

                tsrv.RootFolder.RegisterTaskDefinition(tskName, tskDef,
                                                       Scheduler.TaskCreation.CreateOrUpdate, _adminsGroupName, null,
                                                       Scheduler.TaskLogonType.Group);
            }
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="TaskEditDialog"/> class.
		/// </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>
		/// <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(TaskService service, TaskDefinition td = null, bool editable = true, bool registerOnAccept = true)
		{
			InitializeComponent();
			this.Editable = editable;
			this.Initialize(service, td);
			this.RegisterTaskOnAccept = registerOnAccept;
		}
        public void Init()
        {
            _taskServiceConvertorFactory = new Mock<ITaskServiceConvertorFactory>();
            _nativeService = new TaskService();//localhost
            _nativeTask = _nativeService.NewTask();//actually a definition , not an actual task
            _nativeInstance = _nativeTask.Actions;

        }
Example #6
0
 public ScheduledTask(string taskName, string taskDescription)
 {
     this.taskName = taskName;
     this.taskDescription = taskDescription;
     task = new TaskService();
     taskDef = task.NewTask();
     this.serialActions = new List<SerialAction>();
     this.serialTriggers = new List<SerialTrigger>();
     this.triggers = new List<Trigger>();
     this.actions = new List<ExecAction>();
 }
Example #7
0
        public static void TrySetLaunchAtStartup(bool enabled, string username = null, string userpassword = null)
        {
            string name = Application.ProductName;

            using (MW32TS.TaskService service = new MW32TS.TaskService())
            {
                TryDeleteTasksByName(name);

                if (!enabled)
                {
                    return;
                }

                MW32TS.LogonTrigger trigger = new MW32TS.LogonTrigger();


                // MW32TS.BootTrigger trigger = new MW32TS.BootTrigger();
                // trigger.Delay = new TimeSpan(0, 0, 5);
                //trigger.Enabled = true;

                MW32TS.ExecAction action = new MW32TS.ExecAction(Application.ExecutablePath, null, null);
                action.WorkingDirectory = Application.StartupPath;

                MW32TS.TaskDefinition definition = service.NewTask();
                definition.RegistrationInfo.Description = "Launches App At Startup";
                definition.Triggers.Add(trigger);
                definition.Actions.Add(action);

                definition.Principal.RunLevel = MW32TS.TaskRunLevel.Highest;
                //definition.Principal.
                if (!username.IsNullOrEmpty())
                {
                    service.UserName = username;
                }

                if (!userpassword.IsNullOrEmpty())
                {
                    service.UserPassword = userpassword;
                }

                service.RootFolder.RegisterTaskDefinition(name, definition);
            }
        }
Example #8
0
        public static void SetAutorunValue(bool autorun)
        {
            using (TaskService ts = new TaskService())
            {
                if (autorun)
                {
                    td = ts.NewTask();
                    td.RegistrationInfo.Description = "Запуск Alerts";

                    td.Triggers.Add(new LogonTrigger());


                    td.Actions.Add(new ExecAction(Application.ExecutablePath));
                    td.Principal.RunLevel = TaskRunLevel.Highest;

                    ts.RootFolder.RegisterTaskDefinition("Alerts", td);
                }
                else
                {
                    ts.RootFolder.DeleteTask("Alerts");
                }
            }
        }
        /// <summary>
        /// Registers (creates) a task in a specified location using a <see cref="TaskDefinition"/> instance to define a task.
        /// </summary>
        /// <param name="Path">The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path.</param>
        /// <param name="definition">The <see cref="TaskDefinition"/> of the registered task.</param>
        /// <param name="createType">A union of <see cref="TaskCreation"/> flags.</param>
        /// <param name="UserId">The user credentials used to register the task.</param>
        /// <param name="password">The password for the userId used to register the task.</param>
        /// <param name="LogonType">A <see cref="TaskLogonType"/> value that defines what logon technique is used to run the registered task.</param>
        /// <param name="sddl">The security descriptor associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task.</param>
        /// <returns>A <see cref="Task"/> instance that represents the new task.</returns>
        public Task RegisterTaskDefinition(string Path, TaskDefinition definition, TaskCreation createType, string UserId, string password, TaskLogonType LogonType, string sddl)
        {
            if (v2Folder != null)
                return new Task(this.TaskService, v2Folder.RegisterTaskDefinition(Path, definition.v2Def, (int)createType, UserId, password, LogonType, sddl));

            // Adds ability to set a password for a V1 task. Provided by Arcao.
            V1Interop.TaskFlags flags = definition.v1Task.GetFlags();
            switch (LogonType)
            {
                case TaskLogonType.Group:
                case TaskLogonType.S4U:
                case TaskLogonType.None:
                    throw new NotV1SupportedException("This LogonType is not supported on Task Scheduler 1.0.");
                case TaskLogonType.InteractiveToken:
                    flags |= (V1Interop.TaskFlags.RunOnlyIfLoggedOn | V1Interop.TaskFlags.Interactive);
                    if (String.IsNullOrEmpty(UserId))
                        UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                    definition.v1Task.SetAccountInformation(UserId, IntPtr.Zero);
                    break;
                case TaskLogonType.ServiceAccount:
                    flags &= ~(V1Interop.TaskFlags.Interactive | V1Interop.TaskFlags.RunOnlyIfLoggedOn);
                    definition.v1Task.SetAccountInformation(String.IsNullOrEmpty(UserId) ? String.Empty : UserId, IntPtr.Zero);
                    break;
                case TaskLogonType.InteractiveTokenOrPassword:
                    flags |= V1Interop.TaskFlags.Interactive;
                    using (V1Interop.CoTaskMemString cpwd = new V1Interop.CoTaskMemString(password))
                        definition.v1Task.SetAccountInformation(UserId, cpwd.DangerousGetHandle());
                    break;
                case TaskLogonType.Password:
                    using (V1Interop.CoTaskMemString cpwd = new V1Interop.CoTaskMemString(password))
                        definition.v1Task.SetAccountInformation(UserId, cpwd.DangerousGetHandle());
                    break;
                default:
                    break;
            }
            definition.v1Task.SetFlags(flags);

            switch (createType)
            {
                case TaskCreation.Create:
                case TaskCreation.CreateOrUpdate:
                case TaskCreation.Disable:
                case TaskCreation.Update:
                    if (createType == TaskCreation.Disable)
                        definition.Settings.Enabled = false;
                    definition.V1Save(Path);
                    break;
                case TaskCreation.DontAddPrincipalAce:
                    throw new NotV1SupportedException("Security settings are not available on Task Scheduler 1.0.");
                case TaskCreation.IgnoreRegistrationTriggers:
                    throw new NotV1SupportedException("Registration triggers are not available on Task Scheduler 1.0.");
                case TaskCreation.ValidateOnly:
                    throw new NotV1SupportedException("Xml validation not available on Task Scheduler 1.0.");
                default:
                    break;
            }
            return new Task(this.TaskService, definition.v1Task);
        }
Example #10
0
 /// <summary>
 /// Registers (creates) a task in a specified location using a <see cref="TaskDefinition"/> instance to define a task.
 /// </summary>
 /// <param name="Path">The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path.</param>
 /// <param name="definition">The <see cref="TaskDefinition"/> of the registered task.</param>
 /// <returns>A <see cref="Task"/> instance that represents the new task.</returns>
 public Task RegisterTaskDefinition(string Path, TaskDefinition definition)
 {
     return RegisterTaskDefinition(Path, definition, TaskCreation.CreateOrUpdate, definition.Principal.UserId, null, definition.Principal.LogonType, null);
 }
 public IDev2TaskDefinition CreateTaskDefinition(TaskDefinition taskDefinition)
 {
     return new Dev2TaskDefinition(this, taskDefinition);
 }
        private static Dev2TaskDefinition Dev2TaskDefinition(TaskDefinition native)
        {
            var factory = new TaskServiceConvertorFactory();

            var defn = new Dev2TaskDefinition(factory, native);
            return defn;
        }
        /// <summary>
        /// Adds scheduled trigger(s) to <paramref name="taskDefinition"/> based on
        /// <paramref name="intervalMinutes"/>.
        /// </summary>
        /// <param name="taskDefinition">The task to add the trigger(s) to.</param>
        /// <param name="intervalMinutes">This must be a number less than 1 or a whole number (integer) greater than 1.</param>
        private void AddSchedule(TaskDefinition taskDefinition, float intervalMinutes)
        {
            int frequencySeconds = Convert.ToInt32(intervalMinutes * 60.0);
            int schedules = frequencySeconds >= 60 ? 1 : 60 / frequencySeconds;

            for (int i = 0; i < schedules; i++)
            {
                int intervalInt;
                if (!int.TryParse(intervalMinutes.ToString(CultureInfo.InvariantCulture), out intervalInt))
                {
                    intervalInt = 1;
                }

                Trigger trigger = taskDefinition.Triggers.AddNew(TaskTriggerType.Daily);
                trigger.Repetition.Interval = new TimeSpan(0, intervalInt, 0);
                trigger.StartBoundary = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, i * frequencySeconds);
            }
        }
		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;
		}
Example #15
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);
     }
 }
Example #16
0
 public Dev2TaskDefinition(ITaskServiceConvertorFactory taskServiceConvertorFactory,
     TaskDefinition taskDefinition)
 {
     _taskServiceConvertorFactory = taskServiceConvertorFactory;
     _taskDefinition = taskDefinition;
 }
		/// <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", GetServerString(service));
			this.okBtn.Enabled = false;
			taskPropertiesControl1.Initialize(service, td);
		}
 static string WriteXml(TaskDefinition td, string name)
 {
     string fn = GetTempXmlFile(name);
     System.IO.File.WriteAllText(fn, td.XmlText, System.Text.Encoding.Unicode);
     return fn;
 }
 static TaskDefinition DisplayTask(TaskService ts, TaskDefinition td, bool editable)
 {
     if (editorForm == null)
         editorForm = new TaskEditDialog();
     editorForm.Editable = editable;
     editorForm.Initialize(ts, td);
     editorForm.RegisterTaskOnAccept = true;
     editorForm.AvailableTabs = AvailableTaskTabs.All;
     return (editorForm.ShowDialog() == System.Windows.Forms.DialogResult.OK) ? editorForm.TaskDefinition : null;
 }
Example #20
0
        private void AddTrigger(TaskDefinition definition, RepetitiveTask task)
        {
            switch (task.Type)
            {
                case RepetitiveTaskType.Daily:
                    {
                        var trigger = (DailyTrigger)definition.Triggers.Add(new DailyTrigger());
                        trigger.StartBoundary = task.StartAt.HasValue ? task.StartAt.Value : DateTime.Now;
                    }
                    break;
                case RepetitiveTaskType.Weekly:
                    {
                        var trigger = (WeeklyTrigger)definition.Triggers.Add(new WeeklyTrigger(task.DaysOfWeek));
                        trigger.StartBoundary = task.StartAt.HasValue ? task.StartAt.Value : DateTime.Now;
                    }
                    break;

                case RepetitiveTaskType.Monthly:
                    {
                        var trigger = (MonthlyTrigger)definition.Triggers.Add(new MonthlyTrigger(task.DayOfMonth));
                        trigger.StartBoundary = task.StartAt.HasValue ? task.StartAt.Value : DateTime.Now;
                    }
                    break;
                case RepetitiveTaskType.Interval:
                    {
                        var trigger = (TimeTrigger)definition.Triggers.Add(new TimeTrigger());
                        trigger.StartBoundary = task.StartAt.HasValue ? task.StartAt.Value : DateTime.Now;
                        trigger.Repetition.Interval = task.Interval;
                    }
                    break;
                default:
                    throw new NotSupportedException("The task type is not supported.");
            }

            definition.Settings.StopIfGoingOnBatteries = false;
            definition.Settings.DisallowStartIfOnBatteries = false;
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="TaskSchedulerWizard"/> class.
		/// </summary>
		/// <param name="service">A <see cref="TaskService"/> instance.</param>
		/// <param name="definition">An optional <see cref="TaskDefinition"/>. Leaving null creates a new task.</param>
		/// <param name="registerOnFinish">If set to <c>true</c> the task will be registered when Finish is pressed.</param>
		public TaskSchedulerWizard(TaskService service, TaskDefinition definition = null, bool registerOnFinish = false)
			: this()
		{
			Initialize(service, definition);
			RegisterTaskOnFinish = registerOnFinish;
		}
		/// <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 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="TaskOptionsEditor"/> class.
		/// </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>
		/// <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(TaskService service, TaskDefinition td = null, bool editable = true, bool registerOnAccept = true) : this()
		{
			this.Editable = editable;
			this.Initialize(service, td);
			this.RegisterTaskOnAccept = registerOnAccept;
		}
 /// <summary>
 /// Returns a <see cref="TaskDefinition"/> populated with the properties defined in an XML file.
 /// </summary>
 /// <param name="xmlFile">The XML file to use as input.</param>
 /// <returns>A <see cref="TaskDefinition"/> instance.</returns>
 /// <exception cref="NotV1SupportedException">Importing from an XML file is only supported under Task Scheduler 2.0.</exception>
 public TaskDefinition NewTaskFromFile(string xmlFile)
 {
     if (v2TaskService != null)
     {
         TaskDefinition td = new TaskDefinition(v2TaskService.NewTask(0));
         td.XmlText = System.IO.File.ReadAllText(xmlFile);
         return td;
     }
     throw new NotV1SupportedException();
 }
 /// <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;
     }
 }