Example #1
0
        private void AddTaskOptions(ITaskDefinition iTaskDefinition, ScheduledJobOptions jobOptions)
        {
            _TASK_RUNLEVEL variable;

            iTaskDefinition.Settings.DisallowStartIfOnBatteries = !jobOptions.StartIfOnBatteries;
            iTaskDefinition.Settings.StopIfGoingOnBatteries     = jobOptions.StopIfGoingOnBatteries;
            iTaskDefinition.Settings.WakeToRun     = jobOptions.WakeToRun;
            iTaskDefinition.Settings.RunOnlyIfIdle = !jobOptions.StartIfNotIdle;
            iTaskDefinition.Settings.IdleSettings.StopOnIdleEnd = jobOptions.StopIfGoingOffIdle;
            iTaskDefinition.Settings.IdleSettings.RestartOnIdle = jobOptions.RestartOnIdleResume;
            iTaskDefinition.Settings.IdleSettings.IdleDuration  = ScheduledJobWTS.ConvertTimeSpanToWTSString(jobOptions.IdleDuration);
            iTaskDefinition.Settings.IdleSettings.WaitTimeout   = ScheduledJobWTS.ConvertTimeSpanToWTSString(jobOptions.IdleTimeout);
            iTaskDefinition.Settings.Hidden = !jobOptions.ShowInTaskScheduler;
            iTaskDefinition.Settings.RunOnlyIfNetworkAvailable = !jobOptions.RunWithoutNetwork;
            iTaskDefinition.Settings.AllowDemandStart          = !jobOptions.DoNotAllowDemandStart;
            iTaskDefinition.Settings.MultipleInstances         = this.ConvertFromMultiInstances(jobOptions.MultipleInstancePolicy);
            TaskScheduler.IPrincipal principal = iTaskDefinition.Principal;
            if (jobOptions.RunElevated)
            {
                variable = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;
            }
            else
            {
                variable = _TASK_RUNLEVEL.TASK_RUNLEVEL_LUA;
            }
            principal.RunLevel = variable;
        }
