public static void ScheduleSmartMonkey(string dirPath)
        {
            using (var ts = new TS.TaskService())
            {
                string taskName  = @"Run SmartMonkey";
                string exePath   = Path.Combine(dirPath, "SmartMonkey.exe");
                string arguments = string.Empty;

                try
                {
                    ts.RootFolder.DeleteTask(taskName);
                }
                catch
                { }

                var td = ts.NewTask();
                td.RegistrationInfo.Description = taskName;

                var trigger = new TS.TimeTrigger();
                trigger.SetRepetition(new TimeSpan(2, 0, 0), TimeSpan.Zero);
                td.Triggers.Add(trigger);

                td.Actions.Add(new TS.ExecAction("cmd.exe", "/c \"start " + exePath + "\" " + arguments, null));

                ts.RootFolder.RegisterTaskDefinition(taskName, td);
            }
        }
Beispiel #2
0
 public void TestTimeSelect()
 {
     var span1 = new TimeTrigger { StartBoundary = DateTime.Parse("12/7/2014 6:00 PM") };
     var r = span1.SelectDates(x => x).Take(5).ToArray();
     Debug.Assert(r.Length == 1);
     Debug.Assert(r[0].Date == DateTime.Today);
     Debug.Assert(r[0].TimeOfDay == new TimeSpan(18, 0, 0));
     // repeat interval
     span1.Repetition.Interval = new TimeSpan(1, 0, 0);
     span1.Repetition.Duration = new TimeSpan(3, 0, 0);
     r = span1.SelectDates(x => x).Take(5).ToArray();
     Debug.Assert(r.Length == 3);
     Debug.Assert(r[0].Date == DateTime.Today);
     Debug.Assert(r[0].TimeOfDay == new TimeSpan(18, 0, 0));
     Debug.Assert(r[1].Date == DateTime.Today);
     Debug.Assert(r[1].TimeOfDay == new TimeSpan(19, 0, 0));
     Debug.Assert(r[2].TimeOfDay == new TimeSpan(20, 0, 0));
     // end boundry
     span1.EndBoundary = DateTime.Today.AddHours(19);
     r = span1.SelectDates(x => x).Take(5).ToArray();
     Debug.Assert(r.Length == 2);
     Debug.Assert(r[0].Date == DateTime.Today);
     Debug.Assert(r[0].TimeOfDay == new TimeSpan(18, 0, 0));
     Debug.Assert(r[1].Date == DateTime.Today);
     Debug.Assert(r[1].TimeOfDay == new TimeSpan(19, 0, 0));
 }
        private void btnInput_Click(object sender, EventArgs e)
        {
            string strTaskID = "";
            string appPath = System.Configuration.ConfigurationManager.AppSettings["AutoGetOdds"];
            Application.DoEvents();
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                // Get the service on the local machine
                TaskService ts = new TaskService();
                // Delete Schedules
                DataTable dt = oddBO.GetSchedules(1);
                foreach (DataRow dr in dt.Rows)
                {
                    strTaskID = dr["TaskID"].ToString();
                    if (ts.FindTask(strTaskID, true) != null)
                    {
                        // Remove the task we just created
                        ts.RootFolder.DeleteTask(strTaskID);
                    }
                    // Delete schedules follow taskid
                    oddBO.DeleleSchedules(strTaskID);
                }
                DateTime currDate = dtpDate.Value;
                // Create Schedules
                dt = oddBO.GetSchedules(0, currDate);
                foreach (DataRow dr in dt.Rows)
                {
                    strTaskID = dr["TaskID"].ToString();
                    // Create a new task definition and assign properties
                    TaskDefinition td = ts.NewTask();

                    Trigger t = new TimeTrigger();
                    t.StartBoundary = Convert.ToDateTime(dr["RunTime"].ToString());

                    td.RegistrationInfo.Description = "Get odd at " + dr["RunTime"].ToString();

                    // Create a trigger that will fire the task at this time every other day
                    td.Triggers.Add(t);

                    // Create an action that will launch Notepad whenever the trigger fires
                    td.Actions.Add(new ExecAction(appPath, "\"" + strTaskID + "\"", null));

                    // Register the task in the root folder
                    ts.RootFolder.RegisterTaskDefinition(strTaskID, td);
                }
                MessageBox.Show("Schedules have inputed successfully!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor.Current = Cursors.WaitCursor;
            }
        }
        public static void ScheduleSmartMonkey(string dirPath)
        {
            using (var ts = new TS.TaskService())
            {
                string taskName = @"Run SmartMonkey";
                string exePath = Path.Combine(dirPath, "SmartMonkey.exe");
                string arguments = string.Empty;

                try
                {
                    ts.RootFolder.DeleteTask(taskName);
                }
                catch
                { }

                var td = ts.NewTask();
                td.RegistrationInfo.Description = taskName;

                var trigger = new TS.TimeTrigger();
                trigger.SetRepetition(new TimeSpan(2, 0, 0), TimeSpan.Zero);
                td.Triggers.Add(trigger);

                td.Actions.Add(new TS.ExecAction("cmd.exe", "/c \"start " + exePath + "\" " + arguments, null));

                ts.RootFolder.RegisterTaskDefinition(taskName, td);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Begins a new slideshow, cancelling any active ones and setting the initial
        /// background.
        /// </summary>
        /// <param name="path">The path to the background directory.</param>
        /// <param name="position">The position with which the background will be displayed.</param>
        /// <param name="interval">The interval before which the next background will be set.</param>
        /// <param name="index">The file index within the directory at which to begin.</param>
        public static void BeginSlideshow(string path, PicturePosition position, 
            int interval, int index)
        {
            if (interval < 0) throw new ArgumentOutOfRangeException("showInterval");
            if (index < 0)    throw new ArgumentOutOfRangeException("showIndex");

            // Get the absolute path to the directory
            path = Path.GetFullPath(path);

            // Get the current images in the given directory
            string[] images = GetBackgroundsInFolder(path);

            // Wrap index
            if (index >= images.Length) index = 0;

            // Clamp interval
            interval = Math.Min(interval, 44640);

            // Save registry values
            using (var key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true))
            {
                key.SetValue("WWU CurrentIndex",    index);
                key.SetValue("WWU CurrentInterval", interval);
                key.SetValue("WWU CurrentDir",      path);
            }

            // Remove any current slideshows
            CancelSlideshow();

            // Schedule slideshow
            using (TaskService service = new TaskService())
            {
                // Create new task
                TaskDefinition task = service.NewTask();

                // Create time trigger
                var trigger = new TimeTrigger();
                trigger.SetRepetition(TimeSpan.FromMinutes(interval), TimeSpan.Zero);

                task.Triggers.Add(trigger);
                task.Settings.StartWhenAvailable = true;
                task.Settings.WakeToRun          = false;

                // Add re-execution to set next background
                task.Actions.Add(new ExecAction(GetWallpaperwExe() + " /next"));

                // Register task
                service.RootFolder.RegisterTaskDefinition("wwu_slideshow", task);
            }

            // Now actually set the first wallpaper

            // Set blank if no images in folder
            if (images.Length == 0) {
                WallpaperInterop.SetWallpaper("", PicturePosition.Center, false);
            }
            // Otherwise set background to the next image
            else {
                WallpaperInterop.SetWallpaper(images[index], position, false);
            }
        }
Beispiel #6
0
        void SaveSettings(object o)
        {
            ErrorMessage = string.Empty;

            try
            {
                Trace.TraceInformation("Saving settings...");
                Settings.Default.Save();
                PendingChanges = false;
                Trace.TraceInformation("Settings saved successfully.");
            }
            catch (Exception ex)
            {
                ErrorMessage = "Couldn't save settings: " + ex.Message;
                return;
            }

            try
            {
                Trace.TraceInformation("Updating schedule settings...");

                const string taskPath = "IPFilter";

                // Get the service on the local machine
                using (var service = new TaskService())
                {
                    if (!IsScheduleEnabled)
                    {
                        // If we're disabling the scheduling, then delete the task if it exists.
                        Trace.TraceInformation("Schedule is disabled. Removing any existing scheduled task.");
                        service.RootFolder.DeleteTask(taskPath, false);
                        Trace.TraceInformation("Finished updating schedule settings.");
                        return;
                    }

                    var identity = WindowsIdentity.GetCurrent();
                    if (identity == null)
                    {
                        Trace.TraceWarning("Couldn't get the user identity; can't schedule task.");
                        return;
                    }

                    Trace.TraceInformation("Setting up the automatic schedule...");
                    using (var task = service.NewTask())
                    {
                        task.RegistrationInfo.Description = "Updates the IP Filter for bit torrent clients";

                        task.Triggers.Clear();

                        // Schedule for midnight, then check every x hours (6 by default).
                        var trigger = new TimeTrigger(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0));
                        trigger.Repetition.Interval = TimeSpan.FromHours(ScheduleHours ?? 6);
                        task.Triggers.Add(trigger);

                        task.Actions.Add(new ExecAction(Process.GetCurrentProcess().MainModule.FileName, "/silent"));

                        task.Settings.RunOnlyIfNetworkAvailable = true;
                        task.Settings.StartWhenAvailable = true;
                        task.Settings.WakeToRun = false;
                        task.Principal.RunLevel = TaskRunLevel.Highest;
                        //task.Principal.UserId = identity.Name;

                        service.RootFolder.RegisterTaskDefinition(taskPath, task, TaskCreation.CreateOrUpdate, identity.Name);
                    }

                    Trace.TraceInformation("Finished scheduling automatic update.");
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Couldn't schedule automated update: " + ex);
                ErrorMessage = "Couldn't schedule automated update: " + ex.Message;
            }
        }
        /// <summary>
        /// Saves all the settings setted in the UI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnOK_Click(object sender, EventArgs e)
        {
            bool isNewTask = true;
            try
            {
                TaskService service = new TaskService();
                TaskDefinition td = service.NewTask();
                TriggerCollection trgCollection;
                DateTime oldTriggerDate = new DateTime();

                Task task = service.FindTask("PCCleaner1ClickMaint");

                if (task != null)
                {
                    isNewTask = false;
                    oldTriggerDate = task.Definition.Triggers.Count > 0
                                        ? task.Definition.Triggers[0].StartBoundary.Date
                                        : DateTime.Today;
                    task.Definition.Triggers.Clear();
                    trgCollection = task.Definition.Triggers;
                }
                else
                {
                    td.RegistrationInfo.Description = "PCCleaner 1 ClickMaint";
                    td.Settings.Enabled = true;
                    td.Actions.Add(new ExecAction(Environment.CurrentDirectory + "\\1Click.exe", System.Diagnostics.Process.GetCurrentProcess().ProcessName, Environment.CurrentDirectory));
                    trgCollection = td.Triggers;
                }

                if (cmbSelectSchedule.SelectedIndex == (int)Schedule.Daily)
                {
                    DailyTrigger dTrigger = new DailyTrigger { DaysInterval = (short)nudDays.Value };

                    if (isNewTask)
                        dTrigger.StartBoundary = DateTime.Today.Date + timePicker.Value.TimeOfDay;
                    else
                        dTrigger.StartBoundary = oldTriggerDate + timePicker.Value.TimeOfDay;

                    trgCollection.Add(dTrigger);
                }
                else if (cmbSelectSchedule.SelectedIndex == (int)Schedule.Weekly)
                {
                    WeeklyTrigger wTrigger = new WeeklyTrigger();

                    if (!chkMon.Checked && !chkTue.Checked && !chkWed.Checked && !chkThu.Checked && !chkFri.Checked && !chkSat.Checked &&
                        !chkSun.Checked)
                    {
                        MessageBox.Show(WPFLocalizeExtensionHelpers.GetUIString("select_day"), System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    if (chkMon.Checked && chkTue.Checked && chkWed.Checked && chkThu.Checked && chkFri.Checked && chkSat.Checked &&
                        chkSun.Checked)
                    {
                        wTrigger.DaysOfWeek = DaysOfTheWeek.AllDays;
                        trgCollection.Add(wTrigger);
                        cmbSelectSchedule.SelectedIndex = (int)Schedule.Daily;
                    }
                    else
                    {
                        if (chkMon.Checked)
                        {
                            wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Monday };
                            trgCollection.Add(wTrigger);
                        }
                        if (chkTue.Checked)
                        {
                            wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Tuesday };
                            trgCollection.Add(wTrigger);
                        }
                        if (chkWed.Checked)
                        {
                            wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Wednesday };
                            trgCollection.Add(wTrigger);
                        }
                        if (chkThu.Checked)
                        {
                            wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Thursday };
                            trgCollection.Add(wTrigger);
                        }
                        if (chkFri.Checked)
                        {
                            wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Friday };
                            trgCollection.Add(wTrigger);
                        }
                        if (chkSat.Checked)
                        {
                            wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Saturday };
                            trgCollection.Add(wTrigger);
                        }
                        if (chkSun.Checked)
                        {
                            wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Sunday };
                            trgCollection.Add(wTrigger);
                        }
                    }

                    foreach (WeeklyTrigger trg in trgCollection)
                    {
                        if (isNewTask)
                            trg.StartBoundary = DateTime.Today.Date + timePicker.Value.TimeOfDay;
                        else
                            trg.StartBoundary = oldTriggerDate + timePicker.Value.TimeOfDay;

                        trg.WeeksInterval = (short)nudWeeks.Value;
                    }
                }
                else if (cmbSelectSchedule.SelectedIndex == (int)Schedule.Monthly)
                {
                    if (radDay.Checked)
                    {
                        MonthlyTrigger mTrigger = new MonthlyTrigger();

                        if (isNewTask)
                            mTrigger.StartBoundary = DateTime.Today.Date + timePicker.Value.TimeOfDay;
                        else
                            mTrigger.StartBoundary = oldTriggerDate + timePicker.Value.TimeOfDay;

                        mTrigger.MonthsOfYear = MonthsOfTheYear.AllMonths;
                        mTrigger.DaysOfMonth = new[] { (int)nudDayMonth.Value };

                        trgCollection.Add(mTrigger);
                    }
                    else if (radMonth.Checked)
                    {
                        MonthlyDOWTrigger mdTrigger = new MonthlyDOWTrigger();

                        if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("MondayFull"))
                        {
                            mdTrigger.DaysOfWeek = DaysOfTheWeek.Monday;
                        }
                        else if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("TuesdayFull"))
                        {
                            mdTrigger.DaysOfWeek = DaysOfTheWeek.Tuesday;
                        }
                        else if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("WednesdayFull"))
                        {
                            mdTrigger.DaysOfWeek = DaysOfTheWeek.Wednesday;
                        }
                        else if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("ThursdayFull"))
                        {
                            mdTrigger.DaysOfWeek = DaysOfTheWeek.Thursday;
                        }
                        else if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("FridayFull"))
                        {
                            mdTrigger.DaysOfWeek = DaysOfTheWeek.Friday;
                        }
                        else if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("SaturdayFull"))
                        {
                            mdTrigger.DaysOfWeek = DaysOfTheWeek.Saturday;
                        }
                        else if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("SundayFull"))
                        {
                            mdTrigger.DaysOfWeek = DaysOfTheWeek.Sunday;
                        }

                        if (cmbweek.SelectedIndex == 0)
                        {
                            mdTrigger.WeeksOfMonth = WhichWeek.FirstWeek;
                        }
                        else if (cmbweek.SelectedIndex == 1)
                        {
                            mdTrigger.WeeksOfMonth = WhichWeek.SecondWeek;
                        }
                        else if (cmbweek.SelectedIndex == 2)
                        {
                            mdTrigger.WeeksOfMonth = WhichWeek.ThirdWeek;
                        }
                        else if (cmbweek.SelectedIndex == 3)
                        {
                            mdTrigger.WeeksOfMonth = WhichWeek.FourthWeek;
                        }
                        else if (cmbweek.SelectedIndex == 4)
                        {
                            mdTrigger.WeeksOfMonth = WhichWeek.LastWeek;
                        }

                        mdTrigger.MonthsOfYear = MonthsOfTheYear.AllMonths;
                        mdTrigger.StartBoundary = DateTime.Today.Date + timePicker.Value.TimeOfDay;

                        trgCollection.Add(mdTrigger);
                    }
                }
                else if (cmbSelectSchedule.SelectedIndex == (int)Schedule.Once)
                {
                    TimeTrigger tTrigger = new TimeTrigger { StartBoundary = timePickerOnce.Value.Date + timePicker.Value.TimeOfDay };
                    trgCollection.Add(tTrigger);
                }
                else if (cmbSelectSchedule.SelectedIndex == (int)Schedule.AtSystemStartUp)
                {
                    BootTrigger bTrigger = new BootTrigger { Delay = TimeSpan.FromMinutes(2) };
                    trgCollection.Add(bTrigger);
                }
                else if (cmbSelectSchedule.SelectedIndex == (int)Schedule.AtLogon)
                {
                    LogonTrigger lTrigger = new LogonTrigger { Delay = TimeSpan.FromSeconds(1) };
                    trgCollection.Add(lTrigger);
                }
                else if (cmbSelectSchedule.SelectedIndex == (int)Schedule.WhenIdel)
                {
                    IdleTrigger iTrigger = new IdleTrigger();
                    if (isNewTask)
                        iTrigger.StartBoundary = DateTime.Today.Date + TimeSpan.FromMinutes((double)nudMinutes.Value);
                    else
                        iTrigger.StartBoundary = oldTriggerDate + TimeSpan.FromMinutes((double)nudMinutes.Value);

                    trgCollection.Add(iTrigger);
                }

                // Register the task in the root folder
                if (isNewTask)
                    service.RootFolder.RegisterTaskDefinition(@"PCCleaner1ClickMaint", td);
                else
                    task.RegisterChanges();

                ((OneClickAppsViewModel)Application.Current.MainWindow.DataContext).SchedulerText = lblSchedule.Text;

                Close();
            }
            catch
            {
            }
        }
 public Dev2TimeTrigger(ITaskServiceConvertorFactory _taskServiceConvertorFactory, TimeTrigger instance)
     : base(_taskServiceConvertorFactory, instance)
 {
 }
