예제 #1
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,TaskType,Comment,TaskTime,TaskLogId")] TaskEntry taskEntry)
        {
            if (id != taskEntry.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(taskEntry);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TaskEntryExists(taskEntry.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["TaskLogId"] = new SelectList(_context.TaskLog, "Id", "Id", taskEntry.TaskLogId);
            return(View(taskEntry));
        }
예제 #2
0
        private void RunNextTaskIfAvailableAsync(TaskEntry task)
        {
            TaskEntryQueue.DequeueResult queueEntry;
            lock (_lock) {
                if (task == null)
                {
                    // If there is a running task, bail, because we will be called again when the running task
                    // finishes.
                    if (_runningTask != null)
                    {
                        return;
                    }
                }
                else
                {
                    Invariants.Assert(ReferenceEquals(_runningTask, task));
                }
                queueEntry   = _taskQueue.Dequeue(_dateTimeProvider.UtcNow);
                _runningTask = queueEntry.TaskEntry; // May be null if only pdelayed tasks
            }

            if (queueEntry.TaskEntry != null)
            {
                // If there is a task available, run it
                RunTaskAsync(queueEntry.TaskEntry);
            }
            else if (queueEntry.HasPending)
            {
                // Run this method in a little while if there are pending tasks
                _customThreadPool.RunAsync(() => RunNextTaskIfAvailableAsync(null), TimeSpan.FromMilliseconds(50));
            }
        }
예제 #3
0
        public async Task <bool> AddTaskEntry(TaskEntry taskEntry)
        {
            try
            {
                Logger.Write("--- ADDING NEW TASK ENTRY (BackendService - AddTaskEntry) ---");

                HttpResponseMessage response = await client.PostAsJsonAsync("api/taskentries", taskEntry);

                if (!response.IsSuccessStatusCode)
                {
                    System.Windows.MessageBox.Show("ERROR:  " + response.StatusCode.ToString() + Environment.NewLine +
                                                   Environment.NewLine +
                                                   "Content        : " + response.Content + Environment.NewLine +
                                                   "RequestMessage : " + response.RequestMessage + Environment.NewLine +
                                                   "ReasonPhrase   : " + response.ReasonPhrase, "Adding new Task Entry in database");

                    Logger.Write("!ERROR occurred while adding new task entry (BackendService - AddTaskEntry) : " + Environment.NewLine +
                                 response.ReasonPhrase.ToString());

                    return(false);
                }
                else
                {
                    TaskEntry_maxIndex += 1;
                    return(true);
                }
            }
            catch (Exception e)
            {
                Logger.Write("!ERROR occurred while adding new task entry (BackendService - AddTaskEntry) : " + Environment.NewLine +
                             e.ToString());
                return(false);
            }
        }
예제 #4
0
        public void Enqueue(StagedTask stagedTask)
        {
            var entry = new TaskEntry(stagedTask, ++_sequence);

            if (_first == null)
            {
                _first = entry;
                _last  = entry;
                _count = 1;
            }
            else
            {
                _last.Next = entry;
                _last      = entry;
                _count++;
            }
            // re-initialize already completed queues
            for (var stage = 0; stage <= _maxStage; stage++)
            {
                if (_orderedStage[stage] && _byOrderedStageLast[stage] == null)
                {
                    _byOrderedStageLast[stage] = entry;
                }
            }

            SetEntryCorrelation(entry, stagedTask.InitialCorrelationId);
            EnqueueForStage(entry, 0);
        }
예제 #5
0
        /// <summary>
        /// Creates the new task.
        /// </summary>
        /// <param name="taskDefinition">The task definition.</param>
        /// <returns></returns>
        public Guid CreateNewTask(ITaskDefinitionCreate taskDefinition)
        {
            Guid result;

            using (var transaction = uow.BeginTransaction())
            {
                var parentJobEntry = engineRepository.GetJobById(Guid.Parse(taskDefinition.ParentJobId));
                var taskEntity     = new TaskEntry
                {
                    Description = taskDefinition.Description,
                    FailIfAnyElementHasError   = taskDefinition.FailIfAnyElementHasError,
                    FailIfAnyElementHasWarning = taskDefinition.FailIfAnyElementHasWarning,
                    IsEnabled = taskDefinition.IsEnabled,
                    Name      = taskDefinition.Name,
                    ParentJob = parentJobEntry,
                    Position  = parentJobEntry.Tasks.Select(e => e.Position).DefaultIfEmpty().Max() + 1
                };
                parentJobEntry.Tasks.Add(taskEntity);

                engineRepository.CreateTask(taskEntity);
                engineRepository.UpdateJob(parentJobEntry);

                result = taskEntity.Id;
            }

            return(result);
        }
        public async Task <List <TaskEntry> > GetDBTaskEntryFromPipelineAsync(int limit = 1)
        {
            var outputcmd = _GetTasksInPipelineSQL(limit);

            DBConnection.Open();

            var output = new List <TaskEntry>();

            using (var reader = await outputcmd.ExecuteReaderAsync())
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        var entry = new TaskEntry()
                        {
                            Input     = (TaskEntryInput)JsonSerializer.DeserializeFromJson((string)reader["input"]),
                            Task      = (string)reader["task"],
                            Timestamp = (long)reader["timestamp"],
                            GlobalId  = (string)reader["guid"]
                        };
                        output.Add(entry);
                    }
                }
            }

            DBConnection.Close();
            Logger.LogInformation("Task pipeline (GET) for individual element. {output.count} elements were returned.", output.Count);
            return(output);
        }
