IEnumerator constructionHandler() { yield return(new WaitForSeconds(0.01f)); //Add construction progress and update progress bar. currentTaskProgress += currentWorkers.Count * 0.1f; this.GetComponent <buildingGuiHandler>().taskProgress.fillAmount = (currentTaskProgress / taskProgressMax); if (currentTaskProgress < taskProgressMax) { StartCoroutine(constructionHandler()); } else { currentTask = taskType.nothing; buildingLevel += 1; currentTaskProgress = 0; GameObject building = Instantiate(level[buildingLevel - 1], this.transform.position, this.transform.rotation); building.transform.parent = this.transform; Destroy(currentBuilding); currentBuilding = building; gm.GetComponent <gameManagerScript>().availableWorkers += currentAssignedWorkers.Count; Debug.Log(currentWorkers.Count); var allWorkers = currentWorkers.Count; for (int i = 0; i < allWorkers; i++) { removeWorker(); } } }
//Fire Related funcitons public void startFire() { currentTask = taskType.onFire; currentTaskProgress = 0; StopAllCoroutines(); StartCoroutine(fireHandler()); this.GetComponent <buildingGuiHandler>().taskText.text = "0/" + maxFiremen.ToString(); }
/// <summary> /// Ajoute un enregistrement dans une liste d'un onglet sélectionner /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BTN_Add_Click(object sender, EventArgs e) { // ajouter un projet if (TBC_Project.SelectedTab == TBP_ListProject) { project addProject = new project() { identifier = getIdentifierProject() }; EditProject editProject = new EditProject(addProject); editProject.StartPosition = FormStartPosition.CenterParent; if (editProject.ShowDialog() == DialogResult.OK) { if (!String.IsNullOrWhiteSpace(addProject.name)) { _ProjectManagement.ListProject.Add(addProject); hasChanges = true; } } } // ajouter un type de tâche else if (TBC_Project.SelectedTab == TBP_ListTypeTask) { taskType addTaskType = new taskType() { identifier = getIdentifierTaskType() }; EditTaskType editTaskType = new EditTaskType(addTaskType); editTaskType.StartPosition = FormStartPosition.CenterParent; if (editTaskType.ShowDialog() == DialogResult.OK) { //TODO verif _ProjectManagement.ListTaskType.Add(addTaskType); hasChanges = true; } } //ajouter une tache else if (TBC_Project.SelectedTab == TBP_ListTask) { task addTask = new task() { Identifier = getIdentifierTask() }; EditTask editTask = new EditTask(_ProjectManagement.ListProject, _ProjectManagement.ListTaskType, addTask); editTask.StartPosition = FormStartPosition.CenterParent; if (editTask.ShowDialog() == DialogResult.OK) { //TODO verif _ProjectManagement.ListTask.Add(addTask); hasChanges = true; } } }
/// <summary> /// Supprimer un enrigstrement sélectionner dans une liste d'une onglet sélectionner /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MIT_Delete_Click(object sender, EventArgs e) { if (TBC_Project.SelectedTab == TBP_ListProject && DTG_Project.SelectedRows[0].DataBoundItem != null) { project selected = DTG_Project.SelectedRows[0].DataBoundItem as project; exists = false; foreach (task t in _ProjectManagement.ListTask) { if (t.IdentifierProject == selected.identifier) { exists = true; } } if (!exists) { _ProjectManagement.ListProject.Remove(selected); hasChanges = true; } else { MessageBox.Show("Une tâche est attaché à ce projet !", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else if (TBC_Project.SelectedTab == TBP_ListTypeTask && DTG_ListeTaskType.SelectedRows[0].DataBoundItem != null) { currentTaskType = DTG_ListeTaskType.SelectedRows[0].DataBoundItem as taskType; exists = false; foreach (task t in _ProjectManagement.ListTask) { if (t.IdentifierTaskType == currentTaskType.identifier) { exists = true; } } if (!exists) { _ProjectManagement.ListTaskType.Remove(currentTaskType); hasChanges = true; } else { MessageBox.Show("Une tâche est attaché à ce type de tache !", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else if (TBC_Project.SelectedTab == TBP_ListTask && DTG_ListTask.SelectedRows[0].DataBoundItem != null) { _ProjectManagement.ListTask.Remove(DTG_ListTask.SelectedRows[0].DataBoundItem as task); hasChanges = true; } }
IEnumerator waitEnum(float time) { currTask = taskType.idle; yield return(new WaitForSeconds(time)); currTask = taskType.playFortnite; UpdateTask(); }
internal void Add(taskType node) { if (node != null) { while (System.Threading.Interlocked.CompareExchange(ref queueLock, 1, 0) != 0) { AutoCSer.Threading.ThreadYield.YieldOnly(); } add(node); } }
public EditTaskType(taskType Task) { InitializeComponent(); this._Task = Task; if (!String.IsNullOrWhiteSpace(Task.label)) { TBX_Lbl.Text = Task.label; RTC_Desc.Text = Task.description; } }
public void UpdateTask() { if (currTask == taskType.idle) { return; } if (peg.currCoin) { currTask = taskType.deliverCoin; currTarget = GameManager.main.currLevel.coinAreas[peg.color].transform; return; } float crateScore = 0; float enemyScore = 0; float coinScore = 0; Transform crateTrans = FindClosest(GameManager.main.currCrates.Where(x => x != null).Select(x => x.gameObject.transform).ToList(), out crateScore); Transform coinTrans = FindClosest(GameManager.main.currCoins.Where(x => x != null && x.color != peg.color && x != peg.currCoin && !(x.isHolded && x.currHolder.color == peg.color)).Select(x => x.gameObject.transform).ToList(), out coinScore); Transform enemyTrans = FindClosest(GameManager.main.currPegs.Where(x => x != null && !x.isInvisible && x.color != peg.color && x != peg) .Select(x => x.gameObject.transform).ToList(), out enemyScore); crateScore = crateMult * (1 / crateScore); enemyScore = crateMult * (1 / enemyScore); coinScore = coinMult * (1 / coinScore); //print("Enemy score " + enemyScore); //print("Crate score " + crateScore); //print("Coin score " + coinScore); if (enemyScore > crateScore && enemyScore > coinScore) { currTarget = enemyTrans; currTask = taskType.attack; } else if (crateScore > enemyScore && crateScore > coinScore) { currTarget = crateTrans; currTask = taskType.crate; } else { currTarget = coinTrans; currTask = taskType.collectCoin; } }
/// <summary> /// 添加任务 /// </summary> /// <param name="node"></param> private void add(taskType node) { if (head == null) { head = end = node; System.Threading.Interlocked.Exchange(ref queueLock, 0); queue.Add(this); } else { end.LinkNext = node; end = node; System.Threading.Interlocked.Exchange(ref queueLock, 0); } }
//Construction Related Functions; public void startConstruction() { gm = GameObject.FindGameObjectWithTag("gameManager"); if (buildingLevel < level.Length) { currentTask = taskType.constructing; gm.GetComponent <gameManagerScript>().money -= constructionCost[buildingLevel]; Destroy(currentBuilding); currentBuilding = Instantiate(worksite[buildingLevel], gameObject.transform.position, gameObject.transform.rotation); currentBuilding.transform.parent = this.transform; StartCoroutine(constructionHandler()); this.GetComponent <buildingGuiHandler>().taskText.text = "0/" + maxBuilders.ToString(); } }
/// <summary> /// Modifie un enregistrement sélectionner dans une liste d'un onglet sélectionner /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MIT_Open_Click(object sender, EventArgs e) { // ouvrir la liste des projets if (TBC_Project.SelectedTab == TBP_ListProject && DTG_Project.SelectedRows[0].DataBoundItem != null) { project selectedProject = DTG_Project.SelectedRows[0].DataBoundItem as project; EditProject editProject = new EditProject(selectedProject); editProject.StartPosition = FormStartPosition.CenterParent; if (editProject.ShowDialog() == DialogResult.OK) { _ProjectManagement.ListProject.Remove(selectedProject); _ProjectManagement.ListProject.Add(selectedProject); hasChanges = true; } } // ouvrir la liste des types de tâches else if (TBC_Project.SelectedTab == TBP_ListTypeTask && DTG_ListeTaskType.SelectedRows[0].DataBoundItem != null) { taskType selectedTaskType = DTG_ListeTaskType.SelectedRows[0].DataBoundItem as taskType; EditTaskType editTaskType = new EditTaskType(selectedTaskType); editTaskType.StartPosition = FormStartPosition.CenterParent; if (editTaskType.ShowDialog() == DialogResult.OK) { _ProjectManagement.ListTaskType.Remove(selectedTaskType); _ProjectManagement.ListTaskType.Add(selectedTaskType); hasChanges = true; } } // ouvrir la liste des tâches else if (TBC_Project.SelectedTab == TBP_ListTask && DTG_ListTask.SelectedRows[0].DataBoundItem != null) { task selectedTask = DTG_ListTask.SelectedRows[0].DataBoundItem as task; EditTask editTask = new EditTask(_ProjectManagement.ListProject, _ProjectManagement.ListTaskType, selectedTask); editTask.StartPosition = FormStartPosition.CenterParent; if (editTask.ShowDialog() == DialogResult.OK) { _ProjectManagement.ListTask.Remove(selectedTask); _ProjectManagement.ListTask.Add(selectedTask); hasChanges = true; } } }
/// <summary> /// 添加任务 /// </summary> /// <param name="node"></param> /// <returns></returns> public bool CheckAdd(taskType node) { if (node != null) { while (System.Threading.Interlocked.CompareExchange(ref queueLock, 1, 0) != 0) { AutoCSer.Threading.ThreadYield.YieldOnly(); } if (node.LinkNext == null && node != end) { add(node); return(true); } System.Threading.Interlocked.Exchange(ref queueLock, 0); } return(false); }
/// <summary> /// 执行任务 /// </summary> internal void RunTask() { taskType node = head, next = head.LinkNext; if (next == null) { while (System.Threading.Interlocked.CompareExchange(ref queueLock, 1, 0) != 0) { AutoCSer.Threading.ThreadYield.YieldOnly(); } head = next = head.LinkNext; System.Threading.Interlocked.Exchange(ref queueLock, 0); node.LinkNext = null; try { node.RunTask(); } finally { if (next != null) { queue.Add(this); } } } else { head = next; node.LinkNext = null; try { node.RunTask(); } finally { queue.Add(this); } } }
public void RemoveTask() { currTarget = null; currTask = taskType.idle; }
/** * Creates a new task to be performed at the given target, with the given * scheduling limitations * @param Type the type of task to perform * @param Target the target at which the task is to be performed * @param MaxTimesToPerform the maximum number of times the task should be performed */ // ToDo: convert taskType to an extensable enumeration public Task(taskType taskType, Target target, int maxTimesToPerform) { Type = taskType; Target = target; MaxTimesToPerform = maxTimesToPerform; }
/// <summary> /// Modifit la valeur de la description du type de tâche en fonction du type de tâche de la combobox /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CBX_TaskType_SelectedIndexChanged(object sender, EventArgs e) { taskType selectedTaskType = CBX_TaskType.SelectedItem as taskType; RTB_DescTaskType.Text = selectedTaskType.description; }
static void Main(string[] args) { string hostURL; Console.Write("Please enter the URL of the webservice host, without the path name of the service file, and press Enter."); Console.WriteLine(" [Leave blank for http://localhost:8080]"); hostURL = Console.ReadLine().Trim(); if (hostURL.Length == 0) { hostURL = "http://localhost:8080"; } if (!hostURL.EndsWith("/")) { hostURL += "/"; } hostURL += "itg/ppmservices/ProjectService?wsdl"; Console.WriteLine("\nCreating service proxy..."); ProjectServiceWse serviceProxy = new ProjectServiceWse(); serviceProxy.Url = hostURL; Console.WriteLine("\nSetting authentication policy..."); UsernameOverTransportAssertion policyAssertion = new UsernameOverTransportAssertion(); policyAssertion.UsernameTokenProvider = new UsernameTokenProvider("admin", "admin"); Policy p = new Policy(policyAssertion); serviceProxy.SetPolicy(p); Console.WriteLine("\nCalling createProject service..."); CreateProject cp = new CreateProject(); cp.projectBean = new projectType(); cp.projectBean.Item = "Enterprise"; cp.projectBean.plannedFinishPeriodFullName = "May 2007"; cp.projectBean.plannedStartPeriodFullName = "May 2007"; cp.projectBean.projectName = "Test webservices project " + DateTime.Now.Ticks; cp.projectBean.regionName = "America"; cp.projectBean.projectManagerUserName = new string[1] { "admin" }; CreateProjectResponse cpr = serviceProxy.createProject(cp); Console.WriteLine("Project created with ID={0}; Name={1}", [email protected], cp.projectBean.projectName); Console.WriteLine("\nCalling createBlankWorkPlan service..."); CreateBlankWorkPlan cbwp = new CreateBlankWorkPlan(); cbwp.projectInput = new workPlanInputType(); cbwp.projectInput.Item = cp.projectBean.projectName; CreateBlankWorkPlanResponse cbwpr = serviceProxy.createBlankWorkPlan(cbwp); Console.WriteLine("Blank work plan created with response={0}", cbwpr.ToString()); Console.WriteLine("\nAdding a task to the blank work plan (addTasksToExistingWorkPlan)..."); AddTasksToExistingWorkPlan attewp = new AddTasksToExistingWorkPlan(); attewp.workPlanInput = new workPlanInputType(); attewp.workPlanInput.Item = cp.projectBean.projectName; //Create and add an empty task element taskType task1 = new taskType(); attewp.tasks = new taskType[1]; attewp.tasks[0] = task1; //Set required properties for task //set outline level task1.outlineLevel = 2; //set sequence task1.taskSequence = 1; //set task name task1.taskName = "pm ws test addTask 1"; //create and add task scheduling bean to task. scheduleInfo si = new scheduleInfo(); si.scheduledDuration = 4; si.scheduledEffort = 34; si.scheduledStart = new DateTime(2007, 2, 21); si.scheduledFinish = new DateTime(2007, 2, 22); si.constraintType = scheduleInfoConstraintType.assoonaspossible; task1.schedulingBean = si; attewp.anchors = new taskAnchors(); attewp.anchors.topAnchor = new anchorType(); attewp.anchors.topAnchor.outLineLevel = 1; attewp.anchors.topAnchor.taskSequeceNumber = 0; //All other data is optional, but can be set up the same way as above. //Calling service layer api addTaskResultType[] addedTasks = serviceProxy.addTasksToExistingWorkPlan(attewp); //Check the response and make sure we are getting it back ok for (int i = 0; i < addedTasks.Length; i++) { addTaskResultType addedTask = addedTasks[i]; Console.WriteLine("Task added: ID={0}; Sequence={1}", addedTask.taskId, addedTask.taskSequenceNumber); } Console.WriteLine(); Console.WriteLine("\nAdding two more tasks to the work plan (addTasksToExistingWorkPlan)..."); attewp = new AddTasksToExistingWorkPlan(); attewp.workPlanInput = new workPlanInputType(); attewp.workPlanInput.Item = cp.projectBean.projectName; attewp.tasks = new taskType[2]; attewp.tasks[0] = new taskType(); attewp.tasks[1] = new taskType(); //Set required properties for task //set outline level attewp.tasks[0].outlineLevel = 2; //set sequence attewp.tasks[0].taskSequence = 2; //set task name attewp.tasks[0].taskName = "pm ws test addTask 2"; //set outline level attewp.tasks[1].outlineLevel = 3; //set sequence attewp.tasks[1].taskSequence = 3; //set task name attewp.tasks[1].taskName = "pm ws test addTask 3"; //create and add task scheduling bean to task. si = new scheduleInfo(); si.scheduledDuration = 4; si.scheduledEffort = 34; si.scheduledStart = new DateTime(2007, 2, 21); si.scheduledFinish = new DateTime(2007, 2, 22); si.constraintType = scheduleInfoConstraintType.assoonaspossible; attewp.tasks[0].schedulingBean = si; si = new scheduleInfo(); si.scheduledDuration = 4; si.scheduledEffort = 34; si.scheduledStart = new DateTime(2007, 2, 21); si.scheduledFinish = new DateTime(2007, 2, 22); si.constraintType = scheduleInfoConstraintType.assoonaspossible; attewp.tasks[1].schedulingBean = si; attewp.anchors = new taskAnchors(); attewp.anchors.topAnchor = new anchorType(); attewp.anchors.topAnchor.outLineLevel = 1; attewp.anchors.topAnchor.taskSequeceNumber = 0; attewp.anchors.bottomAnchor = new anchorType(); attewp.anchors.bottomAnchor.outLineLevel = 2; attewp.anchors.bottomAnchor.taskSequeceNumber = 1; //All other data is optional, but can be set up the same way as above. //Calling service layer api addedTasks = serviceProxy.addTasksToExistingWorkPlan(attewp); //Check the response and make sure we are getting it back ok for (int i = 0; i < addedTasks.Length; i++) { addTaskResultType addedTask = addedTasks[i]; Console.WriteLine("Task added: ID={0}; Sequence={1}", addedTask.taskId, addedTask.taskSequenceNumber); } Console.WriteLine(); Console.WriteLine("\nCalling searchTasks service..."); SearchTasks searchTasks = new SearchTasks(); searchTasks.searchPreferences = new searchTaskPreferenceType(); searchTasks.searchPreferences.projectNames = new string[] { cp.projectBean.projectName }; searchTasks.searchPreferences.maximumTasksToShow = 10; long[] searchTasksResponse = serviceProxy.searchTasks(searchTasks); //Check the response and make sure we are getting it back ok for (int i = 0; i < searchTasksResponse.Length; i++) { Console.WriteLine("SearchTasks returned: {0}", searchTasksResponse[i]); } Console.WriteLine(); Console.WriteLine("\nCalling readTasks service..."); taskType[] readTasksResponse = serviceProxy.readTasks(searchTasksResponse); //Check the response and make sure we are getting it back ok for (int i = 0; i < readTasksResponse.Length; i++) { taskType taskResponse = readTasksResponse[i]; Console.WriteLine("ReadTasks returned: Name={0}; Sequence={1}; Start={2}; Finish={3}", taskResponse.taskName, taskResponse.taskSequence, taskResponse.schedulingBean.scheduledStart, taskResponse.schedulingBean.scheduledFinish); } Console.WriteLine(); Console.WriteLine("\nDone. Press any key to exit."); Console.ReadKey(); }
public bool createTask(bool wakeToRun, string startTime, TaskActions[] tActions) { //string xmlFilename = "epg123Task.xml"; DateTime date = DateTime.Parse(string.Format("{0}/{1}/{2}T{3}:{4}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, startTime.Substring(0, 2), startTime.Substring(3, 2))); // create registration registrationInfoType registration = new registrationInfoType() { Author = "GaRyan2's epg123", Description = "Utility to update the Windows Media Center Electronic Program Guide by downloading guide information from Schedules Direct and importing the created .mxf file.", URI = "\\epg123_update" }; // create trigger triggersType triggers = new triggersType() { Items = new triggerBaseType[] { new calendarTriggerType() { id = "epg123 Daily Trigger", Item = new dailyScheduleType() { DaysInterval = 1, DaysIntervalSpecified = true }, StartBoundary = date, StartBoundarySpecified = true } } }; // create settings settingsType settings = new settingsType() { DisallowStartIfOnBatteries = false, StopIfGoingOnBatteries = false, ExecutionTimeLimit = "PT23H", Priority = 6, RestartOnFailure = new restartType() { Count = 5, Interval = "PT30M" }, StartWhenAvailable = true, //RunOnlyIfNetworkAvailable = true, WakeToRun = wakeToRun }; // create principal // Windows10 1607 Anniversary Update introduced a bug which only executes the first // task action unless running a service or possibly administrator? principalsType principals; if (isWindows10()) { principals = new principalsType() { Principal = new principalType() { id = @"NT AUTHORITY\NETWORKSERVICE", UserId = "S-1-5-20", RunLevel = runLevelType.HighestAvailable, RunLevelSpecified = true } }; } else { principals = new principalsType() { Principal = new principalType() { id = @"Author", LogonType = logonType.S4U, LogonTypeSpecified = true, RunLevel = runLevelType.HighestAvailable, RunLevelSpecified = true } }; } // create action(s) execType[] executions = new execType[tActions.Length]; for (int i = 0; i < tActions.Length; ++i) { executions[i] = new execType() { id = string.Format("epg123 Execution Action {0}", i + 1), Command = tActions[i].Path, Arguments = tActions[i].Arguments, WorkingDirectory = Helper.ExecutablePath }; } actionsType actions = new actionsType() { Exec = executions }; // build complete task taskType newTask = new taskType() { RegistrationInfo = registration, Triggers = triggers, Settings = settings, Principals = principals, Actions = actions, }; // serialize to xml and save to the drive try { using (StreamWriter stream = new StreamWriter(Helper.Epg123TaskXmlPath, false, Encoding.Unicode)) { XmlSerializer serializer = new XmlSerializer(typeof(taskType)); TextWriter writer = stream; serializer.Serialize(writer, newTask); return(true); } } catch (Exception ex) { Logger.WriteError(string.Format("Failed to create a {0} daily update task XML file. message: {1}", startTime, ex.Message)); } return(false); }
public void queryTask() { responseString = string.Empty; errorString = string.Empty; ProcessStartInfo startInfo = new ProcessStartInfo() { FileName = "schtasks.exe", Arguments = string.Format("/query /xml /tn \"{0}\"", taskName), UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true }; Process proc = Process.Start(startInfo); proc.OutputDataReceived += Proc_OutputDataReceived; proc.BeginOutputReadLine(); proc.ErrorDataReceived += Proc_ErrorDataReceived; proc.BeginErrorReadLine(); proc.WaitForExit(); if (exist = (proc.ExitCode == 0)) { existNoAccess = false; XmlSerializer serializer = new XmlSerializer(typeof(taskType)); using (StringReader reader = new StringReader(responseString)) { taskType task = (taskType)(serializer.Deserialize(reader)); actions = new TaskActions[task.Actions.Exec.Length]; for (int i = 0; i < task.Actions.Exec.Length; ++i) { actions[i].Path = task.Actions.Exec[i].Command; actions[i].Arguments = task.Actions.Exec[i].Arguments; } wake = task.Settings.WakeToRun; schedTime = task.Triggers.Items[0].StartBoundary.Date + task.Triggers.Items[0].StartBoundary.TimeOfDay; } responseString = string.Empty; startInfo.Arguments = string.Format("/query /fo csv /v /tn \"{0}\"", taskName); proc = Process.Start(startInfo); proc.OutputDataReceived += Proc_OutputDataReceived; proc.BeginOutputReadLine(); proc.WaitForExit(); if (!string.IsNullOrEmpty(responseString)) { statusString = string.Empty; string[] lines = responseString.Split('\n'); string[] columns = lines[0].Replace("\",\"", "|").TrimStart('\"').TrimEnd('\"').Split('|'); string[] values = lines[1].Replace("\",\"", "|").TrimStart('\"').TrimEnd('\"').Split('|'); for (int i = 0; i < columns.Length; ++i) { switch (columns[i]) { case "Status": statusString += string.Format("{0}.", values[i]); break; case "Last Run Time": DateTime dt; if (DateTime.TryParse(values[i], out dt) && (dt.Year > 2015)) { statusString += string.Format(" Last Run {0};", values[i]); } else { statusString += "The task has not yet run."; } break; case "Last Result": statusString += string.Format(" Exit: 0x{0}", int.Parse(values[i]).ToString("X8")); break; default: break; } } } } else if (errorString.ToLower().Contains("access")) // permission problem { existNoAccess = true; statusString = errorString; } else { statusString = "No task is scheduled to run."; } Logger.WriteVerbose(string.Format("Successfully queried the Task Scheduler for status. {0}", statusString)); return; }
public Task(taskType tasktype, Unit target, Texture2D unitImage) { unitTarget = target; type = tasktype; image = unitImage; }
public Task(taskType tasktype, City target) { cityTarget = target; type = tasktype; image = Resources.Load("Images/building") as Texture2D; }
public static void Main() { const int SIZE = 1000; int currentPosition = 0; string option; bool finished = false; taskType[] tasks = new taskType[SIZE]; do { Console.WriteLine("1. Add a new task"); Console.WriteLine("2. View all tasks"); Console.WriteLine("0. Exit"); option = Console.ReadLine(); switch (option) { case "1": if (currentPosition < SIZE - 1) { Console.Write("Enter the description:"); tasks[currentPosition].description = Console.ReadLine(); Console.Write("Enter the priority:"); tasks[currentPosition].priority = Convert.ToByte( Console.ReadLine()); Console.Write("Enter the day of the date:"); tasks[currentPosition].date.day = Convert.ToByte( Console.ReadLine()); Console.Write("Enter the month of the date:"); tasks[currentPosition].date.month = Convert.ToByte( Console.ReadLine()); Console.Write("Enter the year of the date:"); tasks[currentPosition].date.year = Convert.ToInt16( Console.ReadLine()); currentPosition++; } else { Console.WriteLine("Database full!"); } break; case "2": for (int i = 0; i < currentPosition; i++) { Console.WriteLine( tasks[i].priority + " - " + tasks[i].description + " (" + tasks[i].date.day + "/" + tasks[i].date.month + "/" + tasks[i].date.year + ")"); } break; case "0": finished = true; break; default: Console.WriteLine("Incorrect option"); break; } }while (!finished); Console.WriteLine("See you later!"); }
public bool CreateTask(bool wakeToRun, string startTime, TaskActions[] tActions) { //string xmlFilename = "epg123Task.xml"; var date = DateTime.Parse($"{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.Now.Day}T{startTime.Substring(0, 2)}:{startTime.Substring(3, 2)}"); // create registration var registration = new registrationInfoType() { Author = "GaRyan2's epg123", Description = "Utility to update the Windows Media Center Electronic Program Guide by downloading guide information from Schedules Direct and importing the created .mxf file.", URI = "\\epg123_update", SecurityDescriptor = "D:(A;;FRFWSDWDWO;;;BA)(A;;FRFWSDWDWO;;;SY)(A;;FRFWFXDTDCSDWD;;;NS)(A;;FXFR;;;AU)" }; // create trigger var triggers = new triggersType() { Items = new triggerBaseType[] { new calendarTriggerType() { id = "epg123 Daily Trigger", Item = new dailyScheduleType() { DaysInterval = 1, DaysIntervalSpecified = true }, StartBoundary = date, StartBoundarySpecified = true } } }; // create settings var settings = new settingsType() { DisallowStartIfOnBatteries = false, StopIfGoingOnBatteries = false, ExecutionTimeLimit = "PT23H", Priority = 6, RestartOnFailure = new restartType() { Count = 5, Interval = "PT30M" }, StartWhenAvailable = true, //RunOnlyIfNetworkAvailable = true, WakeToRun = wakeToRun }; // create principal // Windows10 1607 Anniversary Update introduced a bug which only executes the first // task action unless running a service or possibly administrator? // Also, network service does not have access to some registry keys in Win7 var principals = new principalsType() { Principal = new principalType() { id = @"SYSTEM", UserId = "S-1-5-18", RunLevel = runLevelType.HighestAvailable, RunLevelSpecified = true } }; // create action(s) var executions = new execType[tActions.Length]; for (var i = 0; i < tActions.Length; ++i) { executions[i] = new execType() { id = $"epg123 Execution Action {i + 1}", Command = tActions[i].Path, Arguments = tActions[i].Arguments.Replace("http:", "EPG:"), WorkingDirectory = Helper.ExecutablePath }; } var actions = new actionsType() { Exec = executions }; // build complete task var newTask = new taskType() { RegistrationInfo = registration, Triggers = triggers, Settings = settings, Principals = principals, Actions = actions, }; // serialize to xml and save to the drive try { using (var stream = new StreamWriter(Helper.Epg123TaskXmlPath, false, Encoding.Unicode)) { var serializer = new XmlSerializer(typeof(taskType)); TextWriter writer = stream; serializer.Serialize(writer, newTask); return(true); } } catch (Exception ex) { Logger.WriteError($"Failed to create a {startTime} daily update task XML file. message: {ex.Message}"); } return(false); }