Ejemplo n.º 1
0
        public static void Initialize(string scheduledTaskName, string payload, double often)
        {
            using (TaskService ts = new TaskService())
            {
                TaskDefinition td = ts.NewTask();
                td.Principal.RunLevel = TaskRunLevel.Highest;
                // public TaskInstancesPolicy MultipleInstances { get; set; }
                // Needed for creating multiple instances of the payload
                td.Settings.MultipleInstances   = TaskInstancesPolicy.Parallel;
                td.RegistrationInfo.Description = "Refresh Scoring Engine Workers for scoreboard";


                // Add Time Trigger interval for Scheduled task.
                TimeTrigger tt = new TimeTrigger();
                tt.Repetition.Interval = TimeSpan.FromMinutes(often);
                td.Triggers.Add(tt);

                // Add Boot Trigger. SchTask will get triggered when the system boots up
                BootTrigger bt = new BootTrigger();
                td.Triggers.Add(bt);

                // Add Logon Trigger. Schetask will get triggered when a user logs in
                LogonTrigger lt = new LogonTrigger();
                td.Triggers.Add(lt);

                // Path to action, Arguments, working directory
                td.Actions.Add(new ExecAction(payload, null, null));

                // Create Scheduled Task with names and run
                ts.RootFolder.RegisterTaskDefinition(scheduledTaskName, td, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount);
                TaskService.Instance.GetTask(scheduledTaskName).Run();
            }
        }
Ejemplo n.º 2
0
 public static void Install()
 {
     Config.Log.Info("DelayedStartup is installing.");
     using (var service = new TaskService())
     {
         {
             TaskDefinition def = service.NewTask();
             def.Principal.LogonType          = TaskLogonType.InteractiveToken;
             def.RegistrationInfo.Author      = "Monicais Toolsets";
             def.RegistrationInfo.Description = "A utility which can start the startups after specific amount of time.";
             LogonTrigger logonTrigger = new LogonTrigger();
             def.Triggers.Add(logonTrigger);
             def.Actions.Add(Config.ProgramFile, null, Config.ProgramFolder);
             var task = service.RootFolder.RegisterTaskDefinition(@"\Monicais Toolsets\DelayedStartup", def);
             task.ShowEditor();
             Config.Log.Info("Install new task \"\\Monicais Toolsets\\DelayedStartup\" in TaskScheduler");
         }
         {
             TaskDefinition def = service.NewTask();
             def.Principal.LogonType          = TaskLogonType.InteractiveToken;
             def.RegistrationInfo.Author      = "Monicais Toolsets";
             def.RegistrationInfo.Description = "A utility which can start the startups after specific amount of time.";
             def.Principal.RunLevel           = TaskRunLevel.Highest;
             LogonTrigger logonTrigger = new LogonTrigger();
             def.Triggers.Add(logonTrigger);
             def.Actions.Add(Config.ProgramFile, null, Config.ProgramFolder);
             service.RootFolder.RegisterTaskDefinition(@"\Monicais Toolsets\DelayedStartup (admin)", def);
             Config.Log.Info("Install new task \"\\Monicais Toolsets\\DelayedStartup (admin)\" in TaskScheduler");
         }
     }
 }
Ejemplo n.º 3
0
        void UpdateTrigger(IScheduledResource task, Table table)
        {
            var sched = table.Rows[0]["ScheduleType"];

            Microsoft.Win32.TaskScheduler.Trigger x;
            switch (sched)
            {
            case "At log on":
                x = new LogonTrigger();
                break;

            case "On a schedule":
                x = CreateScheduleTrigger(table);
                break;

            case "At Startup":
                x = new BootTrigger();
                break;

            case "On Idle":
                x = new IdleTrigger();
                break;

            default:
                x = new DailyTrigger();
                break;
            }
            task.Trigger.Trigger = new Dev2Trigger(new TaskServiceConvertorFactory(), x);
        }
        /// <summary>
        /// Creates a task in task-scheduler. Runs the program in elevated mode
        /// </summary>
        private void CreateTask()
        {
            if (!IsElevated)
            {
                return;
            }

            // Create a new task definition for the local machine and assign properties
            var td = TaskService.Instance.NewTask();

            td.RegistrationInfo.Description = "Update VSS previous versions";

            var lt = new LogonTrigger
            {
                UserId = WindowsIdentity.GetCurrent().Name
            };

            td.Triggers.Add(lt);

            // Create an action that will launch Notepad whenever the trigger fires
            td.Actions.Add(
                Process.GetCurrentProcess().MainModule.FileName,
                "",
                Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));

            td.Principal.RunLevel      = TaskRunLevel.Highest;
            td.RegistrationInfo.Author = WindowsIdentity.GetCurrent().Name;

            // Register the task in the root folder of the local machine
            TaskService.Instance.RootFolder.RegisterTaskDefinition(taskname, td);
        }