예제 #7
0
        public async Task <IActionResult> Edit(int id, [Bind("TaskEntryId,DateCreated,DateDue,TaskEntryDescription,TaskStatusId,TaskTypeId,UserId,DateNextAction")] TaskEntry taskEntry)
        {
            if (id != taskEntry.TaskEntryId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(taskEntry);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TaskEntryExists(taskEntry.TaskEntryId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["TaskStatusId"] = new SelectList(_context.TaskStatuses, "TaskStatusId", "TaskStatusDescription", taskEntry.TaskStatusId);
            ViewData["TaskTypeId"]   = new SelectList(_context.TaskTypes, "TaskTypeId", "TaskTypeDescription", taskEntry.TaskTypeId);
            ViewData["UserId"]       = new SelectList(_context.Users, "UserId", "UserName", taskEntry.UserId);
            return(View(taskEntry));
        }
예제 #8
0
        public async Task <ActionResult <TaskEntry> > PostTaskEntry(TaskEntry taskEntry)
        {
            _context.TaskEntry.Add(taskEntry);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetTaskEntry", new { id = taskEntry.Id }, taskEntry));
        }
예제 #9
0
        public async Task <IActionResult> Create(int id, [Bind("Id,TaskType,Comment,TaskTime,TaskLogId")] TaskEntry taskEntry)
        {
            if (ModelState.IsValid)
            {
                if (User.IsInRole("Employee"))
                {
                    var userId   = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
                    var employee = _context.Employee.Where(c => c.ApplicationUserId == userId).FirstOrDefault();
                    var taskLog  = _context.TaskLog.Where(t => t.ApplicationUserId == userId).LastOrDefault();
                    taskEntry.TaskLogId = taskLog.Id;
                    _context.Add(taskEntry);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                if (User.IsInRole("Manager"))
                {
                    var userId  = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
                    var manager = _context.Manager.Where(c => c.ApplicationUserId == userId).FirstOrDefault();
                    var taskLog = _context.TaskLog.Where(t => t.ApplicationUserId == userId).LastOrDefault();
                    taskEntry.TaskLogId = taskLog.Id;
                    _context.Add(taskEntry);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            ViewData["TaskLogId"] = new SelectList(_context.TaskLog, "Id", "Id");
            return(View(taskEntry));
        }
예제 #10
0
 private void RemoveCompleted()
 {
     while (_first != null && _first.Completed)
     {
         var task = _first;
         _first = task.Next;
         if (_first == null)
         {
             _last = null;
         }
         _count--;
         if (task.BusyCorrelationId != null)
         {
             var nextByCorrelation = task.NextByCorrelation;
             if (nextByCorrelation != null)
             {
                 if (nextByCorrelation.PreviousByCorrelation != task)
                 {
                     throw new Exception("Invalid linked list by correlation");
                 }
                 task.NextByCorrelation = null;
                 nextByCorrelation.PreviousByCorrelation = null;
                 if (!_orderedStage[nextByCorrelation.ReadForStage])
                 {
                     EnqueueForStage(nextByCorrelation, nextByCorrelation.ReadForStage);
                 }
             }
             else
             {
                 // remove the last one
                 _correlationLastEntries.Remove(task.BusyCorrelationId);
             }
         }
     }
 }
예제 #11
0
        private void RunTaskAsync(TaskEntry task)
        {
            Invariants.Assert(ReferenceEquals(_runningTask, task));
            _customThreadPool.RunAsync(() => {
                Invariants.Assert(ReferenceEquals(_runningTask, task));
                try {
                    if (Logger.IsDebugEnabled)
                    {
                        Logger.LogDebug("Queue \"{0}\": Executing task \"{1}\" after waiting for {2:n0} msec",
                                        _description,
                                        task.Id.Description,
                                        (_dateTimeProvider.UtcNow - task.EnqueuedDateTimeUtc).TotalMilliseconds);
                    }

                    task.StopWatch.Start();
                    task.Action(_taskCancellationTracker.NewToken());
                } finally {
                    Invariants.Assert(ReferenceEquals(_runningTask, task));
                    task.StopWatch.Stop();
                    if (Logger.IsDebugEnabled)
                    {
                        Logger.LogDebug("Queue \"{0}\": Executed task \"{1}\" in {2:n0} msec",
                                        _description,
                                        task.Id.Description,
                                        task.StopWatch.ElapsedMilliseconds);
                    }
                    RunNextTaskIfAvailableAsync(task);
                }
            });
        }
예제 #12
0
        public async Task <IActionResult> PutTaskEntry(int id, TaskEntry taskEntry)
        {
            if (id != taskEntry.Id)
            {
                return(BadRequest());
            }

            _context.Entry(taskEntry).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TaskEntryExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
예제 #13
0
        public static TimeSpanHMS CalculateTimespanHMS(TaskEntry taskEntry)
        {
            // Initialize
            TimeSpan    timeSpan    = new TimeSpan(0, 0, 0);
            TimeSpanHMS timeSpanHMS = new TimeSpanHMS();

            try
            {
                // Calculate sum of all target Time Entries
                if (taskEntry.TimeEntries != null)
                {
                    foreach (TimeEntry timeEntry in taskEntry.TimeEntries)
                    {
                        timeSpan = timeSpan + timeEntry.Duration;
                    }
                }

                // Assign resulting TimeSpan data to correct object
                timeSpanHMS = new TimeSpanHMS(timeSpan);
            }
            catch (Exception e)
            {
                Logger.Write("!ERROR occurred while trying to CalculateTimespanHMS: " + Environment.NewLine +
                             e.ToString());
            }

            return(timeSpanHMS);
        }
예제 #14
0
        private void SetEntryCorrelation(TaskEntry entry, object newCorrelationId)
        {
            if (!Equals(entry.BusyCorrelationId, newCorrelationId))
            {
                if (entry.ReadForStage != -1 && !_orderedStage[entry.ReadForStage])
                {
                    throw new InvalidOperationException("Cannot set busy correlation id at non-ordered stage");
                }
                if (entry.BusyCorrelationId != null)
                {
                    throw new InvalidOperationException("Busy correlation id has been already set");
                }

                entry.BusyCorrelationId = newCorrelationId;
                if (newCorrelationId != null)
                {
                    TaskEntry lastEntry;
                    if (_correlationLastEntries.TryGetValue(newCorrelationId, out lastEntry))
                    {
                        if (entry.Sequence < lastEntry.Sequence)
                        {
                            //NOTE: should never happen as we require ordered stage or initialization
                            throw new InvalidOperationException("Cannot inject task correlation id before another task with the same correlation id");
                        }
                        lastEntry.NextByCorrelation = entry;
                        entry.PreviousByCorrelation = lastEntry;
                        _correlationLastEntries[newCorrelationId] = entry;
                    }
                    else
                    {
                        _correlationLastEntries.Add(newCorrelationId, entry);
                    }
                }
            }
        }
예제 #15
0
        public void Enqueue(TaskId id, Action task)
        {
            var entry = new TaskEntry {
                Id = id,
                EnqueuedDateTimeUtc = _dateTimeProvider.UtcNow,
                Action    = task,
                StopWatch = new Stopwatch(),
            };

            Logger.LogInfo("Queue \"{0}\": Enqueing task \"{1}\"", _description, entry.Id.Description);

            bool isFirstTask;

            lock (_lock) {
                if (_runningTask == null)
                {
                    _runningTask = entry;
                    isFirstTask  = true;
                }
                else
                {
                    _tasks.Enqueue(entry);
                    isFirstTask = false;
                }
            }

            if (isFirstTask)
            {
                RunTaskAsync(entry);
            }
        }
예제 #16
0
        public TaskEditPage()
        {
            InitializeComponent();

            // Set the BindingContext of the page to a new Note.
            BindingContext = new TaskEntry();
        }
예제 #17
0
파일: SleepSets.cs 프로젝트: p-org/PSharp
        /// <summary>
        /// Update the sleep sets for the top operation on the stack.
        /// This will look at the second from top element in the stack
        /// and copy forward the sleep set, excluding tasks that are dependent
        /// with the executed operation.
        /// </summary>
        public static void UpdateSleepSets(Stack stack)
        {
            if (stack.GetNumSteps() <= 1)
            {
                return;
            }

            TaskEntryList prevTop      = stack.GetSecondFromTop();
            TaskEntry     prevSelected = prevTop.List[prevTop.GetSelected()];

            TaskEntryList currTop = stack.GetTop();

            // For each task on the top of stack (except previously selected task and new tasks):
            //   if task was slept previously
            //   and task's op was independent with selected op then:
            //     the task is still slept.
            //   else: not slept.
            for (int i = 0; i < prevTop.List.Count; i++)
            {
                if (i == prevSelected.Id)
                {
                    continue;
                }

                if (prevTop.List[i].Sleep && !IsDependent(prevTop.List[i], prevSelected))
                {
                    currTop.List[i].Sleep = true;
                }
            }
        }
예제 #18
0
 private void CompleteTaskProcessing(TaskEntry entry, int readyForStage, object newCorrelationId)
 {
     if (!entry.Busy)
     {
         throw new InvalidOperationException("Task was not in progress");
     }
     entry.Busy = false;
     SetEntryCorrelation(entry, newCorrelationId);
     if (readyForStage < 0)
     {
         MarkCompletedTask(entry);
         if (entry == _first)
         {
             RemoveCompleted();
         }
     }
     else
     {
         EnqueueForStage(entry, readyForStage);
     }
     if (EnsureTickPending != null)
     {
         EnsureTickPending();
     }
 }
예제 #19
0
 private void AdvanceStage(int stage, TaskEntry entry)
 {
     if (!_orderedStage[stage])
     {
         if (_byUnorderedStageFirst[stage].Entry != entry)
         {
             throw new ArgumentException(
                       string.Format("entry is not a head of the queue at the stage {0}", stage), "entry");
         }
         _byUnorderedStageFirst[stage] = _byUnorderedStageFirst[stage].Next;
         if (_byUnorderedStageFirst[stage] == null)
         {
             _byUnorderedStageLast[stage] = null;
         }
     }
     else
     {
         if (_byOrderedStageLast[stage] != entry)
         {
             throw new ArgumentException(
                       string.Format("entry is not a head of the queue at the stage {0}", stage), "entry");
         }
         _byOrderedStageLast[stage] = entry.Next;
     }
 }
예제 #20
0
        public ActionResult EditTask(int id = 0)
        {
            if (Session["UserName"] != null)
            {
                List <TeamItem> teamItems        = _db.TeamItems.ToList();
                List <string>   teamCodeCategory = new List <string>();
                foreach (TeamItem teamMember in teamItems)
                {
                    teamCodeCategory.Add(teamMember.TEAMNAME);
                }
                SelectList TeamCodes1 = new SelectList(teamCodeCategory);
                ViewBag.TeamCodes  = TeamCodes1;
                ViewBag.TaskStatus = TaskStatus;

                ViewBag.ActivePage = "TASKS";
                ViewBag.Title      = "Edit Task";
                TaskEntry taskEntry = _db.TaskEntries.Find(id);

                return(View("AddNewTask", taskEntry));
            }
            else
            {
                return(RedirectToAction("Login", "MyAccount"));
            }
        }
예제 #21
0
파일: IceTask.cs 프로젝트: nolith/tasque
        public IceTask(IceBackend iceBackend,
                       IceCategory iceCategory,
                       TaskEntry taskEntry)
        {
            this.backend  = iceBackend;
            this.category = iceCategory;
            this.entry    = taskEntry;
            if (entry.Status == TaskStatus.Completed)
            {
                this.state = TaskState.Completed;
            }
            else if (entry.Status == TaskStatus.Cancelled)
            {
                this.state = TaskState.Inactive;                 // TODO: Is this the right thing to do?
            }
            else
            {
                this.state = TaskState.Active;
            }

            // Construct a unique id in the format of
            // <team-id>-<team-folder-id>-<task-entry-id>
            id = string.Format("{0}-{1}-{2}",
                               iceCategory.Team.ID,
                               iceCategory.Folder.ID,
                               taskEntry.ID);
        }
예제 #22
0
        public async Task EnqueueAsync(T t)
        {
            TaskCompletionSource <bool> taskCompletionSource    = new TaskCompletionSource <bool>();
            CancellationTokenSource     cancellationTokenSource = new CancellationTokenSource();

            TaskEntry previousTaskEntry = Interlocked.Exchange(ref previousTask, new TaskEntry(taskCompletionSource.Task, cancellationTokenSource));

            previousTaskEntry.CancellationTokenSource.Cancel();
            try
            {
                await previousTaskEntry.Task;
            }
            catch (OperationCanceledException)
            {
                // Do nothing;
            }

            try
            {
                cancellationTokenSource.Token.ThrowIfCancellationRequested();
                await func(t, cancellationTokenSource.Token);

                taskCompletionSource.TrySetResult(true);
            }
            catch (OperationCanceledException)
            {
                taskCompletionSource.TrySetCanceled();
            }
            catch (Exception ex)
            {
                taskCompletionSource.TrySetException(ex);
            }
        }
예제 #23
0
 public void Initialize()
 {
     _byUnorderedStageFirst = new StageEntry[_orderedStage.Length];
     _byUnorderedStageLast  = new StageEntry[_orderedStage.Length];
     _byOrderedStageLast    = new TaskEntry[_orderedStage.Length];
     _count = 0;
     _first = null;
     _last  = null;
 }
예제 #24
0
 private void ProcessEntry(TaskEntry entry)
 {
     // here we should be at the first StagedTask of current processing level which is not busy
     entry.Busy = true;
     AdvanceStage(entry.ReadForStage, entry);
     entry.Task.Process(
         entry.ReadForStage,
         (readyForStage, newCorrelationId) => CompleteTaskProcessing(entry, readyForStage, newCorrelationId));
 }
예제 #25
0
        private static int CompareDate(TaskEntry x, TaskEntry y)
        {
            if (x.END == null)
            {
                if (y.END == null)
                {
                    // If x is null and y is null, they're
                    // equal.
                    return(0);
                }
                else
                {
                    // If x is null and y is not null, y
                    // is greater.
                    return(-1);
                }
            }
            else
            {
                // If x is not null...
                //
                if (y.END == null)
                // ...and y is null, x is greater.
                {
                    return(1);
                }
                else
                {
                    // ...and y is not null, compare the
                    // lengths of the two strings.
                    //
                    //DateTime xdt = Convert.ToDateTime(x.END);
                    //DateTime ydt = Convert.ToDateTime(y.END);
                    DateTime xdt = (x.END);
                    DateTime ydt = (y.END);



                    int retval = xdt.CompareTo(ydt);

                    if (retval != 0)
                    {
                        // If the strings are not of equal length,
                        // the longer string is greater.
                        //
                        return(retval);
                    }
                    else
                    {
                        // If the strings are of equal length,
                        // sort them with ordinary string comparison.
                        //
                        return(xdt.CompareTo(ydt));
                    }
                }
            }
        }
예제 #26
0
 async void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (e.CurrentSelection != null)
     {
         // Navigate to the TaskeEntryPage, passing the ID as a query parameter.
         TaskEntry task = (TaskEntry)e.CurrentSelection.FirstOrDefault();
         await Shell.Current.GoToAsync($"{nameof(TaskEntryPage)}?{nameof(TaskEntryPage.ItemId)}={task.ID.ToString()}");
     }
 }
 public void Initialize()
 {
     _correlationLastEntries.Clear();
     _byUnorderedStageFirst = new StageEntry[_orderedStage.Length];
     _byUnorderedStageLast  = new StageEntry[_orderedStage.Length];
     _byOrderedStageLast    = new TaskEntry[_orderedStage.Length];
     _count = 0;
     _first = null;
     _last  = null;
 }
예제 #28
0
        async void ExecuteAddCmd()
        {
            var dt = DateTime.Now;
            var t  = new TaskEntry("Test " + dt.TimeOfDay, "Description " + dt.ToLongDateString(), TaskPriority.Medium, dt, dt.AddDays(2));

            _taskEntryRepo.Add(t);
            await _taskEntryRepo.SaveAsync();

            ReloadCmd.Execute();
        }
예제 #29
0
 public int QueueTask(int duration, System.Action callback)
 {
     if (duration == 0) Debug.LogError("Duration should be greater than 0");
     var entry = new TaskEntry() {
         Id = lastId++,
         DurationMS = duration,
         StartMS = timeMS,
     };
     entries.Add(entry);
     return entry.Id;
 }
예제 #30
0
        public string AddNewTask(string name)
        {
            var newTask = new TaskEntry
            {
                Name    = name,
                DueDate = DateTime.Now.AddDays(1)
            };

            _repo.Add(newTask);
            return("200");
        }
예제 #31
0
        public ActionResult SubmitTaskEntry([Bind("Id,TaskType,Comment,TaskTime,TaskLogId")] TaskEntry taskEntry)
        {
            var      userId   = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
            Employee employee = _context.Employee.Where(c => c.ApplicationUserId == userId).FirstOrDefault();

            taskEntry.Id = employee.Id;
            _context.TaskEntry.Add(taskEntry);
            _context.SaveChanges();
            TaskLog taskLog = new TaskLog();

            return(RedirectToAction("CreateTaskEntry"));
        }
예제 #32
0
 private void RunTaskAsync(TaskEntry entry) {
   _customThreadPool.RunAsync(() => {
     try {
       Logger.LogInfo("Queue \"{0}\": Executing task \"{1}\" after waiting for {2:n0} msec",
         _description,
         entry.Id.Description,
         (_dateTimeProvider.UtcNow - entry.EnqueuedDateTimeUtc).TotalMilliseconds);
       entry.StopWatch.Start();
       entry.Action();
     }
     finally {
       OnTaskFinished(entry);
     }
   });
 }
예제 #33
0
    private void OnTaskFinished(TaskEntry task) {
      task.StopWatch.Stop();
      Logger.LogInfo("Queue \"{0}\": Executed task \"{1}\" in {2:n0} msec",
        _description,
        task.Id.Description,
        task.StopWatch.ElapsedMilliseconds);

      TaskEntry nextTask = null;
      lock (_lock) {
        Debug.Assert(object.ReferenceEquals(_runningTask, task));
        nextTask = _runningTask = _tasks.Dequeue();
      }

      if (nextTask != null)
        RunTaskAsync(nextTask);
    }
예제 #34
0
파일: IceTask.cs 프로젝트: nolith/tasque
        public IceTask(IceBackend iceBackend,
						IceCategory iceCategory,
						TaskEntry taskEntry)
        {
            this.backend = iceBackend;
            this.category = iceCategory;
            this.entry = taskEntry;
            if (entry.Status == TaskStatus.Completed)
                this.state = TaskState.Completed;
            else if (entry.Status == TaskStatus.Cancelled)
                this.state = TaskState.Inactive; // TODO: Is this the right thing to do?
            else
                this.state = TaskState.Active;

            // Construct a unique id in the format of
            // <team-id>-<team-folder-id>-<task-entry-id>
            id = string.Format ("{0}-{1}-{2}",
                                iceCategory.Team.ID,
                                iceCategory.Folder.ID,
                                taskEntry.ID);
        }
예제 #35
0
        public void Enqueue(StagedTask stagedTask)
        {
            var entry = new TaskEntry(stagedTask, ++_sequence);
            if (_first == null)
            {
                _first = entry;
                _last = entry;
                _count = 1;
            }
            else
            {
                _last.Next = entry;
                _last = entry;
                _count++;
            }
            // re-initialize already completed queues
            for (var stage = 0; stage <= _maxStage; stage++)
                if (_orderedStage[stage] && _byOrderedStageLast[stage] == null)
                    _byOrderedStageLast[stage] = entry;

            SetEntryCorrelation(entry, stagedTask.InitialCorrelationId);
            EnqueueForStage(entry, 0);
        }
예제 #36
0
    public void Enqueue(TaskId id, Action task) {
      var entry = new TaskEntry {
        Id = id,
        EnqueuedDateTimeUtc = _dateTimeProvider.UtcNow,
        Action = task,
        StopWatch = new Stopwatch(),
      };

      Logger.LogInfo("Queue \"{0}\": Enqueing task \"{1}\"", _description, entry.Id.Description);

      bool isFirstTask;
      lock (_lock) {
        if (_runningTask == null) {
          _runningTask = entry;
          isFirstTask = true;
        } else {
          _tasks.Enqueue(entry);
          isFirstTask = false;
        }
      }

      if (isFirstTask)
        RunTaskAsync(entry);
    }
예제 #37
0
 public void Enqueue(TaskEntry entry) {
   LinkedListNode<TaskEntry> currentEntry;
   if (_map.TryGetValue(entry.Id, out currentEntry)) {
     _queue.Remove(currentEntry);
     _map.Remove(entry.Id);
   }
   var newEntry = _queue.AddLast(entry);
   _map.Add(entry.Id, newEntry);
 }
 private void MarkCompletedTask(TaskEntry entry)
 {
     entry.Completed = true;
 }
 public void Initialize()
 {
     _byUnorderedStageFirst = new StageEntry[_orderedStage.Length];
     _byUnorderedStageLast = new StageEntry[_orderedStage.Length];
     _byOrderedStageLast = new TaskEntry[_orderedStage.Length];
     _count = 0;
     _first = null;
     _last = null;
 }
예제 #40
0
    /// <summary>
    /// Creates a task and add it to corresponding quest
    /// </summary>
    /// <param name="stQuestName"> The name of the quest to add this task. The quest is identified by it's name </param>
    /// <param name="stTaskDescription"> A string with the description of this task </param>
    /// <param name="eEvent"> A EQuestEvents enum with the type of event to perform this task </param>
    public void CreateTaskInQuest(string stQuestName, string stTaskDescription, EQuestEvents eEvent, int nCount)
    {
        // First of all, let's find the quest in the list
        QuestEntry questEntry = null;

        foreach(QuestEntry entry in lstQuests) {

            if(entry.stName == stQuestName) {

                questEntry = entry;
                break;
            }
        }

        if(questEntry != null) {

            // Ok, quest found. Create the task...
            TaskEntry taskEntry = new TaskEntry();
            taskEntry.stTaskDescription = stTaskDescription;
            taskEntry.eEvent = eEvent;
            taskEntry.nEventCount = nCount;

            // ... and add it to the quest
            questEntry.lstTasks.Add(taskEntry);
        }
    }
예제 #41
0
        public void Add(ITask task)
        {
            var ea = new TaskmanagerEventArgs() { Task = task };
            AddingTask.Raise(this, ea);

            var t = task;
            t.TimeStamp = DateTime.Now;
            t.UniqueId = Guid.NewGuid();

            TaskEntry te = new TaskEntry();
            te.State = "pending";
            te.UniqueId = t.UniqueId;
            te.User = "******";
            te.TimeStamp = t.TimeStamp;
            te.Name = t.Name;

            te.Message = "Awaiting processing.";

            te.Description = task.TaskDescription;

            //Display of queued items:
            QueuedTasks.TryAdd(t.UniqueId, te);

            t.OnStatusChange += new EventHandler<TaskEventArgs>(value_OnStatusChange);

            //Processing the tasks:
            if (t.ByPassQueue)
            {
                if (secondaryTasks.TryAdd(t))
                    AddedTask.Raise(this, ea);
            }
            else
            {
                if (tasks.TryAdd(t))
                    AddedTask.Raise(this, ea);
            }
        }
 private void CompleteTaskProcessing(TaskEntry entry, int readyForStage, object newCorrelationId)
 {
     if (!entry.Busy)
         throw new InvalidOperationException("Task was not in progress");
     entry.Busy = false;
     SetEntryCorrelation(entry, newCorrelationId);
     if (readyForStage < 0)
     {
         MarkCompletedTask(entry);
         if (entry == _first)
             RemoveCompleted();
     }
     else
         EnqueueForStage(entry, readyForStage);
     if (EnsureTickPending != null)
         EnsureTickPending();
 }
예제 #43
0
 /// <summary>
 /// The handle date start reg ex.
 /// </summary>
 /// <param name="match">
 /// The match.
 /// </param>
 /// <param name="lineNumber">
 /// The line Number.
 /// </param>
 /// <param name="lineText">
 /// The line Text.
 /// </param>
 private void HandleDateStartRegularExpression(Match match, int lineNumber, string lineText)
 {
     DateTime dateTime;
     if (DateTime.TryParseExact(
         match.Groups["date"].Value,
         "yyyy-MM-dd",
         CultureInfo.InvariantCulture,
         DateTimeStyles.None,
         out dateTime))
     {
         this.currentDate = dateTime;
         this.lastTaskEntry = null;
     }
     else
     {
         this.errors.Add(new ParserErrorInfo(lineNumber, lineText, ErrorType.InvalidDate));
     }
 }
 private void ProcessEntry(TaskEntry entry)
 {
     // here we should be at the first StagedTask of current processing level which is not busy
     entry.Busy = true;
     AdvanceStage(entry.ReadForStage, entry);
     entry.Task.Process(
         entry.ReadForStage,
         (readyForStage, newCorrelationId) => CompleteTaskProcessing(entry, readyForStage, newCorrelationId));
 }
 private void RemoveCompleted()
 {
     while (_first != null && _first.Completed)
     {
         var task = _first;
         _first = task.Next;
         if (_first == null)
             _last = null;
         _count--;
         if (task.BusyCorrelationId != null)
         {
             var nextByCorrelation = task.NextByCorrelation;
             if (nextByCorrelation != null)
             {
                 if (nextByCorrelation.PreviousByCorrelation != task)
                     throw new Exception("Invalid linked list by correlation");
                 task.NextByCorrelation = null;
                 nextByCorrelation.PreviousByCorrelation = null;
                 if (!_orderedStage[nextByCorrelation.ReadForStage])
                     EnqueueForStage(nextByCorrelation, nextByCorrelation.ReadForStage);
             }
             else
             {
                 // remove the last one
                 _correlationLastEntries.Remove(task.BusyCorrelationId); 
             }
         }
     }
 }
예제 #46
0
 private bool TrySteal(int victim, out TaskEntry task)
 {
     return manager.workers[victim].taskData.TryDequeueLast(out task);
 }
예제 #47
0
 private void CompleteTaskProcessing(TaskEntry entry, int readyForStage)
 {
     if (!entry.Busy)
         throw new InvalidOperationException("Task was not in progress");
     entry.Busy = false;
     if (readyForStage < 0)
         RemoveCompletedTask(entry);
     else
         entry.ReadForStage = readyForStage;
 }
예제 #48
0
 private void RemoveCompletedTask(TaskEntry entry)
 {
     entry.Completed = true;
 }
 private void CompleteTaskProcessing(TaskEntry entry, int readyForStage, object newCorrelationId)
 {
     if (!entry.Busy)
         throw new InvalidOperationException("Task was not in progress");
     entry.Busy = false;
     if (!_orderedStage[entry.ReadForStage] && !Equals(entry.BusyCorrelationId, newCorrelationId))
         throw new InvalidOperationException("Cannot change busy correlation id at non-ordered stage");
     entry.BusyCorrelationId = newCorrelationId;
     if (readyForStage < 0)
         RemoveCompletedTask(entry);
     else
         entry.ReadForStage = readyForStage;
 }
 private void EnqueueForStage(TaskEntry entry, int readyForStage)
 {
     entry.ReadForStage = readyForStage;
     if (!_orderedStage[readyForStage] && (entry.PreviousByCorrelation == null))
     {
         var stageEntry = new StageEntry {Entry = entry, Next = null};
         if (_byUnorderedStageFirst[readyForStage] != null)
         {
             _byUnorderedStageLast[readyForStage].Next = stageEntry;
             _byUnorderedStageLast[readyForStage] = stageEntry;
         }
         else
         {
             _byUnorderedStageFirst[readyForStage] = stageEntry;
             _byUnorderedStageLast[readyForStage] = stageEntry;
         }
     }
 }
예제 #51
0
        /// <summary>
        /// The handle task regex.
        /// </summary>
        /// <param name="match">
        /// The match.
        /// </param>
        /// <param name="lineNumber">
        /// The line Number.
        /// </param>
        /// <param name="lineText">
        /// The line Text.
        /// </param>
        private void HandleTaskRegex(Match match, int lineNumber, string lineText)
        {
            if (!this.currentDate.HasValue)
            {
                this.errors.Add(new ParserErrorInfo(lineNumber, lineText, ErrorType.NoDateDefined));
                return;
            }

            string task = match.Groups["task"].Value;
            DateTime startTime = DateTime.ParseExact(
                match.Groups["startTime"].Value,
                "H:mm",
                CultureInfo.InvariantCulture);
            DateTime endTime = DateTime.ParseExact(match.Groups["endTime"].Value, "H:mm", CultureInfo.InvariantCulture);
            TaskStartEndEntry taskStartEndEntry = new TaskStartEndEntry(
                this.currentDate.Value,
                task,
                startTime,
                endTime);

            this.taskEntries.Add(taskStartEndEntry, lineNumber);

            this.lastTaskEntry = taskStartEndEntry;
        }
 private void AdvanceStage(int stage, TaskEntry entry)
 {
     if (!_orderedStage[stage])
     {
         if (_byUnorderedStageFirst[stage].Entry != entry)
             throw new ArgumentException(
                 string.Format("entry is not a head of the queue at the stage {0}", stage), "entry");
         _byUnorderedStageFirst[stage] = _byUnorderedStageFirst[stage].Next;
         if (_byUnorderedStageFirst[stage] == null)
             _byUnorderedStageLast[stage] = null;
     }
     else
     {
         if (_byOrderedStageLast[stage] != entry)
             throw new ArgumentException(
                 string.Format("entry is not a head of the queue at the stage {0}", stage), "entry");
         _byOrderedStageLast[stage] = entry.Next;
     }
 }
예제 #53
0
 public int GetTaskEntryLine(TaskEntry taskEntry)
 {
     return this.taskEntries[taskEntry];
 }
        private void SetEntryCorrelation(TaskEntry entry, object newCorrelationId)
        {
            if (!Equals(entry.BusyCorrelationId, newCorrelationId))
            {
                if (entry.ReadForStage != -1 && !_orderedStage[entry.ReadForStage])
                    throw new InvalidOperationException("Cannot set busy correlation id at non-ordered stage");
                if (entry.BusyCorrelationId != null)
                    throw new InvalidOperationException("Busy correlation id has been already set");

                entry.BusyCorrelationId = newCorrelationId;
                if (newCorrelationId != null)
                {
                    TaskEntry lastEntry;
                    if (_correlationLastEntries.TryGetValue(newCorrelationId, out lastEntry))
                    {
                        if (entry.Sequence < lastEntry.Sequence)
                            //NOTE: should never happen as we require ordered stage or initialization
                            throw new InvalidOperationException("Cannot inject task correlation id before another task with the same correlation id");
                        lastEntry.NextByCorrelation = entry;
                        entry.PreviousByCorrelation = lastEntry;
                        _correlationLastEntries[newCorrelationId] = entry;
                    }
                    else
                        _correlationLastEntries.Add(newCorrelationId, entry);
                }
            }
        }
예제 #55
0
파일: IceBackend.cs 프로젝트: GNOME/tasque
        /// <summary>
        /// Create a new task.
        /// </summary>
        public ITask CreateTask(string taskName, ICategory category)
        {
            IceTask task = null;
            IceCategory iceCategory = category as IceCategory;

            if (taskName == null || taskName.Trim () == string.Empty
                    || category == null) {
                Logger.Warn ("Cannot call IceBackend.CreateTask () with null/empty arguments.");
                return null;
            }

            string taskId = null;
            try {
                taskId =
                deskIceDaemon.CreateTask (iceCategory.Folder.ID,
                                          taskName,
                                          string.Empty,	// description
                                          5,			// Lowest Priority/None
                                          TaskStatus.NeedsAction,
                                          string.Empty,	// start date
                                          string.Empty);	// due date
            } catch (Exception e) {
                Logger.Error ("Exception calling deskIceDaemon.CreateTask (): {0}", e.Message);
                return null;
            }

            TaskEntry taskEntry = new TaskEntry (taskId, taskName);
            task = new IceTask (this, iceCategory, taskEntry);

            UpdateTask (task);

            return task;
        }
예제 #56
0
        public void Cancel(Guid taskId)
        {
            if (CurrentTasks.ContainsKey(taskId))
            {
                var ea = new TaskmanagerEventArgs() { Task = new TaskBase() { UniqueId = taskId } };

                CancellingTask(this, ea);

                var value = CurrentTasks[taskId];
                TaskEntry s = new TaskEntry();

                s.State = "cancelled";
                s.Message = "Cancelled by user";

                s.UniqueId = value.UniqueId;
                s.Description = value.TaskDescription; ;
                s.Name = value.Name;
                s.TimeStamp = value.TimeStamp;
                ProcessedTasks.TryAdd(s.UniqueId, s);

                value.Cancel();

                ITask irt;
                if (CurrentTasks.TryRemove(s.UniqueId, out irt))
                {
                    ea.Task = irt;
                    CancelledTask(this, ea);
                    irt.Dispose();
                }
            }
            else if (QueuedTasks.ContainsKey(taskId))
            {
                TaskEntry te;
                if (QueuedTasks.TryRemove(taskId, out te))
                {
                    te.State = "cancelled";
                    te.Message = "Cancelled by user";
                    ProcessedTasks.TryAdd(te.UniqueId, te);
                }
            }
        }