static async Task TaskProducer(ConcurrentQueue<CustomTask> queue) { for (int i = 1; i <= 20; i++) { await Task.Delay(50); var workItem = new CustomTask {Id = i}; queue.Enqueue(workItem); Console.WriteLine("Task {0} has been posted", workItem.Id); } }
static async Task TaskProducer(ConcurrentStack<CustomTask> stack) { for (int i = 1; i <= 20; i++) { await Task.Delay(50); var workItem = new CustomTask { Id = i }; stack.Push(workItem); Console.WriteLine("Task {0} has been posted", workItem.Id); } }
static async Task TaskProducer(BlockingCollection<CustomTask> collection) { for (int i = 1; i <= 20; i++) { await Task.Delay(20); var workItem = new CustomTask { Id = i }; collection.Add(workItem); Console.WriteLine("Task {0} has been posted", workItem.Id); } collection.CompleteAdding(); }
public async void CreateToDoItem(IToDoItem todo) { var item = new CustomTask() { Name = todo.Name, UserId = todo.UserId, ToDoId = todo.ToDoId, IsCompleted = todo.IsCompleted }; items.Add(item as IToDoItem); isAdded = true; await fastClient.SyncToDoItemsAsync(item); }
public async Task <ActionResult> RemoveGroupTask(TravelGroupandUserTaskandItems model, int TaskId) { habiticatravelEntities HabiticaORM = new habiticatravelEntities(); CustomTask selectedTask = HabiticaORM.CustomTasks.Single(t => t.TaskId == TaskId && t.UserId == null); var selectedTaskItems = HabiticaORM.CustomTaskItems.Where(t => t.TaskId == TaskId).ToList(); if (selectedTaskItems.Count != 0) { foreach (var item in selectedTaskItems) { HabiticaORM.CustomTaskItems.Remove(item); } } HabiticaORM.CustomTasks.Remove(selectedTask); List <TravelGroupUser> GroupUsers = new List <TravelGroupUser>(); GroupUsers = HabiticaORM.TravelGroupUsers.Where(u => u.TravelGroupId == model.TravelGroupandUser.TravelGroup.TravelGroupId).ToList(); foreach (TravelGroupUser user in GroupUsers) { HabiticaUser MyHabUser = HabiticaORM.HabiticaUsers.Single(u => u.UserId == user.UserId); CustomTask selectedUserTask = HabiticaORM.CustomTasks.Single(t => t.TravelGroupId == model.TaskAndItems.CustomTask.TravelGroupId && t.UserId == user.UserId && t.TaskName == model.TaskAndItems.CustomTask.TaskName); var selectedUserTaskItems = HabiticaORM.CustomTaskItems.Where(t => t.TaskId == selectedUserTask.TaskId).ToList(); if (selectedUserTaskItems.Count != 0) { foreach (var item in selectedUserTaskItems) { var ItemConfirm = (JObject)JObject.FromObject(await HabiticaHTTP.DeleteChecklistItem(selectedUserTask, item, MyHabUser)); HabiticaORM.CustomTaskItems.Remove(item); } } var ItemConfirm2 = (JObject)JObject.FromObject(await HabiticaHTTP.DeleteATask(selectedUserTask, MyHabUser)); HabiticaORM.CustomTasks.Remove(selectedUserTask); } HabiticaORM.SaveChanges(); return(RedirectToAction("Index", "Home")); }
public async void RunMainTask_Failed() { _taskProviderManager.Setup(p => p.InvokeTaskProvider(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync((string taskProviderDll, string taskProviderArgs, string secretTaskProviderArgs) => new Dictionary <string, object> { { "errorMessage", "error-message" } }); var config = new Dictionary <string, string>(); var task = new CustomTask(_projectService.Object, _externalServiceService.Object, _externalServiceTypeService.Object, _providerService.Object, _taskProviderManager.Object, _logger.Object); task.SetConfig(config, "working"); task.Provider = "FakeGenericTaskProvider"; var result = await task.RunMainTask(new Dictionary <string, string>()); Assert.False(result.IsSuccess); Assert.Equal("error-message", result.ErrorMessage); }
public async void RunMainTask_Success() { _pluginManager.Setup(p => p.InvokeTaskProvider(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync((string pluginDll, string pluginArgs, string secretPluginArgs) => new Dictionary <string, object> { { "successMessage", "success" } }); var config = new Dictionary <string, string>(); var task = new CustomTask(_projectService.Object, _externalServiceService.Object, _externalServiceTypeService.Object, _providerService.Object, _pluginManager.Object, _logger.Object); task.SetConfig(config, "working"); task.Provider = "FakeGenericTaskProvider"; var result = await task.RunMainTask(new Dictionary <string, string>()); Assert.True(result.IsSuccess); Assert.Equal("success", result.TaskRemarks); }
public ActionResult EditGroupCustomTask(TravelGroupandUserTaskandItems model, int TaskId) { habiticatravelEntities HabiticaORM = new habiticatravelEntities(); var CurrentTaskItems = new List <CustomTaskItem>(HabiticaORM.CustomTasks.Find(TaskId).CustomTaskItems.ToList()); CustomTask TaskToEdit = HabiticaORM.CustomTasks.Find(TaskId); TaskAndItems TaskAndItemToEdit = new TaskAndItems { CustomTask = TaskToEdit, CustomTaskItem = CurrentTaskItems }; ViewBag.TaskToBeEdited = TaskToEdit; return(View(TaskAndItemToEdit)); }
/// <summary> /// Starts the given Task when this Task ended successfully. /// </summary> /// <param name="that">The that.</param> /// <param name="followingTask">The task to start.</param> /// <param name="target">The DispatcherBase to start the following task on.</param> /// <returns> /// This task. /// </returns> public static CustomTask Then(this CustomTask that, CustomTask followingTask, CustomTaskDispatcherBase target) { that.WhenFailed(followingTask.Abort); that.WhenSucceeded(() => { if (target != null) { followingTask.Run(target); } else if (CustomThread.CurrentThread is TaskWorker) { followingTask.Run(((TaskWorker)CustomThread.CurrentThread).TaskDistributor); } else { followingTask.Run(); } }); return(that); }
//产生任务 private static async Task TaskProducer(ConcurrentQueue <CustomTask> queue) { int len = 1; while (len != 100) { await Task.Delay(50); var workItem = new CustomTask { Id = len }; queue.Enqueue(workItem); Console.WriteLine("成功生产对象CustomTask,获取Id ={0}", workItem.Id); len++; if (queue.Count > 20) { await Task.Delay(500); } } }
public ActionResult Post([FromForm] UploadTaskModel task) { try { if (_fileService.UploadFile(task.FileName, task.FormFile, _env, _host, out string path)) { CustomTask newTask = new CustomTask(path, task.Text); TasksServiceSingleton.Instance.AddTask(newTask); return(StatusCode(StatusCodes.Status201Created, newTask)); } else { //file name already exist return(Conflict("File alreay exist")); } } catch (Exception e) { return(StatusCode(StatusCodes.Status500InternalServerError, "Error in file uploading")); } }
static void Main(string[] args) { string fileName = string.Empty; if (args != null && args.Length == 1) { fileName = args[1]; } else { Console.Write("Input File Path: "); fileName = Console.ReadLine(); } CustomTask task = new CustomTask(fileName); task.ExecuteInSequence(); Console.Write("Press any key to exit..."); Console.ReadKey(); }
public async Task <IActionResult> Create([FromBody] CreateCustomTaskRequest customTaskRequest) { var customTask = new CustomTask { Title = customTaskRequest.Title, Description = customTaskRequest.Description, Importance = customTaskRequest.Importance, DueDate = customTaskRequest.DueDate, IsCompleted = customTaskRequest.IsCompleted, UserId = HttpContext.GetUserId() }; await _customTaskService.CreateCustomTaskAsync(customTask); var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}"; var locationUri = baseUrl + "/" + ApiRoutes.CustomTask.Get.Replace("customTaskTitle", customTask.Title); var response = new CustomTaskResponse { Title = customTask.Title, Description = customTask.Description, Importance = customTask.Importance, DueDate = customTask.DueDate, IsCompleted = customTask.IsCompleted }; return(Created(locationUri, response)); }
/// <summary> /// Performs the given Func sequential for each element in the enumerable. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <typeparam name="T"></typeparam> /// <param name="that">The that.</param> /// <param name="action">The Func to perform for each element.</param> /// <param name="target">The TaskDistributor instance on which the operation should perform.</param> /// <returns> /// IEnumerable of created tasks. /// </returns> public static IEnumerable <CustomTask <TResult> > SequentialForEach <TResult, T>(this IEnumerable <T> that, Func <T, TResult> action, TaskDistributor target) { var result = new List <CustomTask <TResult> >(); CustomTask lastTask = null; foreach (var element in that) { var tmp = element; var task = CustomTask.Create(() => action(tmp)); if (lastTask == null) { task.Run(target); } else { lastTask.WhenEnded(() => task.Run(target)); } lastTask = task; result.Add(task); } return(result); }
public async Task <ActionResult> SaveCustomTaskChanges(TaskAndItems NewTaskAndItems) { var HabiticaORM = new habiticatravelEntities(); string UserId = User.Identity.GetUserId(); HabiticaUser MyHabUser = HabiticaORM.HabiticaUsers.Single(u => u.UserId == UserId); int TaskId = NewTaskAndItems.CustomTask.TaskId; CustomTask DBTask = HabiticaORM.CustomTasks.Find(TaskId); List <CustomTaskItem> DBItemsList = new List <CustomTaskItem>(); if (HabiticaORM.CustomTasks.Find(TaskId).CustomTaskItems != null) { DBItemsList = HabiticaORM.CustomTasks.Find(TaskId).CustomTaskItems.ToList(); } CustomTask MyTask = NewTaskAndItems.CustomTask; List <CustomTaskItem> MyItemsList = new List <CustomTaskItem>(); if (NewTaskAndItems.CustomTaskItem != null && DBItemsList.Count != 0) { foreach (CustomTaskItem T in NewTaskAndItems.CustomTaskItem) { MyItemsList.Add(T); HabiticaORM.Entry(HabiticaORM.CustomTaskItems.Find(T.TaskItemsId)).CurrentValues.SetValues(T); var ItemConfirm = (JObject)JObject.FromObject(await HabiticaHTTP.PutUpdateChecklistItem(T, MyHabUser, MyTask)); } } MyTask.CustomTaskItems = MyItemsList; HabiticaORM.Entry(DBTask).CurrentValues.SetValues(MyTask); var ItemConfirm2 = (JObject)JObject.FromObject(await HabiticaHTTP.PutUpdateTask(MyTask, MyHabUser)); HabiticaORM.SaveChanges(); return(RedirectToAction("Index", "Home")); }
public void RunSubSequence() { Sequence.Execute("Test sub sequence 1.1", () => { SqlTask.ExecuteNonQuery($"Sql #2", "Select 1 as test"); SqlTask.ExecuteNonQuery($"Sql #3", "Select 1 as test"); LogTask.Warn("Warn message #1"); }); Sequence.Execute("Test sub sequence 1.2", () => { SqlTask.ExecuteNonQuery($"Sql #4", "Select 1 as test"); }); Sequence.Execute("Test sub sequence 1.3", () => { Sequence.Execute("Test sub sequence 2.1", () => { Sequence.Execute("Test sub sequence 3.1", () => { SqlTask.ExecuteNonQuery($"Sql #5", "Select 1 as test"); SqlTask.ExecuteNonQuery($"Sql #6", "Select 1 as test"); LogTask.Warn("Warn message #2"); }); CustomTask.Execute($"Custom #1", () => {; }); SqlTask.ExecuteNonQuery($"Sql #7", "Select 1 as test"); }); Sequence.Execute("Test sub sequence 2.2", () => { CustomTask.Execute($"Custom #2", () => {; }); SqlTask.ExecuteNonQuery($"Sql #7", "Select 1 as test"); }); Sequence.Execute("Test sub sequence 2.3", () => { SqlTask.ExecuteNonQuery($"Sql #8", "Select 1 as test"); CustomTask.Execute($"Custom #2", () => {; }); Sequence.Execute("Test sub sequence 3.3", () => { SqlTask.ExecuteNonQuery($"Sql #9", "Select 1 as test"); SqlTask.ExecuteNonQuery($"Sql #10", "Select 1 as test"); LogTask.Error("Error message"); }); }); }); CustomTask.Execute($"Custom #3", () => {; }); }
private void SubmitWorkTimeTask(IfUser Submitter, IfUser Handler) { string strName = "填报工时_" + Handler.Name + "_" + DateTime.Today.ToShortDateString(); if (mainDataSet.GetTaskItem(strName) != null) { ShowStatus("Task: " + strName + " already exists."); return; } DateTime dDate = DateTime.Now + new TimeSpan(3, 0, 0, 0); CustomTask newTask = new CustomTask(strName, DateTime.Now, dDate, strName); TaskType workTime = mainDataSet.GetTypeItem("填报工时"); if (workTime == null) { workTime = new TaskType("填报工时", 70); } newTask.UpdateRealtion(workTime, Submitter, Handler, mainDataSet.GetQlevelItem("Q3")); mainDataSet.InsertCustomTask(newTask, workTime); mainDataSet.UpdateRuntimeDataSet(); }
static void Main(string[] args) { CustomTask antecedent = new CustomTask( () => { throw new Exception("Unhandled"); }); antecedent.ContinueWith( (predTask) => { ((CustomTask)predTask).PerformRollback(); }, TaskContinuationOptions.OnlyOnFaulted); antecedent.Start(); try { antecedent.Wait(); } catch (AggregateException ex) { } }
/// <summary> /// The given Action will be performed when the task ends. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="task">The task.</param> /// <param name="action">The action to perform.</param> /// <returns> /// This task. /// </returns> public static CustomTask <T> WhenEnded <T>(this CustomTask <T> task, Action <CustomTask <T> > action) { return(task.WhenEnded(action, null)); }
/// <summary> /// The given Action will be performed when the task ends. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="task">The task.</param> /// <param name="action">The action to perform.</param> /// <returns> /// This task. /// </returns> public static CustomTask <T> WhenEnded <T>(this CustomTask <T> task, Action action) { return(task.WhenEnded(t => action(), null)); }
/// <summary> /// Starts the given Task when the tasks ended successfully. /// </summary> /// <param name="that">The that.</param> /// <param name="followingTask">The task to start.</param> /// <param name="target">The DispatcherBase to start the following task on.</param> /// <returns> /// The tasks. /// </returns> public static IEnumerable <CustomTask> Then(this IEnumerable <CustomTask> that, CustomTask followingTask, CustomTaskDispatcherBase target) { var remaining = that.Count(); var syncRoot = new object(); foreach (var task in that) { task.WhenFailed(() => { if (followingTask.ShouldAbort) { return; } followingTask.Abort(); }); task.WhenSucceeded(() => { if (followingTask.ShouldAbort) { return; } lock (syncRoot) { remaining--; if (remaining != 0) { return; } if (target != null) { followingTask.Run(target); } else if (CustomThread.CurrentThread is TaskWorker) { followingTask.Run(((TaskWorker)CustomThread.CurrentThread).TaskDistributor); } else { followingTask.Run(); } } }); } return(that); }
/// <summary> /// Converts this Task. /// </summary> /// <param name="that"></param> /// <returns>The converted task.</returns> public static CustomTask <T> As <T>(this CustomTask that) { return((CustomTask <T>)that); }
/// <summary> /// Starts this Task when the other Task ended successfully. /// </summary> /// <param name="that">The that.</param> /// <param name="taskToWaitFor">The task to wait for.</param> /// <param name="target">The DispatcherBase to start this task on.</param> /// <returns> /// This task. /// </returns> public static CustomTask Await(this CustomTask that, CustomTask taskToWaitFor, CustomTaskDispatcherBase target) { taskToWaitFor.Then(that, target); return(that); }
private void SaveBtn_Click(object sender, EventArgs e) { try { DateTime start = StartDateTimePicker.Value; string temp = "0"; string minute_temp = "0"; // store temp time int hour = 0; // parsed hour int minute = 0; bool reminderset = false; // To Check if User Wants a Reminder or Not if (PlaceCombo.SelectedItem == null) // Task Has no associated place { if (ReminderHourCombo.SelectedItem != null) { if (!ReminderHourCombo.SelectedItem.Equals("No Alarm")) { temp = ReminderHourCombo.SelectedItem.ToString(); // parse the hour reminderset = true; } else { reminderset = false; } } if (ReminderMinutesCombo.SelectedItem != null) { if (!ReminderMinutesCombo.SelectedItem.Equals("No Alarm")) { minute_temp = ReminderMinutesCombo.SelectedItem.ToString(); reminderset = true; } else { reminderset = false; } } hour = int.Parse(temp); // convert hour to int minute = int.Parse(minute_temp); // convert minutes to int DateTime due = new DateTime(DueDateTimePicker.Value.Year, DueDateTimePicker.Value.Month, DueDateTimePicker.Value.Day, hour, minute, 0); // pass the integer hour as parameter to constructor task = new Task(); task.Subject = SubjectCombo.Text; task.Complete = complete; task.StartDate = StartDateTimePicker.Value; task.DueDate = due; if (reminderset == true) { task.ReminderTime = due; } OutlookSession os = new OutlookSession(); TaskFolder folder = os.Tasks; if (SubjectCombo.Text.ToString() != "") { folder.Items.Add(task); // save to folder MessageBox.Show("Task Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2); } else { MessageBox.Show("Subject Can't Be Empty"); } } else //Task has an associated place { if (ReminderHourCombo.SelectedItem != null) { if (!ReminderHourCombo.SelectedItem.Equals("No Alarm")) { temp = ReminderHourCombo.SelectedItem.ToString(); // parse the hour reminderset = true; } else { reminderset = false; } } if (ReminderMinutesCombo.SelectedItem != null) { if (!ReminderMinutesCombo.SelectedItem.Equals("No Alarm")) { minute_temp = ReminderMinutesCombo.SelectedItem.ToString(); reminderset = true; } else { reminderset = false; } } hour = int.Parse(temp); // convert hour to int minute = int.Parse(minute_temp); // convert minutes to int foreach (Place p in place_list) { if (p.PlaceNameProp.Equals(PlaceCombo.SelectedItem.ToString())) { Selected_Place_ID = p.PlaceIDProp; } } hour = int.Parse(temp); // convert hour to int minute = int.Parse(minute_temp); // convert minutes to int DateTime due = new DateTime(DueDateTimePicker.Value.Year, DueDateTimePicker.Value.Month, DueDateTimePicker.Value.Day, hour, minute, 0); // pass the integer hour as parameter to constructor tsk = new CustomTask(SubjectCombo.Text.ToString(), complete, start, due, reminderset , due, Selected_Place_ID); if (SubjectCombo.Text != null) { tsk.SaveTaskToOutlookFolder(); // save to folder tsk.SaveTaskToDbase(tsk); } else { MessageBox.Show("Subject Can't Be Empty"); } ////////////////////////////////////////////////// Save to Dbase // set selected place id to Task Object MessageBox.Show("Task Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); MessageBox.Show("Error Saving Task...Please Retry", "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button2); } SubjectCombo.Text = null; ReminderHourCombo.Text = null; PlaceCombo.Text = null; }
public static async Task <dynamic> PostNewChecklistItem(CustomTaskItem item, HabiticaUser user, CustomTask task) { string str1 = "checklist"; try { return(await "https://habitica.com/api/v3/tasks/" .WithHeaders(new { x_api_user = user.Uuid, x_api_key = user.ApiToken }) .AppendPathSegment(task.HabiticaTaskId, true) .AppendPathSegment(str1, true) .PostJsonAsync(new { text = item.ItemName, }) .ReceiveJson()); } catch (FlurlHttpException ex) { return(ex.GetResponseJson()); } }
/// <summary> /// Invokes the given action with the set result of the task when the task succeeded. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="task">The task.</param> /// <param name="action">The action to perform.</param> /// <param name="actionTarget">The action target.</param> /// <returns> /// This task. /// </returns> public static CustomTask <T> OnResult <T>(this CustomTask <T> task, Action <T> action, CustomTaskDispatcherBase actionTarget) { return(task.WhenSucceeded(t => action(t.Result), actionTarget)); }
/// <summary> /// Invokes the given action with the set result of the task when the task succeeded. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="task">The task.</param> /// <param name="action">The action to perform.</param> /// <returns> /// This task. /// </returns> public static CustomTask <T> OnResult <T>(this CustomTask <T> task, Action <T> action) { return(task.OnResult(action, null)); }
/// <summary> /// Sets the name of the task /// </summary> public static CustomTask WithName(this CustomTask task, string name) { task.Name = name; return(task); }
/// <summary> /// Invokes the given action with the set result of the task when the task succeeded. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="task">The task.</param> /// <param name="action">The action to perform.</param> /// <param name="target">The DispatcherBase to perform the action on.</param> /// <returns> /// This task. /// </returns> public static CustomTask OnResult <T>(this CustomTask task, Action <T> action, CustomTaskDispatcherBase target) { return(task.WhenSucceeded(t => action((T)t.RawResult), target)); }
/// <summary> /// Invokes the given action with the set result of the task when the task succeeded. /// </summary> /// <param name="task">The task.</param> /// <param name="action">The action to perform.</param> /// <returns> /// This task. /// </returns> public static CustomTask OnResult(this CustomTask task, Action <object> action) { return(task.OnResult(action, null)); }
/// <summary> /// The given Action will be performed when the task ends. /// </summary> /// <param name="task">The task.</param> /// <param name="action">The action to perform.</param> /// <returns> /// This task. /// </returns> public static CustomTask WhenEnded(this CustomTask task, Action action) { return(task.WhenEnded(t => action())); }
/// <summary> /// The given Action will be performed when the task ends. /// </summary> /// <param name="task">The task.</param> /// <param name="action">The action to perform.</param> /// <returns> /// This task. /// </returns> public static CustomTask WhenEnded(this CustomTask task, Action <CustomTask> action) { return(task.WhenEnded(action, null)); }
/// <summary> /// Starts this Task when the other Task ended successfully. /// </summary> /// <param name="that">The that.</param> /// <param name="taskToWaitFor">The task to wait for.</param> /// <returns> /// This task. /// </returns> public static CustomTask Await(this CustomTask that, CustomTask taskToWaitFor) { taskToWaitFor.Then(that); return(that); }
public static async Task <dynamic> PutUpdateChecklistItem(CustomTaskItem item, HabiticaUser user, CustomTask task) { try { return(await $"https://habitica.com/api/v3/tasks/{task.HabiticaTaskId}/checklist/{item.HabiticaItemId}" .WithHeaders(new { x_api_user = user.Uuid, x_api_key = user.ApiToken }) .PostJsonAsync(new { text = item.ItemName, }) .ReceiveJson()); } catch (FlurlHttpException ex) { return(ex.GetResponseJson()); } }
/// <summary> /// Sets the name of the task /// </summary> public static CustomTask <T> WithName <T>(this CustomTask <T> task, string name) { task.Name = name; return(task); }