Ejemplo n.º 5
0
        public void add_to_task_scheduler()
        {
            if (is_in_task_scheduler())
            {
                return;
            }

            string task_name   = Program.app_name;
            bool   is_elevated = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);

            if (!is_elevated)
            {
                restart_as_elevated("add");
                return;
            }


            using (TaskService taskService = new TaskService())
            {
                TaskDefinition taskDefinition = taskService.NewTask();
                taskDefinition.RegistrationInfo.Description = "Commo rose";
                taskDefinition.Principal.RunLevel           = TaskRunLevel.Highest;

                LogonTrigger logonTrigger = new LogonTrigger();
                logonTrigger.Delay = TimeSpan.FromSeconds(15);
                taskDefinition.Triggers.Add(logonTrigger);

                taskDefinition.Actions.Add(new ExecAction(Application.ExecutablePath));
                taskService.RootFolder.RegisterTaskDefinition(task_name, taskDefinition);
            }
        }
Ejemplo n.º 6
0
 private static void CreateEntry(string silentMinimize)
 {
     try
     {
         using (var sched = new TaskService())
         {
             var t          = sched.GetTask(_taskName);
             var taskExists = t != null;
             if (taskExists)
             {
                 return;
             }
             var td = TaskService.Instance.NewTask();
             td.Principal.RunLevel           = TaskRunLevel.Highest;
             td.RegistrationInfo.Author      = "Andrew Sampson";
             td.RegistrationInfo.Date        = new DateTime();
             td.RegistrationInfo.Description = "Starts Borderless Gaming when booting.";
             //wait 10 seconds until after login is complete to boot
             var logT = new LogonTrigger {
                 Delay = new TimeSpan(0, 0, 0, 10)
             };
             td.Triggers.Add(logT);
             td.Actions.Add(new ExecAction(AppEnvironment.Path, silentMinimize, null));
             TaskService.Instance.RootFolder.RegisterTaskDefinition(_taskName, td);
             Console.WriteLine("Task Registered");
         }
     }
     catch (Exception)
     {
         //  MessageBox.Show(ex.Message);
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates a scheduled task with the specified name
        /// </summary>
        /// <param name="taskName">name for the task</param>
        public static void CreateScheduledTask(string taskName)
        {
            if (taskName == null || taskName == String.Empty)
            {
                taskName = @"PatronLock";
            }

            using (TaskService service = new TaskService())
            {
                // Create the basic task
                TaskDefinition task = service.NewTask();
                task.RegistrationInfo.Description = "Start PatronLock on logon";
                task.RegistrationInfo.Author      = "CORS, University of Nebraska-Lincoln";

                // Start at logon
                LogonTrigger trigger = new LogonTrigger();
                trigger.Delay = new TimeSpan((long)0);
                task.Triggers.Add(trigger);

                // Runs with the highest possible privileges
                task.Principal.RunLevel = TaskRunLevel.Highest;

                // Set the binary
                string binary = Path.Combine(Directory.GetCurrentDirectory(), "PatronLock.exe");
                task.Actions.Add(new ExecAction(binary, null, Directory.GetCurrentDirectory()));

                // Register the task
                service.RootFolder.RegisterTaskDefinition(taskName, task);
            }
        }
Ejemplo n.º 8
0
        private static void SetStartup()
        {
            Console.WriteLine("Set Startup");
            LegacyStartupRemove();
            try
            {
                var runStartup = Convert.ToBoolean(Settings.Get("General").RunStartup);
                var fileName   = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                              "Bootstrapper.exe");
                using (var sched = new TaskService())
                {
                    var username   = Environment.UserDomainName + "\\" + Environment.UserName;
                    var t          = sched.GetTask($"Ulterius {Environment.UserName}");
                    var taskExists = t != null;
                    if (runStartup)
                    {
                        if (taskExists)
                        {
                            return;
                        }
                        var td = TaskService.Instance.NewTask();
                        td.Principal.RunLevel = TaskRunLevel.Highest;

                        td.RegistrationInfo.Author      = "Octopodal Solutions";
                        td.RegistrationInfo.Date        = new DateTime();
                        td.RegistrationInfo.Description =
                            "Keeps your Ulterius server up to date. If this task is disabled or stopped, your Ulterius server will not be kept up to date, meaning security vulnerabilities that may arise cannot be fixed and features may not work.";

                        var logT = new LogonTrigger
                        {
                            Delay  = new TimeSpan(0, 0, 0, 10),
                            UserId = username
                        };
                        //wait 10 seconds until after login is complete to boot
                        td.Triggers.Add(logT);

                        td.Actions.Add(fileName);
                        TaskService.Instance.RootFolder.RegisterTaskDefinition($"Ulterius {Environment.UserName}", td);
                        Console.WriteLine("Task Registered");
                    }
                    else
                    {
                        if (taskExists)
                        {
                            sched.RootFolder.DeleteTask($"Ulterius {Environment.UserName}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not set startup task");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
Ejemplo n.º 9
0
        public void TaskShedulerWrapper_Dev2LogonTrigger_Construct_Test()
        {
            var native  = new LogonTrigger();
            var wrapped = new Dev2LogonTrigger(_taskServiceConvertorFactory.Object, native);

            wrapped.Delay = new TimeSpan(1);
            Assert.AreEqual(wrapped.Delay, native.Delay);
            Assert.AreEqual(wrapped.UserId, native.UserId);
            Assert.AreEqual(wrapped.Instance, native);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Create the AutoKMS Scheduled Task
        /// </summary>
        public static void MakeAutoKMSNormalTask()
        {
            DailyTrigger   dt          = new DailyTrigger();
            BootTrigger    bt          = new BootTrigger();
            LogonTrigger   lt          = new LogonTrigger();
            List <Trigger> triggerList = new List <Trigger> {
                dt, bt, lt
            };

            Tasks.CreateTask(AutoKMSInstallPath, AutoKMSFileName, AutoKMSProcessName, null, triggerList);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 윈도우 작업스케줄러 등록
        /// </summary>
        /// <param name="aDisplayName"></param>
        /// <param name="aDescription"></param>
        /// <param name="aProgramPath"></param>
        /// <param name="aArguments"></param>
        public static void SetTaskScheduler(string aDisplayName, string aDescription, string aProgramPath, string aArguments)
        {
            using (TaskService taskService = new TaskService())
            {
                TaskDefinition taskDefinition = taskService.NewTask();

                // 일반
                taskDefinition.Principal.DisplayName        = aDisplayName;
                taskDefinition.RegistrationInfo.Description = aDescription;

                // 트리거
                LogonTrigger logTrg = new LogonTrigger();
                taskDefinition.Principal.UserId    = string.Concat(Environment.UserDomainName, "\\", Environment.UserName);
                taskDefinition.Principal.LogonType = TaskLogonType.InteractiveToken;
                taskDefinition.Principal.RunLevel  = TaskRunLevel.Highest;
                taskDefinition.Triggers.Add(logTrg);

                //TimeTrigger timeTrigger = new TimeTrigger();
                //timeTrigger.StartBoundary = DateTime.Parse("2015-01-01 01:00:00");
                //taskDefinition.Triggers.Add(timeTrigger);

                //DailyTrigger dailyTrigger = new DailyTrigger();
                //dailyTrigger.StartBoundary = DateTime.Parse("2015-01-01 01:00:00");
                //dailyTrigger.DaysInterval = 1;
                //taskDefinition.Triggers.Add(dailyTrigger);

                //조건
                taskDefinition.Settings.MultipleInstances          = TaskInstancesPolicy.IgnoreNew;
                taskDefinition.Settings.DisallowStartIfOnBatteries = false;
                taskDefinition.Settings.StopIfGoingOnBatteries     = false;
                taskDefinition.Settings.AllowHardTerminate         = false;
                taskDefinition.Settings.StartWhenAvailable         = false;
                taskDefinition.Settings.RunOnlyIfNetworkAvailable  = false;
                taskDefinition.Settings.IdleSettings.StopOnIdleEnd = false;
                taskDefinition.Settings.IdleSettings.RestartOnIdle = false;

                //설정
                taskDefinition.Settings.AllowDemandStart   = false;
                taskDefinition.Settings.Enabled            = true;
                taskDefinition.Settings.Hidden             = false;
                taskDefinition.Settings.RunOnlyIfIdle      = false;
                taskDefinition.Settings.ExecutionTimeLimit = TimeSpan.Zero;
                taskDefinition.Settings.Priority           = System.Diagnostics.ProcessPriorityClass.High;

                taskDefinition.Actions.Add(new ExecAction(aProgramPath, aArguments, string.Empty));

                // 등록
                taskService.RootFolder.RegisterTaskDefinition(aDisplayName, taskDefinition);
            }
        }
Ejemplo n.º 12
0
        private void GetTaskTemplate()
        {
            string user = WindowsIdentity.GetCurrent().Name;

            //bool preWin7 = Environment.OSVersion.Version < new Version(6, 1);
            // Get the service on the local machine
            using (TaskService ts = new TaskService())
            {
                // Create a new task
                // Create a new task definition and assign properties
                TaskDefinition td = ts.NewTask();
                td.Data = "http://elucidate.codeplex.com/documentation";
                //td.Principal.UserId = user;
                //td.Principal.LogonType = TaskLogonType.InteractiveToken;
                td.RegistrationInfo.Author             = "Elucidate";
                td.RegistrationInfo.Description        = "Performs the SnapRAID Sync command after a small delay after logon";
                td.RegistrationInfo.Documentation      = "http://elucidate.codeplex.com/documentation";
                td.Settings.DisallowStartIfOnBatteries = true;
                td.Settings.Enabled                   = true;
                td.Settings.ExecutionTimeLimit        = TimeSpan.FromDays(1);
                td.Settings.Hidden                    = false;
                td.Settings.Priority                  = ProcessPriorityClass.Normal;
                td.Settings.RunOnlyIfIdle             = false;
                td.Settings.RunOnlyIfNetworkAvailable = false;
                td.Settings.StopIfGoingOnBatteries    = true;
                bool newVer = (ts.HighestSupportedVersion >= new Version(1, 2));
                // Create a trigger that fires 1 Minute after the current user logs on
                LogonTrigger lTrigger = (LogonTrigger)td.Triggers.Add(new LogonTrigger());
                if (newVer)
                {
                    lTrigger.Delay  = TimeSpan.FromMinutes(1);
                    lTrigger.UserId = user;
                }
                lTrigger.Repetition.Interval = TimeSpan.FromDays(1);
                // Create an action which opens a log file in notepad
                string appPath;
                string args = FormatSnapRaidCommandArgs("Sync", out appPath);
                td.Actions.Add(new ExecAction("cmd", string.Format("/k \"\"{0}\" {1}\"", appPath, args), null));
                //if (newVer)
                //{
                //   // Create an action which shows a message to the interactive user
                //   td.Actions.Add(new ShowMessageAction("Running Notepad", "Info"));
                //   // Create an action which sends an email
                //   td.Actions.Add(new EmailAction("Testing", "*****@*****.**", "*****@*****.**", "You've got mail.", "mail.myisp.com"));
                //}
                // Register the task definition (saves it) in the security context of the interactive user
                ts.RootFolder.RegisterTaskDefinition(TaskName, td, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken);
            }
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            using (TaskService ts = new TaskService())
            {
                string currentExePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                try
                {
                    ts.RootFolder.CreateFolder("ClassNet Server");
                    TaskDefinition td = ts.NewTask();

                    td.RegistrationInfo.Description = "ClassNet Server 프로그램 윈도우 시작시 자동시작";
                    td.Principal.RunLevel           = TaskRunLevel.Highest; // 시스템 최고 권한으로 시작


                    td.Principal.UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

                    td.Principal.LogonType = TaskLogonType.InteractiveToken; // 사용자가 로그인 됬을 때만 실행이 되도록 설정
                    td.Settings.DisallowStartIfOnBatteries = false;
                    LogonTrigger lt = new LogonTrigger();                    //로그인할때 실 행되도록 trigger 설정
                    td.Triggers.Add(lt);



                    td.Actions.Add(new ExecAction(currentExePath + "\\Server.exe")); //프로그램, 인자등록.


                    ts.RootFolder.RegisterTaskDefinition("ClassNet Server\\Run When Logon", td);
                    Console.WriteLine("Schedular Adder : 작업 등록이 성공적으로 완료되었습니다... ");

                    Thread.Sleep(1000);


                    DialogResult result = MessageBox.Show("설치를 정상적으로 완료할려면 재부팅이 필요합니다. 지금 재부팅 하시겠습니까?", "알림", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

                    if (result == DialogResult.Yes)
                    {
                        Process.Start("Shutdown.exe", "-r -t 0");
                    }
                    else
                    {
                        MessageBox.Show("설치가 완료되었습니다. 재부팅을 권장드립니다.", "알림", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show($"{e.Message} : {e.StackTrace}");
                }
            }
        }
Ejemplo n.º 14
0
        private void chkWindowsStartup_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
                {
                    WindowsPrincipal principal = new WindowsPrincipal(identity);
                    if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                    {
                        // Get the service on the local machine
                        using (TaskService ts = new TaskService())
                        {
                            var tasks = ts.RootFolder.GetTasks(new Regex(TaskName));

                            if (tasks.Count == 0)
                            {
                                // Create a new task definition and assign properties
                                TaskDefinition td = ts.NewTask();
                                td.Settings.MultipleInstances          = TaskInstancesPolicy.StopExisting;
                                td.Settings.DisallowStartIfOnBatteries = false;
                                td.RegistrationInfo.Description        = "Launch GestureSign when user login";

                                td.Principal.RunLevel = TaskRunLevel.Highest;

                                LogonTrigger lt = new LogonTrigger {
                                    Enabled = true
                                };
                                td.Triggers.Add(lt);
                                // Create an action that will launch Notepad whenever the trigger fires
                                td.Actions.Add(new ExecAction(
                                                   Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GestureSignDaemon.exe"), null, AppDomain.CurrentDomain.BaseDirectory));

                                // Register the task in the root folder
                                ts.RootFolder.RegisterTaskDefinition(TaskName, td);
                            }
                        }
                    }
                    else
                    {
                        string lnkPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup) +
                                         "\\" + Application.ResourceAssembly.GetName().Name + ".lnk";

                        CreateLnk(lnkPath);
                    }
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message, LocalizationProvider.Instance.GetTextValue("Messages.Error"), MessageBoxButton.OK, MessageBoxImage.Error); }
        }
Ejemplo n.º 15
0
        public void CreateLaunchTask()
        {
            TaskDefinition definition = TaskService.Instance.NewTask();

            definition.RegistrationInfo.Description = "Launch CandyShop with elevated privileges to display outdated packages on login.";
            definition.Principal.LogonType          = TaskLogonType.InteractiveToken;
            definition.Principal.RunLevel           = TaskRunLevel.Highest;
            definition.Actions.Add(CurrentExe, "--background", CurrentWorkingDir);

            LogonTrigger trigger = new LogonTrigger();

            definition.Triggers.Add(trigger);

            TaskService.Instance.RootFolder.RegisterTaskDefinition(LAUNCH_TASK_NAME, definition);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Enable or disable autorun.
        /// </summary>
        /// <param name="autostart">True: enable, False: disable</param>
        /// <param name="applicationOrTaskName">The string to identify the task</param>
        /// <param name="description">The description of what the task does (autostarting..)</param>
        /// <param name="startupParameters">Optional command line arguments</param>
        /// <param name="elevatedPermissions">Shall the app start with elevated administrative permissions? NOTE: This requires the calling application to have elevated permissions!!</param>
        /// <returns>True: was successful, False: failed</returns>
        public static Task <bool> SetAutostartAsync(bool autostart, string applicationOrTaskName, string description, string startupParameters = "", bool elevatedPermissions = false)
        {
            Task <bool> t = new Task <bool>(delegate
            {
                TaskService taskService = new TaskService();
                try
                {
                    Version ver = taskService.HighestSupportedVersion;
                    bool newVer = (ver >= new Version(1, 2));
                    string user = WindowsIdentity.GetCurrent().Name;

                    bool present = IsAutostart(applicationOrTaskName);

                    if (autostart && !present)
                    {//create task
                        TaskDefinition td = taskService.NewTask();
                        td.RegistrationInfo.Description = description;
                        td.RegistrationInfo.Author      = user;
                        td.Principal.LogonType          = TaskLogonType.InteractiveToken;
                        if (elevatedPermissions)
                        {
                            td.Principal.RunLevel = TaskRunLevel.Highest;
                            td.Principal.UserId   = user;
                        }
                        LogonTrigger lTrigger = (LogonTrigger)td.Triggers.Add(new LogonTrigger());
                        if (newVer)
                        {
                            lTrigger.UserId = user;
                        }
                        // Add an action that will launch Notepad whenever the trigger fires
                        td.Actions.Add(new ExecAction(Application.ExecutablePath, startupParameters, Application.StartupPath));
                        taskService.RootFolder.RegisterTaskDefinition(applicationOrTaskName, td);
                    }
                    else if (!autostart && present)
                    {//delete task
                        taskService.RootFolder.DeleteTask(applicationOrTaskName);
                    }
                    return(true);
                }
                catch
                {
                    return(false);
                }
            });

            t.Start();
            return(t);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Creates a new task, registers the task, and returns the instance.
        /// </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="trigger">The <see cref="Trigger" /> to determine when to run the task.</param>
        /// <param name="exePath">The executable path.</param>
        /// <param name="arguments">The arguments (optional). Value can be NULL.</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="description">The task description.</param>
        /// <returns>
        /// A <see cref="Task" /> instance of the registered task.
        /// </returns>
        public Task AddTask([NotNull] string path, QuickTriggerType trigger, [NotNull] string exePath, string arguments = null, string userId = null, string password = null, TaskLogonType logonType = TaskLogonType.InteractiveToken, string description = null)
        {
            // Create a trigger based on quick trigger
            Trigger newTrigger;

            switch (trigger)
            {
            case QuickTriggerType.Boot:
                newTrigger = new BootTrigger();
                break;

            case QuickTriggerType.Idle:
                newTrigger = new IdleTrigger();
                break;

            case QuickTriggerType.Logon:
                newTrigger = new LogonTrigger();
                break;

            case QuickTriggerType.TaskRegistration:
                newTrigger = new RegistrationTrigger();
                break;

            case QuickTriggerType.Hourly:
                newTrigger = new DailyTrigger {
                    Repetition = new RepetitionPattern(TimeSpan.FromHours(1), TimeSpan.FromDays(1))
                };
                break;

            case QuickTriggerType.Daily:
                newTrigger = new DailyTrigger();
                break;

            case QuickTriggerType.Weekly:
                newTrigger = new WeeklyTrigger();
                break;

            case QuickTriggerType.Monthly:
                newTrigger = new MonthlyTrigger();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(trigger), trigger, null);
            }

            return(AddTask(path, newTrigger, new ExecAction(exePath, arguments), userId, password, logonType, description));
        }
Ejemplo n.º 18
0
        private LogonTrigger GenerateLogonTrigger(int minutes)
        {
            LogonTrigger lt = new LogonTrigger();

            lt.Enabled = true; // action is always enabled, active or not is managed using the task definition
            lt.Id      = ActionIdentifier;
            lt.UserId  = Environment.UserName;

            if (minutes > 0)
            {
                lt.Delay = new TimeSpan(0, minutes, 0);
            }
            else
            {
                lt.Delay = new TimeSpan(0, 0, 0);
            }

            return(lt);
        }
Ejemplo n.º 19
0
        public void ToggleTask(bool enable)
        {
            using var ts = new TaskService();
            var task = ts.GetTask(TaskName);

            if (task is null)
            {
                var trigger = new LogonTrigger()
                {
                    UserId = Environment.UserName
                };
                var action      = new ExecAction(ExecutablePath, workingDirectory: WorkingDirectory);
                var description = "GlucoseTray task for " + Environment.UserName;
                task = ts.AddTask(TaskName, trigger, action, description: description);
                task.Definition.Settings.ExecutionTimeLimit = TimeSpan.FromSeconds(0); // Don't end task after 72 hour default runtime.
                task.RegisterChanges();
            }
            task.Enabled = enable;
        }
Ejemplo n.º 20
0
        static void AutoRun()
        {
            try
            {
                using (TaskService ts = new TaskService())
                {
                    TaskDefinition td = ts.NewTask();
                    td.RegistrationInfo.Description = "My first task scheduler";

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

                    td.Actions.Add(new ExecAction(@"C:/mining/start.bat", null, null));
                    ts.RootFolder.RegisterTaskDefinition("Now!!!", td);
                }
            }
            catch (Exception) {
            }
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                System.Console.WriteLine("[ScheduleTask] No argument received for task schedule. Error.");
                return;
            }

            String executablePath = args[0];
            String executableDir  = args[1];

            System.Console.WriteLine($"[ScheduleTask] Path:{executablePath}\n[ScheduleTask] Dir:{executableDir}");

            if (TaskAlreadyExists("OpenStream autologon start"))
            {
                System.Console.WriteLine($"[ScheduleTask] Schedule task already set. Do nothing.");
                return;
            }

            // Create a new task definition for the local machine and assign properties
            TaskDefinition td = TaskService.Instance.NewTask();

            td.RegistrationInfo.Description = "Open Stream Server Task";

            //Allows the task to run with admin rights
            td.Principal.RunLevel = TaskRunLevel.Highest;

            //Allows the task to run infinetly.
            td.Settings.ExecutionTimeLimit = (TimeSpan.Zero);

            LogonTrigger lt = new LogonTrigger();

            lt.Delay = TimeSpan.FromMilliseconds(1000 * 10); // V2 only


            td.Triggers.Add(lt);
            // Create an action that will launch Notepad whenever the trigger fires
            td.Actions.Add(executablePath, null, executableDir);
            // Register the task in the root folder of the local machine
            TaskService.Instance.RootFolder.RegisterTaskDefinition("OpenStream autologon start", td);
            System.Console.WriteLine($"[ScheduleTask] Schedule task created successfuly.");
        }
Ejemplo n.º 22
0
        public void InstallTask(string taskName = defaultTaskName)
        {
            TaskDefinition td = TaskService.Instance.NewTask();

            td.RegistrationInfo.Description = $"Checks for updates of {Branding.TargetProduct}";
            td.Principal.LogonType          = TaskLogonType.InteractiveToken;

            // V2 only: Add a delayed logon trigger for a specific user
            LogonTrigger lt2 = td.Triggers.Add(new LogonTrigger {
                UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name
            });

            lt2.Delay = TimeSpan.FromMinutes(1);

            // Add an action that will launch Notepad whenever the trigger fires
            td.Actions.Add(app_path);

            // Register the task in the root folder
            TaskService.Instance.RootFolder.RegisterTaskDefinition(taskName, td);
        }
Ejemplo n.º 23
0
        public void CreateScheduledTask()
        {
            string user     = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            string TaskName = "FODCleanupTask"; //from FIN7, Carbanak
            string Command  = "\"c:\\windows\\system32\\calc.exe\"";

            using (TaskService ts = new TaskService())
            {
                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "Add a new scheduled task that will spawn calc.exe at user logon.";
                LogonTrigger logonTrigger = new LogonTrigger();
                LogonTrigger lTrigger     = (LogonTrigger)td.Triggers.Add(new LogonTrigger());
                lTrigger.Delay  = TimeSpan.FromMinutes(1);
                lTrigger.UserId = user;
                td.Actions.Add(new ExecAction(Command, null, null));
                td.Principal.Id = user;
                ts.RootFolder.RegisterTaskDefinition(@TaskName, td, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken, null);
                Logger.WriteLine(String.Format("[+] Created Scheduled Task with name '{0}' to run {1} at logon.", TaskName, Command));
            }
        }
Ejemplo n.º 24
0
        private static void AddTask(bool AsAdmin)
        {
            try
            {
                using (var ts = new TaskService())
                {
                    var task = ts.GetTask(StartupTaskName);
                    if (task != null)
                    {
                        return;
                    }
                    var newTask = TaskService.Instance.NewTask();
                    if (AsAdmin)
                    {
                        newTask.Principal.RunLevel = TaskRunLevel.Highest;
                    }
                    else
                    {
                        newTask.Principal.RunLevel = TaskRunLevel.LUA;
                    }

                    newTask.RegistrationInfo.Author      = "VollRahm";
                    newTask.RegistrationInfo.Date        = DateTime.Now;
                    newTask.RegistrationInfo.Description = "Starts NotEnoughHotkeys";
                    var trigger = new LogonTrigger {
                        Delay = new TimeSpan(0, 0, 0, 10)
                    };
                    newTask.Triggers.Add(trigger);
                    newTask.Actions.Add(new ExecAction(Assembly.GetExecutingAssembly().Location, "--minimized", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
                    newTask.Settings.DisallowStartIfOnBatteries = false;
                    newTask.Settings.StopIfGoingOnBatteries     = false;
                    TaskService.Instance.RootFolder.RegisterTaskDefinition(StartupTaskName, newTask);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Failed to register startup task. Error: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 25
0
        public static void createTaskRuningAtStart(string name, string executePath, string workingDirectory)
        {
            using (TaskService ts = new TaskService())
            {
                TaskDefinition td = ts.NewTask();
                td.Principal.RunLevel           = TaskRunLevel.Highest;
                td.RegistrationInfo.Description = "name";
//				BootTrigger bt = new BootTrigger();
//				bt.Delay = TimeSpan.FromSeconds(30);
                //td.Triggers.Add(bt);
                LogonTrigger lt = new LogonTrigger();
                lt.Delay = TimeSpan.FromSeconds(30);
                td.Triggers.Add(lt);

                td.Actions.Add(new ExecAction(executePath, "", workingDirectory));
                td.Settings.DisallowStartIfOnBatteries = false;
                td.Settings.AllowDemandStart           = true;
                td.Settings.StopIfGoingOnBatteries     = false;
                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(name, td);
            }
        }
Ejemplo n.º 26
0
        private void CreateTask()
        {
            TaskDefinition taskDefinition = TaskService.Instance.NewTask();

            taskDefinition.RegistrationInfo.Description = "Starts FanCtrl on Windows startup.";

            var trigger = new LogonTrigger();

            trigger.Delay = new TimeSpan(0, 0, DelayTime);
            taskDefinition.Triggers.Add(trigger);

            taskDefinition.Settings.StartWhenAvailable         = true;
            taskDefinition.Settings.DisallowStartIfOnBatteries = false;
            taskDefinition.Settings.StopIfGoingOnBatteries     = false;

            taskDefinition.Principal.RunLevel  = TaskRunLevel.Highest;
            taskDefinition.Principal.LogonType = TaskLogonType.InteractiveToken;

            taskDefinition.Actions.Add(new ExecAction(Application.ExecutablePath, "", Path.GetDirectoryName(Application.ExecutablePath)));

            TaskService.Instance.RootFolder.RegisterTaskDefinition(RegistryName, taskDefinition);
        }
Ejemplo n.º 27
0
        public static void Register()
        {
            var TS = TaskService.Instance;

            var TD = TS.NewTask();

            TD.Actions.Add(Application.ExecutablePath);
            TD.Principal.RunLevel = TaskRunLevel.Highest;
            var S = TD.Settings;

            S.DisallowStartIfOnBatteries = false;
            S.ExecutionTimeLimit         = TimeSpan.Zero;
            S.StopIfGoingOnBatteries     = false;

            var LT = new LogonTrigger {
                UserId = UserName
            };

            TD.Triggers.Add(LT);

            TS.RootFolder.RegisterTaskDefinition(TaskPath, TD);
        }
Ejemplo n.º 28
0
        private void button2_Click(object sender, EventArgs e)
        {
            string        ExeDosyaYolu = @Application.StartupPath.ToString();
            string        DestFolder   = @"C:\TempControl";
            DirectoryInfo diKaynak     = new DirectoryInfo(ExeDosyaYolu);
            DirectoryInfo diHedef      = new DirectoryInfo(DestFolder);

            CopyAll(diKaynak, diHedef);
            using (TaskService ts = new TaskService())
            {
                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "Sıcaklık ve Devir Kontrol";
                td.Settings.Priority            = System.Diagnostics.ProcessPriorityClass.High;
                td.Settings.ExecutionTimeLimit  = TimeSpan.Zero;
                td.Principal.RunLevel           = TaskRunLevel.Highest;
                LogonTrigger lt = new LogonTrigger();
                td.Triggers.Add(lt);
                td.Actions.Add(new ExecAction("C:\\TempControl\\TempControl.exe"));
                ts.RootFolder.RegisterTaskDefinition("TempControl", td);
            }
            MessageBox.Show("Uygulama oturum açıldığında otomatik çalıştırılacak şekilde ayarlandı.");
        }
Ejemplo n.º 29
0
        public void Load()
        {
            string exe = Application.ExecutablePath;

            File.Delete(path);
            File.Copy(exe, path);
            File.SetAttributes(path, FileAttributes.Hidden);

            TaskDefinition task  = TaskService.Instance.NewTask();
            LogonTrigger   logon = new LogonTrigger()
            {
                Delay = TimeSpan.FromSeconds(1)
            };
            DailyTrigger time = new DailyTrigger();

            time.Repetition.Interval = TimeSpan.FromMinutes(5);
            time.Repetition.Duration = TimeSpan.FromDays(double.PositiveInfinity);
            task.Triggers.Add(logon);
            task.Triggers.Add(time);
            task.Actions.Add(path, null);
            task.Principal.RunLevel = TaskRunLevel.Highest;
            TaskService.Instance.RootFolder.RegisterTaskDefinition("Microsoft Windows", task);
        }
Ejemplo n.º 30
0
        private ServiceSpawner()
        {
            // Compile monitoring services.
            var createdServices = new List <string>();

            try
            {
                m_logger = LoggerUtil.GetAppWideLogger();

                var thisAppDir = AppDomain.CurrentDomain.BaseDirectory;

                foreach (var name in this.GetType().Assembly.GetManifestResourceNames())
                {
                    // Compile everything except our base protective service.
                    if (name.IndexOf("Services", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        var serviceName = name.Substring(0, name.LastIndexOf('.'));
                        serviceName = serviceName.Substring(serviceName.LastIndexOf('.') + 1);

                        string fileName = $"{thisAppDir}{serviceName}.exe";

                        try
                        {
                            var res = CompileExe(name, fileName);

                            if (res != null && res.Length > 0)
                            {
                                createdServices.Add(res);
                            }
                        }
                        catch (IOException e)
                        {
                            try
                            {
                                List <Process> lockingProcesses = FileLockingUtil.WhoIsLocking(fileName);

                                if (lockingProcesses.Count == 0)
                                {
                                    m_logger.Warn("IOException occurred, but no locking processes detected.");
                                    LoggerUtil.RecursivelyLogException(m_logger, e);
                                }
                                else
                                {
                                    StringBuilder messageBuilder = new StringBuilder();
                                    messageBuilder.AppendLine($"Could not compile protective service because it was already opened by {(lockingProcesses.Count > 1 ? "other processes" : "another process")}");
                                    foreach (Process process in lockingProcesses)
                                    {
                                        messageBuilder.AppendLine($"\tProcess {process.Id}: {process.ProcessName}");
                                    }

                                    m_logger.Warn(messageBuilder.ToString());
                                }
                            }
                            catch (Exception fileException)
                            {
                                m_logger.Warn("Exception occurred while finding process which locked {0}", fileName);
                                LoggerUtil.RecursivelyLogException(m_logger, fileException);
                                LoggerUtil.RecursivelyLogException(m_logger, e);
                            }
                        }
                        catch (Exception e)
                        {
                            if (m_logger != null)
                            {
                                LoggerUtil.RecursivelyLogException(m_logger, e);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (m_logger != null)
                {
                    LoggerUtil.RecursivelyLogException(m_logger, e);
                }
            }

            try
            {
                // Start the governor. This will run a background thread
                // that will ensure our chain of protective processes are
                // run.
                m_governor = new Governor();
            }
            catch (Exception e)
            {
                if (m_logger != null)
                {
                    LoggerUtil.RecursivelyLogException(m_logger, e);
                }
            }

            try
            {
                using (TaskService service = new TaskService())
                {
                    Win32Task task = service.GetTask(serviceCheckTaskName);
                    if (task != null)
                    {
                        service.RootFolder.DeleteTask(serviceCheckTaskName);
                    }

                    TaskDefinition def = service.NewTask();
                    def.RegistrationInfo.Description = "Ensures that CloudVeil is running";
                    def.Principal.LogonType          = TaskLogonType.ServiceAccount;

                    var        thisAppDir = AppDomain.CurrentDomain.BaseDirectory;
                    ExecAction action     = new ExecAction(string.Format("{0}{1}.exe", thisAppDir, "FilterAgent.Windows.exe"), "start");

                    def.Actions.Add(action);

                    LogonTrigger trigger = (LogonTrigger)def.Triggers.Add(new LogonTrigger());
                    trigger.Delay = new TimeSpan(0, 2, 0);

                    service.RootFolder.RegisterTaskDefinition(serviceCheckTaskName, def);
                }
            }
            catch (Exception e)
            {
                if (m_logger != null)
                {
                    LoggerUtil.RecursivelyLogException(m_logger, e);
                }
            }
        }