Example #2
0
        private CimInstance ConvertToOnce(ScheduledJobTrigger trigger, CimSession cimSession)
        {
            CimClass    cimClass    = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskTimeTrigger");
            CimInstance cimInstance = new CimInstance(cimClass);

            cimInstance.CimInstanceProperties["RandomDelay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay);

            if (trigger.RepetitionInterval != null && trigger.RepetitionDuration != null)
            {
                CimClass    cimRepClass    = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskRepetitionPattern");
                CimInstance cimRepInstance = new CimInstance(cimRepClass);

                cimRepInstance.CimInstanceProperties["Interval"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RepetitionInterval.Value);

                if (trigger.RepetitionDuration == TimeSpan.MaxValue)
                {
                    cimRepInstance.CimInstanceProperties["StopAtDurationEnd"].Value = false;
                }
                else
                {
                    cimRepInstance.CimInstanceProperties["StopAtDurationEnd"].Value = true;
                    cimRepInstance.CimInstanceProperties["Duration"].Value          = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RepetitionDuration.Value);
                }

                cimInstance.CimInstanceProperties["Repetition"].Value = cimRepInstance;
            }

            AddCommonProperties(trigger, cimInstance);
            return(cimInstance);
        }
        /// <summary>
        /// Process input.
        /// </summary>
        protected override void ProcessRecord()
        {
            List <ScheduledJobDefinition> definitions = null;

            switch (ParameterSetName)
            {
            case DefinitionParameterSet:
                definitions = new List <ScheduledJobDefinition>(_definitions);
                break;

            case DefinitionNameParameterSet:
                definitions = GetJobDefinitionsByName(_names);
                break;

            case DefinitionIdParameterSet:
                definitions = GetJobDefinitionsById(_definitionIds);
                break;
            }

            if (definitions != null)
            {
                foreach (ScheduledJobDefinition definition in definitions)
                {
                    string targetString = StringUtil.Format(ScheduledJobErrorStrings.DefinitionWhatIf, definition.Name);
                    if (ShouldProcess(targetString, VerbsLifecycle.Unregister))
                    {
                        // Removes the ScheduledJobDefinition from the job store,
                        // Task Scheduler, and disposes the object.
                        try
                        {
                            definition.Remove(_force);
                        }
                        catch (ScheduledJobException e)
                        {
                            string      msg         = StringUtil.Format(ScheduledJobErrorStrings.CantUnregisterDefinition, definition.Name);
                            Exception   reason      = new RuntimeException(msg, e);
                            ErrorRecord errorRecord = new ErrorRecord(reason, "CantUnregisterScheduledJobDefinition", ErrorCategory.InvalidOperation, definition);
                            WriteError(errorRecord);
                        }
                    }
                }
            }

            // Check for unknown definition names.
            if ((_names != null && _names.Length > 0) &&
                (_definitions == null || _definitions.Length < _names.Length))
            {
                // Make sure there is no PowerShell task in Task Scheduler with removed names.
                // This covers the case where the scheduled job definition was manually removed from
                // the job store but remains as a PowerShell task in Task Scheduler.
                using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS())
                {
                    foreach (string name in _names)
                    {
                        taskScheduler.RemoveTaskByName(name, true, true);
                    }
                }
            }
        }
        private CimInstance ConvertToAtStartup(ScheduledJobTrigger trigger, CimSession cimSession)
        {
            CimClass    @class      = cimSession.GetClass(JobTriggerToCimInstanceConverter.CIM_TRIGGER_NAMESPACE, "MSFT_TaskBootTrigger");
            CimInstance cimInstance = new CimInstance(@class);

            cimInstance.CimInstanceProperties["Delay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay);
            JobTriggerToCimInstanceConverter.AddCommonProperties(trigger, cimInstance);
            return(cimInstance);
        }
Example #5
0
        private static void AddCommonProperties(ScheduledJobTrigger trigger, CimInstance cimInstance)
        {
            cimInstance.CimInstanceProperties["Enabled"].Value = trigger.Enabled;

            if (trigger.At != null)
            {
                cimInstance.CimInstanceProperties["StartBoundary"].Value = ScheduledJobWTS.ConvertDateTimeToString(trigger.At);
            }
        }
        private CimInstance ConvertToWeekly(ScheduledJobTrigger trigger, CimSession cimSession)
        {
            CimClass    @class      = cimSession.GetClass(JobTriggerToCimInstanceConverter.CIM_TRIGGER_NAMESPACE, "MSFT_TaskWeeklyTrigger");
            CimInstance cimInstance = new CimInstance(@class);

            cimInstance.CimInstanceProperties["DaysOfWeek"].Value    = ScheduledJobWTS.ConvertDaysOfWeekToMask(trigger.DaysOfWeek);
            cimInstance.CimInstanceProperties["RandomDelay"].Value   = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay);
            cimInstance.CimInstanceProperties["WeeksInterval"].Value = trigger.Interval;
            JobTriggerToCimInstanceConverter.AddCommonProperties(trigger, cimInstance);
            return(cimInstance);
        }
Example #7
0
        private CimInstance ConvertToDaily(ScheduledJobTrigger trigger, CimSession cimSession)
        {
            CimClass    cimClass    = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskDailyTrigger");
            CimInstance cimInstance = new CimInstance(cimClass);

            cimInstance.CimInstanceProperties["RandomDelay"].Value  = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay);
            cimInstance.CimInstanceProperties["DaysInterval"].Value = trigger.Interval;

            AddCommonProperties(trigger, cimInstance);
            return(cimInstance);
        }