Beispiel #9
0
 public void TestTriggerCollectionSelect()
 {
     var a = new TimeTrigger { StartBoundary = DateTime.Parse("12/7/2014 6:00 PM") };
     a.Repetition.Interval = new TimeSpan(1, 0, 0);
     a.Repetition.Duration = new TimeSpan(3, 0, 0);
     var b = new TimeTrigger { StartBoundary = DateTime.Parse("12/7/2014 6:00 PM") };
     b.Repetition.Interval = new TimeSpan(0, 1, 0);
     b.Repetition.Duration = new TimeSpan(3, 0, 0);
     var span1 = new[] { a, b };
     var r = span1.SelectDates(x => x).Take(6).ToArray();
     Debug.Assert(r.Length == 6);
     //Debug.Assert(r[0].Date.Month == 2);
     //Debug.Assert(r[0].TimeOfDay == new TimeSpan(18, 0, 0));
     //Debug.Assert(r[1].Date == r[0].Date);
     //Debug.Assert(r[1].TimeOfDay == new TimeSpan(19, 0, 0));
     //Debug.Assert(r[2].Date == r[1].Date);
     //Debug.Assert(r[2].TimeOfDay == new TimeSpan(20, 0, 0));
     //Debug.Assert(r[3].Date == r[2].Date.AddYears(1));
     //Debug.Assert(r[3].TimeOfDay == new TimeSpan(18, 0, 0));
     //Debug.Assert(r[4].Date == r[3].Date);
     //Debug.Assert(r[4].TimeOfDay == new TimeSpan(19, 0, 0));
     //Debug.Assert(r[5].Date == r[4].Date);
     //Debug.Assert(r[5].TimeOfDay == new TimeSpan(20, 0, 0));
 }
		private void schedOneRadio_CheckedChanged(object sender, EventArgs e)
		{
			if (((RadioButton)sender).Checked)
			{
				Trigger newTrigger = null;
				if (sender == schedOneRadio)
				{
					schedTabControl.SelectedTab = oneTimeTab;
					if (!onAssignment) newTrigger = new TimeTrigger();
				}
				else if (sender == schedDailyRadio)
				{
					schedTabControl.SelectedTab = dailyTab;
					if (!onAssignment) newTrigger = new DailyTrigger();
				}
				else if (sender == schedWeeklyRadio)
				{
					schedTabControl.SelectedTab = weeklyTab;
					if (!onAssignment) newTrigger = new WeeklyTrigger();
				}
				else if (sender == schedMonthlyRadio)
				{
					schedTabControl.SelectedTab = monthlyTab;
					monthlyTriggerUI1_TriggerTypeChanged(this, EventArgs.Empty);
				}

				if (newTrigger != null && !onAssignment)
				{
					if (trigger != null)
						newTrigger.CopyProperties(trigger);
					this.Trigger = newTrigger;
				}
			}
		}