Example #8
0
        private CimInstance ConvertToAtLogon(ScheduledJobTrigger trigger, CimSession cimSession)
        {
            CimClass    cimClass    = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskLogonTrigger");
            CimInstance cimInstance = new CimInstance(cimClass);

            cimInstance.CimInstanceProperties["Delay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay);

            // Convert the "AllUsers" name ("*" character) to null for Task Scheduler.
            string userId = (ScheduledJobTrigger.IsAllUsers(trigger.User)) ? null : trigger.User;

            cimInstance.CimInstanceProperties["UserId"].Value = userId;

            AddCommonProperties(trigger, cimInstance);
            return(cimInstance);
        }
        private CimInstance ConvertToOnce(ScheduledJobTrigger trigger, CimSession cimSession)
        {
            bool        valueOrDefault;
            CimClass    @class      = cimSession.GetClass(JobTriggerToCimInstanceConverter.CIM_TRIGGER_NAMESPACE, "MSFT_TaskTimeTrigger");
            CimInstance cimInstance = new CimInstance(@class);

            cimInstance.CimInstanceProperties["RandomDelay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay);
            TimeSpan?repetitionInterval = trigger.RepetitionInterval;

            if (repetitionInterval.HasValue)
            {
                TimeSpan?repetitionDuration = trigger.RepetitionDuration;
                if (repetitionDuration.HasValue)
                {
                    CimClass    cimClass  = cimSession.GetClass(JobTriggerToCimInstanceConverter.CIM_TRIGGER_NAMESPACE, "MSFT_TaskRepetitionPattern");
                    CimInstance wTSString = new CimInstance(cimClass);
                    TimeSpan?   nullable  = trigger.RepetitionInterval;
                    wTSString.CimInstanceProperties["Interval"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(nullable.Value);
                    TimeSpan?repetitionDuration1 = trigger.RepetitionDuration;
                    TimeSpan maxValue            = TimeSpan.MaxValue;
                    if (!repetitionDuration1.HasValue)
                    {
                        valueOrDefault = false;
                    }
                    else
                    {
                        valueOrDefault = repetitionDuration1.GetValueOrDefault() == maxValue;
                    }
                    if (!valueOrDefault)
                    {
                        wTSString.CimInstanceProperties["StopAtDurationEnd"].Value = true;
                        TimeSpan?nullable1 = trigger.RepetitionDuration;
                        wTSString.CimInstanceProperties["Duration"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(nullable1.Value);
                    }
                    else
                    {
                        wTSString.CimInstanceProperties["StopAtDurationEnd"].Value = false;
                    }
                    cimInstance.CimInstanceProperties["Repetition"].Value = wTSString;
                }
            }
            JobTriggerToCimInstanceConverter.AddCommonProperties(trigger, cimInstance);
            return(cimInstance);
        }
        private CimInstance ConvertToAtLogon(ScheduledJobTrigger trigger, CimSession cimSession)
        {
            string      user;
            CimClass    @class      = cimSession.GetClass(JobTriggerToCimInstanceConverter.CIM_TRIGGER_NAMESPACE, "MSFT_TaskLogonTrigger");
            CimInstance cimInstance = new CimInstance(@class);

            cimInstance.CimInstanceProperties["Delay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay);
            if (ScheduledJobTrigger.IsAllUsers(trigger.User))
            {
                user = null;
            }
            else
            {
                user = trigger.User;
            }
            string str = user;

            cimInstance.CimInstanceProperties["UserId"].Value = str;
            JobTriggerToCimInstanceConverter.AddCommonProperties(trigger, cimInstance);
            return(cimInstance);
        }
 /// <summary>
 /// Adds this scheduled job definition to the Task Scheduler.
 /// </summary>
 private void AddToWTS()
 {
     using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS())
     {
         taskScheduler.CreateTask(this);
     }
 }
		protected override void ProcessRecord()
		{
			List<ScheduledJobDefinition> scheduledJobDefinitions = null;
			string parameterSetName = base.ParameterSetName;
			string str = parameterSetName;
			if (parameterSetName != null)
			{
				if (str == "Definition")
				{
					scheduledJobDefinitions = new List<ScheduledJobDefinition>(this._definitions);
				}
				else
				{
					if (str == "DefinitionName")
					{
						scheduledJobDefinitions = base.GetJobDefinitionsByName(this._names, true);
					}
					else
					{
						if (str == "DefinitionId")
						{
							scheduledJobDefinitions = base.GetJobDefinitionsById(this._definitionIds, true);
						}
					}
				}
			}
			if (scheduledJobDefinitions != null)
			{
				foreach (ScheduledJobDefinition scheduledJobDefinition in scheduledJobDefinitions)
				{
					string str1 = StringUtil.Format(ScheduledJobErrorStrings.DefinitionWhatIf, scheduledJobDefinition.Name);
					if (!base.ShouldProcess(str1, "Unregister"))
					{
						continue;
					}
					try
					{
						scheduledJobDefinition.Remove(this._force);
					}
					catch (ScheduledJobException scheduledJobException1)
					{
						ScheduledJobException scheduledJobException = scheduledJobException1;
						string str2 = StringUtil.Format(ScheduledJobErrorStrings.CantUnregisterDefinition, scheduledJobDefinition.Name);
						Exception runtimeException = new RuntimeException(str2, scheduledJobException);
						ErrorRecord errorRecord = new ErrorRecord(runtimeException, "CantUnregisterScheduledJobDefinition", ErrorCategory.InvalidOperation, scheduledJobDefinition);
						base.WriteError(errorRecord);
					}
				}
			}
			if (this._names != null && (int)this._names.Length > 0 && (this._definitions == null || (int)this._definitions.Length < (int)this._names.Length))
			{
				using (ScheduledJobWTS scheduledJobWT = new ScheduledJobWTS())
				{
					string[] strArrays = this._names;
					for (int i = 0; i < (int)strArrays.Length; i++)
					{
						string str3 = strArrays[i];
						scheduledJobWT.RemoveTaskByName(str3, true, true);
					}
				}
			}
		}
        protected override void ProcessRecord()
        {
            List <ScheduledJobDefinition> scheduledJobDefinitions = null;
            string parameterSetName = base.ParameterSetName;
            string str = parameterSetName;

            if (parameterSetName != null)
            {
                if (str == "Definition")
                {
                    scheduledJobDefinitions = new List <ScheduledJobDefinition>(this._definitions);
                }
                else
                {
                    if (str == "DefinitionName")
                    {
                        scheduledJobDefinitions = base.GetJobDefinitionsByName(this._names, true);
                    }
                    else
                    {
                        if (str == "DefinitionId")
                        {
                            scheduledJobDefinitions = base.GetJobDefinitionsById(this._definitionIds, true);
                        }
                    }
                }
            }
            if (scheduledJobDefinitions != null)
            {
                foreach (ScheduledJobDefinition scheduledJobDefinition in scheduledJobDefinitions)
                {
                    string str1 = StringUtil.Format(ScheduledJobErrorStrings.DefinitionWhatIf, scheduledJobDefinition.Name);
                    if (!base.ShouldProcess(str1, "Unregister"))
                    {
                        continue;
                    }
                    try
                    {
                        scheduledJobDefinition.Remove(this._force);
                    }
                    catch (ScheduledJobException scheduledJobException1)
                    {
                        ScheduledJobException scheduledJobException = scheduledJobException1;
                        string      str2             = StringUtil.Format(ScheduledJobErrorStrings.CantUnregisterDefinition, scheduledJobDefinition.Name);
                        Exception   runtimeException = new RuntimeException(str2, scheduledJobException);
                        ErrorRecord errorRecord      = new ErrorRecord(runtimeException, "CantUnregisterScheduledJobDefinition", ErrorCategory.InvalidOperation, scheduledJobDefinition);
                        base.WriteError(errorRecord);
                    }
                }
            }
            if (this._names != null && (int)this._names.Length > 0 && (this._definitions == null || (int)this._definitions.Length < (int)this._names.Length))
            {
                using (ScheduledJobWTS scheduledJobWT = new ScheduledJobWTS())
                {
                    string[] strArrays = this._names;
                    for (int i = 0; i < (int)strArrays.Length; i++)
                    {
                        string str3 = strArrays[i];
                        scheduledJobWT.RemoveTaskByName(str3, true, true);
                    }
                }
            }
        }
        /// <summary>
        /// Process input.
        /// </summary>
        protected override void ProcessRecord()
        {
            List<ScheduledJobDefinition> definitions = null;
            switch (ParameterSetName)
            {
                case DefinitionParameterSet:
                    definitions = new List<ScheduledJobDefinition>(_definitions);
                    break;

                case DefinitionNameParameterSet:
                    definitions = GetJobDefinitionsByName(_names);
                    break;

                case DefinitionIdParameterSet:
                    definitions = GetJobDefinitionsById(_definitionIds);
                    break;
            }

            if (definitions != null)
            {
                foreach (ScheduledJobDefinition definition in definitions)
                {
                    string targetString = StringUtil.Format(ScheduledJobErrorStrings.DefinitionWhatIf, definition.Name);
                    if (ShouldProcess(targetString, VerbsLifecycle.Unregister))
                    {
                        // Removes the ScheduledJobDefinition from the job store,
                        // Task Scheduler, and disposes the object.
                        try
                        {
                            definition.Remove(_force);
                        }
                        catch (ScheduledJobException e)
                        {
                            string msg = StringUtil.Format(ScheduledJobErrorStrings.CantUnregisterDefinition, definition.Name);
                            Exception reason = new RuntimeException(msg, e);
                            ErrorRecord errorRecord = new ErrorRecord(reason, "CantUnregisterScheduledJobDefinition", ErrorCategory.InvalidOperation, definition);
                            WriteError(errorRecord);
                        }
                    }
                }
            }

            // Check for unknown definition names.
            if ((_names != null && _names.Length > 0) &&
                (_definitions == null || _definitions.Length < _names.Length))
            {
                // Make sure there is no PowerShell task in Task Scheduler with removed names.
                // This covers the case where the scheduled job definition was manually removed from
                // the job store but remains as a PowerShell task in Task Scheduler.
                using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS())
                {
                    foreach (string name in _names)
                    {
                        taskScheduler.RemoveTaskByName(name, true, true);
                    }
                }
            }
        }
Example #15
0
		private void RemoveFromWTS(bool force)
		{
			using (ScheduledJobWTS scheduledJobWT = new ScheduledJobWTS())
			{
				scheduledJobWT.RemoveTask(this, force);
			}
		}
Example #16
0
		internal static void RemoveDefinition(string definitionName)
		{
			try
			{
				ScheduledJobStore.RemoveJobDefinition(definitionName);
			}
			catch (DirectoryNotFoundException directoryNotFoundException)
			{
			}
			catch (FileNotFoundException fileNotFoundException)
			{
			}
			catch (UnauthorizedAccessException unauthorizedAccessException)
			{
			}
			catch (IOException oException)
			{
			}
			using (ScheduledJobWTS scheduledJobWT = new ScheduledJobWTS())
			{
				try
				{
					scheduledJobWT.RemoveTaskByName(definitionName, true, true);
				}
				catch (UnauthorizedAccessException unauthorizedAccessException1)
				{
				}
				catch (IOException oException1)
				{
				}
			}
		}
Example #17
0
		private void AddToWTS()
		{
			using (ScheduledJobWTS scheduledJobWT = new ScheduledJobWTS())
			{
				scheduledJobWT.CreateTask(this);
			}
		}
Example #18
0
		private void UpdateWTSFromDefinition()
		{
			using (ScheduledJobWTS scheduledJobWT = new ScheduledJobWTS())
			{
				scheduledJobWT.UpdateTask(this);
			}
		}
Example #19
0
		private bool UpdateDefintionFromWTS()
		{
			ScheduledJobTrigger current = null;
			ScheduledJobTrigger item = null;
			bool valueOrDefault = false;
			bool flag = false;
			using (ScheduledJobWTS scheduledJobWT = new ScheduledJobWTS())
			{
				bool taskEnabled = scheduledJobWT.GetTaskEnabled(this._name);
				ScheduledJobOptions jobOptions = scheduledJobWT.GetJobOptions(this._name);
				Collection<ScheduledJobTrigger> jobTriggers = scheduledJobWT.GetJobTriggers(this._name);
				if (taskEnabled != this._enabled)
				{
					this._enabled = taskEnabled;
					flag = true;
				}
				if (jobOptions.DoNotAllowDemandStart != this._options.DoNotAllowDemandStart || jobOptions.IdleDuration != this._options.IdleDuration || jobOptions.IdleTimeout != this._options.IdleTimeout || jobOptions.MultipleInstancePolicy != this._options.MultipleInstancePolicy || jobOptions.RestartOnIdleResume != this._options.RestartOnIdleResume || jobOptions.RunElevated != this._options.RunElevated || jobOptions.RunWithoutNetwork != this._options.RunWithoutNetwork || jobOptions.ShowInTaskScheduler != this._options.ShowInTaskScheduler || jobOptions.StartIfNotIdle != this._options.StartIfNotIdle || jobOptions.StartIfOnBatteries != this._options.StartIfOnBatteries || jobOptions.StopIfGoingOffIdle != this._options.StopIfGoingOffIdle || jobOptions.StopIfGoingOnBatteries != this._options.StopIfGoingOnBatteries || jobOptions.WakeToRun != this._options.WakeToRun)
				{
					jobOptions.JobDefinition = this._options.JobDefinition;
					this._options = jobOptions;
					flag = true;
				}
				if (this._triggers.Count == jobTriggers.Count)
				{
					bool flag1 = false;
					IEnumerator<ScheduledJobTrigger> enumerator = jobTriggers.GetEnumerator();
					using (enumerator)
					{
						do
						{
							if (!enumerator.MoveNext())
							{
								continue;
							}
							current = enumerator.Current;
							if (this._triggers.ContainsKey(current.Id))
							{
								item = this._triggers[current.Id];
								if (item.DaysOfWeek != current.DaysOfWeek || item.Enabled != current.Enabled || item.Frequency != current.Frequency || item.Interval != current.Interval || item.RandomDelay != current.RandomDelay)
								{
									break;
								}
								DateTime? at = item.At;
								DateTime? nullable = current.At;
								if (at.HasValue != nullable.HasValue)
								{
									valueOrDefault = true;
								}
								else
								{
									if (!at.HasValue)
									{
										valueOrDefault = false;
									}
									else
									{
										valueOrDefault = at.GetValueOrDefault() != nullable.GetValueOrDefault();
									}
								}
							}
							else
							{
								flag1 = true;
								break;
							}
						}
						while (!valueOrDefault && !(item.User != current.User));
						flag1 = true;
					}
					if (flag1)
					{
						this.SetTriggers(jobTriggers, false);
						flag = true;
					}
				}
				else
				{
					this.SetTriggers(jobTriggers, false);
					flag = true;
				}
			}
			return flag;
		}
        /// <summary>
        /// Compares the current ScheduledJobDefinition task scheduler information
        /// with the corresponding information stored in Task Scheduler.  If the
        /// information is different then the task scheduler information in this 
        /// object is updated to match what is in Task Scheduler, since that information
        /// takes precedence.
        /// 
        /// Task Scheduler information:
        /// - Triggers
        /// - Options
        /// - Enabled state
        /// </summary>
        /// <returns>Boolean if this object data is modified.</returns>
        private bool UpdateDefintionFromWTS()
        {
            bool dataModified = false;

            // Get information from Task Scheduler.
            using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS())
            {
                bool wtsEnabled = taskScheduler.GetTaskEnabled(_name);
                ScheduledJobOptions wtsOptions = taskScheduler.GetJobOptions(_name);
                Collection<ScheduledJobTrigger> wtsTriggers = taskScheduler.GetJobTriggers(_name);

                //
                // Compare with existing object data and modify if necessary.
                //

                // Enabled.
                if (wtsEnabled != _enabled)
                {
                    _enabled = wtsEnabled;
                    dataModified = true;
                }

                // Options.
                if (wtsOptions.DoNotAllowDemandStart != _options.DoNotAllowDemandStart ||
                    wtsOptions.IdleDuration != _options.IdleDuration ||
                    wtsOptions.IdleTimeout != _options.IdleTimeout ||
                    wtsOptions.MultipleInstancePolicy != _options.MultipleInstancePolicy ||
                    wtsOptions.RestartOnIdleResume != _options.RestartOnIdleResume ||
                    wtsOptions.RunElevated != _options.RunElevated ||
                    wtsOptions.RunWithoutNetwork != _options.RunWithoutNetwork ||
                    wtsOptions.ShowInTaskScheduler != _options.ShowInTaskScheduler ||
                    wtsOptions.StartIfNotIdle != _options.StartIfNotIdle ||
                    wtsOptions.StartIfOnBatteries != _options.StartIfOnBatteries ||
                    wtsOptions.StopIfGoingOffIdle != _options.StopIfGoingOffIdle ||
                    wtsOptions.StopIfGoingOnBatteries != _options.StopIfGoingOnBatteries ||
                    wtsOptions.WakeToRun != _options.WakeToRun)
                {
                    // Keep the current scheduled job definition reference.
                    wtsOptions.JobDefinition = _options.JobDefinition;
                    _options = wtsOptions;
                    dataModified = true;
                }

                // Triggers.
                if (_triggers.Count != wtsTriggers.Count)
                {
                    SetTriggers(wtsTriggers, false);
                    dataModified = true;
                }
                else
                {
                    bool foundTriggerDiff = false;

                    // Compare each trigger object.
                    foreach (var wtsTrigger in wtsTriggers)
                    {
                        if (_triggers.ContainsKey(wtsTrigger.Id) == false)
                        {
                            foundTriggerDiff = true;
                            break;
                        }

                        ScheduledJobTrigger trigger = _triggers[wtsTrigger.Id];
                        if (trigger.DaysOfWeek != wtsTrigger.DaysOfWeek ||
                            trigger.Enabled != wtsTrigger.Enabled ||
                            trigger.Frequency != wtsTrigger.Frequency ||
                            trigger.Interval != wtsTrigger.Interval ||
                            trigger.RandomDelay != wtsTrigger.RandomDelay ||
                            trigger.At != wtsTrigger.At ||
                            trigger.User != wtsTrigger.User)
                        {
                            foundTriggerDiff = true;
                            break;
                        }
                    }

                    if (foundTriggerDiff)
                    {
                        SetTriggers(wtsTriggers, false);
                        dataModified = true;
                    }
                }
            }

            return dataModified;
        }
 /// <summary>
 /// Updates existing information if scheduled job already exists.
 /// WTS entry includes command line, options, and trigger conditions.
 /// </summary>
 private void UpdateWTSFromDefinition()
 {
     using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS())
     {
         taskScheduler.UpdateTask(this);
     }
 }
        /// <summary>
        /// Internal helper method to remove a scheduled job definition
        /// by name from job store and Task Scheduler.
        /// </summary>
        /// <param name="definitionName">Scheduled job definition name</param>
        internal static void RemoveDefinition(
            string definitionName)
        {
            // Remove from store.
            try
            {
                ScheduledJobStore.RemoveJobDefinition(definitionName);
            }
            catch (DirectoryNotFoundException)
            { }
            catch (FileNotFoundException)
            { }
            catch (UnauthorizedAccessException)
            { }
            catch (IOException)
            { }

            // Check and remove from Task Scheduler.
            using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS())
            {
                try
                {
                    taskScheduler.RemoveTaskByName(definitionName, true, true);
                }
                catch (UnauthorizedAccessException)
                { }
                catch (IOException)
                { }
            }
        }
        /// <summary>
        /// Starts registered job definition running from the Task Scheduler.
        /// </summary>
        public void RunAsTask()
        {
            IsDisposed();

            Exception ex = null;
            string reason = null;
            try
            {
                using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS())
                {
                    taskScheduler.RunTask(this);
                }
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                reason = ScheduledJobErrorStrings.reasonJobNotFound;
                ex = e;
            }
            catch (System.IO.FileNotFoundException e)
            {
                reason = ScheduledJobErrorStrings.reasonJobNotFound;
                ex = e;
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                reason = ConvertCOMErrorCode(e);
                ex = e;
            }

            if (ex != null)
            {
                string msg;
                if (reason != null)
                {
                    msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorRunningAsTaskWithReason, this.Name, reason);
                }
                else
                {
                    msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorRunningAsTask, this.Name);
                }

                throw new ScheduledJobException(msg, ex);
            }
        }
 /// <summary>
 /// Removes this scheduled job definition from the Task Scheduler.
 /// This operation will fail if a current instance of this job definition
 /// is running.
 /// If force == true then all current instances will be stopped.
 /// </summary>
 /// <param name="force">Force removal and stop all running instances.</param>
 private void RemoveFromWTS(bool force)
 {
     using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS())
     {
         taskScheduler.RemoveTask(this, force);
     }
 }