Beispiel #11
0
        public void makeSchedules(DateTime currDate)
        {
            string strTaskID = "";
            string appPath = System.Configuration.ConfigurationManager.AppSettings["AutoGetOddsMovements"];

            try
            {
                // Get the service on the local machine
                TaskService ts = new TaskService();
                // Delete Schedules
                DataTable dt = this.GetSchedules(1);
                foreach (DataRow dr in dt.Rows)
                {
                    strTaskID = dr["TaskID"].ToString();
                    if (ts.FindTask(strTaskID, true) != null)
                    {
                        // Remove the task we just created
                        ts.RootFolder.DeleteTask(strTaskID);
                    }
                    // Delete schedules follow taskid
                    this.DeleleSchedules(strTaskID);
                }
                // Create Schedules
                dt = this.GetSchedules(0, currDate);
                foreach (DataRow dr in dt.Rows)
                {
                    strTaskID = dr["TaskID"].ToString();
                    // Create a new task definition and assign properties
                    TaskDefinition td = ts.NewTask();

                    Trigger t = new TimeTrigger();
                    t.StartBoundary = Convert.ToDateTime(dr["RunTime"].ToString());

                    td.RegistrationInfo.Description = "Get odd at " + dr["RunTime"].ToString();

                    // Create a trigger that will fire the task at this time every other day
                    td.Triggers.Add(t);

                    // Create an action that will launch Notepad whenever the trigger fires
                    td.Actions.Add(new ExecAction(appPath, "\"" + strTaskID + "\"", null));

                    //// Run app even user not log on
                    //td.Settings.RunOnlyIfLoggedOn = false;

                    // Register the task in the root folder
                    ts.RootFolder.RegisterTaskDefinition(strTaskID, td);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #12
0
 internal static Trigger CreateTrigger(V1Interop.ITaskTrigger trigger, V1Interop.TaskTriggerType triggerType)
 {
     Trigger t = null;
     switch (triggerType)
     {
         case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.RunOnce:
             t = new TimeTrigger(trigger);
             break;
         case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.RunDaily:
             t = new DailyTrigger(trigger);
             break;
         case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.RunWeekly:
             t = new WeeklyTrigger(trigger);
             break;
         case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.RunMonthly:
             t = new MonthlyTrigger(trigger);
             break;
         case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.RunMonthlyDOW:
             t = new MonthlyDOWTrigger(trigger);
             break;
         case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.OnIdle:
             t = new IdleTrigger(trigger);
             break;
         case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.OnSystemStart:
             t = new BootTrigger(trigger);
             break;
         case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.OnLogon:
             t = new LogonTrigger(trigger);
             break;
         default:
             break;
     }
     //if (t != null) t.ttype = triggerType;
     return t;
 }
Beispiel #13
0
        public void makeSchedules(string strTaskID, DateTime RunTime)
        {
            string appPath = System.Configuration.ConfigurationManager.AppSettings["AutoGetOdds"];

            try
            {
                // Get the service on the local machine
                TaskService ts = new TaskService();
                // Create a new task definition and assign properties
                TaskDefinition td = ts.NewTask();
                Trigger t = new TimeTrigger();
                t.StartBoundary = RunTime;
                td.RegistrationInfo.Description = "Get odd at " + RunTime;
                // Create a trigger that will fire the task at this time every other day
                td.Triggers.Add(t);
                // Create an action that will launch Notepad whenever the trigger fires
                td.Actions.Add(new ExecAction(appPath, "\"" + strTaskID + "\"", null));
                //// Run app even user not log on
                //td.Settings.RunOnlyIfLoggedOn = false;
                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(strTaskID, td);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private static bool SaveTask(string pathToOutputFolder,
                                     string pathToLogFile,
                                     string description,
                                     bool shutdownAfterBackup,
                                     DateTime startTask,
                                     int intervalCout,
                                     string scheduleType,
                                     bool repeatTask,
                                     string fullUserName,
                                     string password,
                                     bool usePermission,
                                     bool addingTimestampToPst,
                                     bool copyMSOutlookRegistrySettings)
        {
            bool result = false;

            string pathToProgram = ConfigurationManager.AppSettings["pathToBackupmsoutlook"];

            if (pathToProgram == "Path.GetDirectoryName(Application.ExecutablePath)")
            {
                pathToProgram = Path.GetDirectoryName(Application.ExecutablePath) + "\\backupmsoutlook.exe";
            }
            else
            {
                pathToProgram = ConfigurationManager.AppSettings["pathToBackupmsoutlook"];
            }
            try
            {
                using (TaskService ts = new TaskService())
                {
                    TaskDefinition td = ts.NewTask();
                    td.RegistrationInfo.Description = description;

                    //permission
                    td.Principal.LogonType = TaskLogonType.InteractiveToken;
                    td.Principal.RunLevel  = TaskRunLevel.Highest;
                    td.Principal.UserId    = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

                    //add action
                    td.Actions.Add(new ExecAction(pathToProgram,
                                                  "\"" + pathToOutputFolder + "\"" + " " +
                                                  "\"" + pathToLogFile + "\"" + " " +
                                                  shutdownAfterBackup + " " +
                                                  addingTimestampToPst + " " +
                                                  copyMSOutlookRegistrySettings,
                                                  null));

                    if (repeatTask)
                    {
                        if (scheduleType == "hour(s)")
                        {
                            using (var tt = new Microsoft.Win32.TaskScheduler.TimeTrigger()
                            {
                                StartBoundary = startTask, Enabled = true
                            })
                            {
                                tt.Repetition.Interval = TimeSpan.FromHours(1);
                                td.Triggers.Add(tt);
                            }
                        }
                        else
                        if (scheduleType == "day(s)")
                        {
                            using (Microsoft.Win32.TaskScheduler.DailyTrigger dt = new Microsoft.Win32.TaskScheduler.DailyTrigger()
                            {
                                StartBoundary = startTask, Enabled = true, DaysInterval = (short)intervalCout
                            })
                            {
                                td.Triggers.Add(dt);
                            }
                        }
                        else
                        if (scheduleType == "week(s)")
                        {
                            using (var wt = new Microsoft.Win32.TaskScheduler.WeeklyTrigger()
                            {
                                StartBoundary = startTask, Enabled = true, WeeksInterval = (short)intervalCout
                            })
                            {
                                td.Triggers.Add(wt);
                            }
                        }
                    }
                    else
                    {
                        var tt = new Microsoft.Win32.TaskScheduler.TimeTrigger()
                        {
                            StartBoundary = startTask,
                            EndBoundary   = startTask.AddHours(12), //12 hours limit execution
                            Enabled       = true
                        };
                        td.Triggers.Add(tt);
                    }

                    //settings
                    td.Settings.Hidden                     = true;
                    td.Settings.MultipleInstances          = Microsoft.Win32.TaskScheduler.TaskInstancesPolicy.IgnoreNew;
                    td.Settings.DisallowStartIfOnBatteries = true;
                    td.Settings.StopIfGoingOnBatteries     = true;
                    td.Settings.AllowHardTerminate         = true;
                    td.Settings.StartWhenAvailable         = false;
                    td.Settings.RunOnlyIfNetworkAvailable  = false;
                    td.Settings.Priority                   = System.Diagnostics.ProcessPriorityClass.High;
                    td.Settings.IdleSettings.StopOnIdleEnd = true;
                    td.Settings.IdleSettings.RestartOnIdle = false;
                    td.Settings.AllowDemandStart           = true;
                    td.Settings.Enabled                    = true;
                    td.Settings.RunOnlyIfIdle              = false;
                    td.Settings.WakeToRun                  = false;
                    td.RegistrationInfo.Date               = DateTime.Now;
                    td.Settings.ExecutionTimeLimit         = new TimeSpan(12, 0, 0);      //12 hours limit execution
                    td.Settings.DeleteExpiredTaskAfter     = new TimeSpan(30 * 24, 0, 0); //delete task
                    //from scheduler
                    //after 30 days

                    //author
                    td.RegistrationInfo.Author = td.Principal.UserId;

                    //register task
                    string taskName = Get_NextTaskName();

                    if (usePermission)
                    {
                        td.Principal.LogonType = Microsoft.Win32.TaskScheduler.TaskLogonType.Password;
                        ts.RootFolder.RegisterTaskDefinition(taskName,
                                                             td,
                                                             Microsoft.Win32.TaskScheduler.TaskCreation.CreateOrUpdate,
                                                             fullUserName,
                                                             password,
                                                             Microsoft.Win32.TaskScheduler.TaskLogonType.Password,
                                                             null);
                    }
                    else
                    {
                        ts.RootFolder.RegisterTaskDefinition(taskName, td);
                    }
                }

                result = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Adding task error -> " + ex.Message);
            }

            return(result);
        }