Example #25
0
        private void AddTaskTrigger(ITaskDefinition iTaskDefinition, ScheduledJobTrigger jobTrigger)
        {
            ITrigger         str;
            string           user;
            TriggerFrequency frequency = jobTrigger.Frequency;

            switch (frequency)
            {
            case TriggerFrequency.Once:
            {
                str = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
                ITimeTrigger wTSString = str as ITimeTrigger;
                wTSString.RandomDelay = ScheduledJobWTS.ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);
                TimeSpan?repetitionInterval = jobTrigger.RepetitionInterval;
                if (repetitionInterval.HasValue)
                {
                    TimeSpan?repetitionDuration = jobTrigger.RepetitionDuration;
                    if (repetitionDuration.HasValue)
                    {
                        TimeSpan?nullable = jobTrigger.RepetitionInterval;
                        wTSString.Repetition.Interval = ScheduledJobWTS.ConvertTimeSpanToWTSString(nullable.Value);
                        TimeSpan?repetitionDuration1 = jobTrigger.RepetitionDuration;
                        if (repetitionDuration1.Value != TimeSpan.MaxValue)
                        {
                            wTSString.Repetition.StopAtDurationEnd = true;
                            TimeSpan?nullable1 = jobTrigger.RepetitionDuration;
                            wTSString.Repetition.Duration = ScheduledJobWTS.ConvertTimeSpanToWTSString(nullable1.Value);
                        }
                        else
                        {
                            wTSString.Repetition.StopAtDurationEnd = false;
                        }
                    }
                }
                str.StartBoundary = ScheduledJobWTS.ConvertDateTimeToString(jobTrigger.At);
                int id = jobTrigger.Id;
                str.Id      = id.ToString(CultureInfo.InvariantCulture);
                str.Enabled = jobTrigger.Enabled;
                return;
            }

            case TriggerFrequency.Daily:
            {
                str = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);
                IDailyTrigger interval = str as IDailyTrigger;
                interval.RandomDelay  = ScheduledJobWTS.ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);
                interval.DaysInterval = (short)jobTrigger.Interval;
                str.StartBoundary     = ScheduledJobWTS.ConvertDateTimeToString(jobTrigger.At);
                int num = jobTrigger.Id;
                str.Id      = num.ToString(CultureInfo.InvariantCulture);
                str.Enabled = jobTrigger.Enabled;
                return;
            }

            case TriggerFrequency.Weekly:
            {
                str = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_WEEKLY);
                IWeeklyTrigger mask = str as IWeeklyTrigger;
                mask.RandomDelay   = ScheduledJobWTS.ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);
                mask.WeeksInterval = (short)jobTrigger.Interval;
                mask.DaysOfWeek    = ScheduledJobWTS.ConvertDaysOfWeekToMask(jobTrigger.DaysOfWeek);
                str.StartBoundary  = ScheduledJobWTS.ConvertDateTimeToString(jobTrigger.At);
                int id1 = jobTrigger.Id;
                str.Id      = id1.ToString(CultureInfo.InvariantCulture);
                str.Enabled = jobTrigger.Enabled;
                return;
            }

            case TriggerFrequency.AtLogon:
            {
                str = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON);
                ILogonTrigger variable  = str as ILogonTrigger;
                ILogonTrigger variable1 = variable;
                if (ScheduledJobTrigger.IsAllUsers(jobTrigger.User))
                {
                    user = null;
                }
                else
                {
                    user = jobTrigger.User;
                }
                variable1.UserId = user;
                variable.Delay   = ScheduledJobWTS.ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);
                int num1 = jobTrigger.Id;
                str.Id      = num1.ToString(CultureInfo.InvariantCulture);
                str.Enabled = jobTrigger.Enabled;
                return;
            }

            case TriggerFrequency.AtStartup:
            {
                str = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_BOOT);
                IBootTrigger wTSString1 = str as IBootTrigger;
                wTSString1.Delay = ScheduledJobWTS.ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);
                int id2 = jobTrigger.Id;
                str.Id      = id2.ToString(CultureInfo.InvariantCulture);
                str.Enabled = jobTrigger.Enabled;
                return;
            }

            default:
            {
                return;
            }
            }
        }