public override void RequestTaskState(TaskState taskState)
		{
			if (taskState == TaskState.Stopped || taskState == TaskState.Finished || taskState == TaskState.Paused)
			{
				while (true)
				{
					try
					{
						tcpListener.Stop();
						tcpListener.Server.Close();
					}
					catch
					{
					}

					if (base.RequestTaskState(taskState, TimeSpan.FromSeconds(0.5)))
					{
						return;
					}

					if (taskState == TaskState.Stopped || taskState == TaskState.Finished)
					{
						return;
					}
				}
			}

			base.RequestTaskState(taskState);
		}
Exemplo n.º 2
0
 public BuildData(string header)
 {
     Header = header;
     Info = new ObservableCollection<Message>();
     _state = TaskState.Normal;
     ItemCount = new ObservableCollection<string>();
 }
Exemplo n.º 3
0
 public IOPH_EZLinkDongle(ADTRecord adtRec, IAppMainWindow mainWin)
 {
     this._adtRec = adtRec;
     this._mainWin = mainWin;
     this._teleFromWin = new Telegram(0x3e8);
     this._teleToWin = new Telegram(0x3e8);
     this._replyData = new DataBuffer(0x3e8);
     this._isSeries = false;
     this._seriesExecStat = SeriesExecutionState.Stop;
     this._taskEvent = new AutoResetEvent(false);
     this._taskState = TaskState.TaskReady_OK;
     if (adtRec.isUsbEZLinkDevice())
     {
         this._ddi = DDI_EZLinkDongle.instance();
     }
     else if (adtRec.isTESTDevice())
     {
         this._ddi = DDI_TEST.instance();
     }
     else
     {
         GlobalServices.ErrMsg("FATAL ERROR: IOPH_EZLinkDongle", "I/O port type not supported, exit WDS!");
         Application.Exit();
     }
     this._iot = new Thread(new ThreadStart(this.doDeviceIO));
     this._iot.IsBackground = true;
     this._iot.Name = "IOPH_EZLink thread";
     this._isTelegramRequest = false;
     this._isRxTimerRequest = false;
     this._isReadRxPacketEnabled = false;
     this._iot.Start();
 }
Exemplo n.º 4
0
 private TaskState ProcessByState(Task processedTask, TaskState state)
 {
     //Global.Log ("Processing task of sequence (" + ToString () + "): " + processedTask.ToString() + " with state: " + state.ToString());
     switch (state) {
     case TaskState.Ready:
         return ExecuteSubTask (processedTask);
     case TaskState.Running:
         return TaskState.Running;
     case TaskState.Success:
         processedTask.State = TaskState.Ready;
         currentTaskIndex++;
         if (currentTaskIndex >= SubTasks.Count) {
             currentTaskIndex = 0;
             return TaskState.Success;
         }
         return TaskState.Running;
     case TaskState.Failed:
         processedTask.State = TaskState.Ready;
         //setting next task to first sub action
         currentTaskIndex = 0;
         return TaskState.Failed;
     default:
         //unexpected
         return TaskState.Failed;
     }
 }
Exemplo n.º 5
0
 /// <summary>
 /// Create a new progress snapshot.
 /// </summary>
 /// <param name="state">The current State of the task.</param>
 /// <param name="unitsByte"><c>true</c> if <see cref="UnitsProcessed"/> and <see cref="UnitsTotal"/> are measured in bytes; <c>false</c> if they are measured in generic units.</param>
 /// <param name="unitsProcessed">The number of units that have been processed so far.</param>
 /// <param name="unitsTotal">The total number of units that are to be processed; -1 for unknown.</param>
 public TaskSnapshot(TaskState state, bool unitsByte = false, long unitsProcessed = 0, long unitsTotal = -1)
 {
     State = state;
     UnitsByte = unitsByte;
     UnitsProcessed = unitsProcessed;
     UnitsTotal = unitsTotal;
 }
Exemplo n.º 6
0
        internal FlowState(Flow flow)
        {
            this.Tasks = new List<TaskState>();
            this.Art = flow.Art;

            foreach (var task in flow.Nodes)
            {
                TaskState state = new TaskState()
                {
                    ItemsProcessed = task.ItemsProcessed,
                    Name = task.Name,
                    Status = task.Status,
                    TotalSecondsBlocked = task.TotalSecondsBlocked,
                    TotalSecondsProcessing = task.TotalSecondsProcessing,
                    Position = task.Position
                };

                this.Tasks.Add(state);
            }
            this.Streams = new List<StreamState>();
            foreach (var stream in flow.Streams)
            {
                StreamState state = new StreamState()
                {
                    Name = stream.Name,
                    Closed = stream.IsClosed,
                    Count = stream.Count,
                    InPoint = stream.InPoint
                };
                this.Streams.Add(state);
            }
        }
Exemplo n.º 7
0
 internal Task(TaskManager taskManager, IEnumerator<IAsyncCall> callIterator)
 {
     this._waitCall = new AsyncCall<bool>();
     this._taskManager = taskManager;
     this._taskState = TaskState.Unstarted;
     this._asyncCallIterator = callIterator;
 }
 public TaskState(RemoteTask task, TaskState parentState, string message = "Internal Error (xunit runner): No status reported", TaskResult result = TaskResult.Inconclusive)
 {
     Task = task;
     Message = message;
     Result = result;
     ParentState = parentState;
 }
Exemplo n.º 9
0
        public ScheduleTrigger(TaskState state, ITrigger trigger, IDev2TaskService service, ITaskServiceConvertorFactory factory)
        {
            _service = service;
            _factory = factory;
            State = state;
            Trigger = trigger;

        }
Exemplo n.º 10
0
        public static IProcessingState GetState(TaskState state)
        {
            if (States.ContainsKey(state))
            {
                return States[state];
            }

            throw new ArgumentOutOfRangeException("state");
        }
Exemplo n.º 11
0
        public void SetState(ITaskExecuteClient source, TaskState state, TaskMessage message)
        {
            this._state = state;

            if (this.StateChanged != null)
            {
                this.StateChanged(source, this, message);
            }
        }
Exemplo n.º 12
0
        private void NotifyTaskStateChanged(AsyncTask task, TaskState state)
        {
            var stateChangedHandler = TaskStateChanged;
            if (stateChangedHandler == null)
                return; // No event handler, bail.

            var e = new TaskStateChangedEventArgs(task, state);
            stateChangedHandler(this, e);
        }
Exemplo n.º 13
0
 /// <summary>
 /// Create method constructer parameters
 /// </summary>
 /// <param name="id"></param>
 /// <param name="name"></param>
 /// <param name="description"></param>
 /// <param name="type"></param>
 /// <param name="user"></param>
 /// <param name="state"></param>
 /// <param name="completedPercent"></param>
 public Task(int id, string name, string description, TaskType type, List<User> user, TaskState state, int completedPercent)
 {
     TaskId = id;
     Name = name;
     Description = description;
     Type = type;
     Users = user;
     State = state;
     CompletedPercent = completedPercent;
 }
Exemplo n.º 14
0
        public bool ChangeTaskState(TaskState destinationState)
        {
            bool isSuccess = _database.ChangeTaskState(_targetTask, destinationState);
            if (isSuccess)
            {
                RefreshTaskList();

            }
            return isSuccess;
        }
Exemplo n.º 15
0
 internal Task(string name, Guid queueId)
 {
     this.Id = Guid.NewGuid();
     this.QueueId = queueId;
     this.Name = name;
     this.State = TaskState.Queued;
     this.OutstandingDependencies = new HashSet<Guid>();
     this.DependantOn = new HashSet<Guid>();
     this.DependencyTo = new HashSet<Guid>();
 }
Exemplo n.º 16
0
 public DummyTask(DummyBackend backend, int id, string taskName)
 {
     this.backend = backend;
     this.id = id;
     this.name = taskName;
     this.dueDate = DateTime.MinValue; // No due date specified
     this.completionDate = DateTime.MinValue; // No due date specified
     this.priority = TaskPriority.None;
     this.state = TaskState.Active;
 }
Exemplo n.º 17
0
        public TaskState Tick( Dictionary<string, object> pxActorView )
        {
            bool bHasTask = m_pxRootTask != null;
            if ( bHasTask )
            {
                m_pxRootTask.TickTask( pxActorView );
                m_eStatus = m_pxRootTask.GetCurrentState();

                return m_eStatus;
            }
            return TaskState.eTaskFailed;
        }
Exemplo n.º 18
0
	        /// <summary>
            /// 
            /// </summary>
            /// <param name="task"></param>
            public TaskAsyncStateAndImplementationHelper(ITask task)
            {
                this.task = task;
                taskState = TaskState.NotStarted;

                requestedTaskState = TaskState.Unknown;
                this.TaskThread = null;
                this.TaskStateLock = new object();

                TaskStateChanged = null;
                RequestedTaskStateChanged = null;
            }
Exemplo n.º 19
0
    public void Initialize(Task _task)
    {
        interfaceB = GameObject.FindGameObjectWithTag("Interface").GetComponent<InterfaceBehaviour>();
        //Debug.Log("prova " + interfaceB.name);
        task = _task;
        if (title.text.Length > maxStringCountTitle)
        {
            title.text = title.text.Substring(0, maxStringCountTitle) + "...";
        }
        else
        {
            title.text = _task.title;
        }

        if (_task.description.Length > maxStringCountDescr)
        {
            description.text = _task.description.Substring(0, maxStringCountDescr) + "...";
        }
        else
        {
            description.text = _task.description;
        }

        state = _task.taskState;
        bitmapNumber.text = _task.number.ToString();
        switch (state)
        {
            case TaskState.New:
                this.GetComponent<Button>().interactable = true;
                maskLock.SetActive(false);
                informationTask.gameObject.SetActive(true);
                stateText.color = InterfaceBehaviour.Orange;
                interfaceB.localizationUtils.AddTranslationText(stateText, "{new_task}");
                break;
            case TaskState.Visited:
                this.GetComponent<Button>().interactable = true;
                maskLock.SetActive(false);
                informationTask.gameObject.SetActive(true);
                stateText.color = InterfaceBehaviour.ClearGreen;
                interfaceB.localizationUtils.AddTranslationText(stateText, "{visited_task}");
                break;
            case TaskState.Locked:
                this.GetComponent<Button>().interactable = false;
                stateText.color = InterfaceBehaviour.Grey;
                interfaceB.localizationUtils.AddTranslationText(stateText, "{locked_task}");
                maskLock.SetActive(true);
                informationTask.gameObject.SetActive(false);
                break;
        }
    }
Exemplo n.º 20
0
        public bool ChangeTaskState(Task task, TaskState newState)
        {
            Open();
            MySqlCommand command = _conn.CreateCommand();

            command = _conn.CreateCommand();
            command.CommandText = "Update task Set " +
                "taskstate = " + ((int)newState).ToString() +

                " Where tid = " + task.PrimeKey.ToString();
            command.ExecuteNonQuery();
            Close();

            return true;
        }
Exemplo n.º 21
0
    private ResmgrNative()
    {
        //初始化本地URL
        #if UNITY_ANDROID && !UNITY_EDITOR
        localurl = Application.streamingAssetsPath;
        //Android 比较特别
        #else
        localurl = "file://" + Application.streamingAssetsPath;
        //此url 在 windows 及 WP IOS  可以使用
        #endif
        cacheurl = System.IO.Path.Combine(Application.persistentDataPath, "vercache");

        sha1 = new System.Security.Cryptography.SHA1Managed();
        taskState = new TaskState();
    }
        /// <summary>
        /// Constructor of the class
        /// </summary>
        /// <param name="taskModel"></param>
        /// <param name="targetList"></param>
        /// <param name="dataConnector"></param>
        /// <param name="mainPage"></param>
        /// <param name="state"></param>
        public DefaultTaskViewModel(ITaskModel taskModel, ObservableCollection<ITaskViewModel> targetList, IDataConnector dataConnector, MainPage mainPage, TaskState state)
        {
            TaskModel = taskModel;
            _targetList = targetList;
            _dataConnector = dataConnector;
            ItemVisualWidth = mainPage.ActualWidth;

            // Commands
            Break = new ViewModelCommand()
            {
                Command = new RelayCommand(r => BreakTask()),
                Text = "Break"
            };

            PunchOut = new ViewModelCommand
            {
                Command = new RelayCommand(r => FinishTask()),
                Text = "Finished",
                ImagePath = @"Images/finish.png"
            };

            DeleteFromList = new ViewModelCommand
            {
                Command = new RelayCommand(
                    r =>
                    {
                        if (targetList != null && targetList.Contains(this))
                        {
                            targetList.Remove(this);
                            _dataConnector.DeleteTask(taskModel.Id);
                        }
                    }),
                Text = "Delete",
                ImagePath = "Images/delete.png"
            };

            // Timer Init
            _timer = new DispatcherTimer();
            _timer.Tick += timer_Tick;
            _timer.Interval = TimeSpan.FromSeconds(1);
            _timer.Start();

            // Setstate
            State = state;
            _initLoad = false;
        }
Exemplo n.º 23
0
Arquivo: IOPH_DCP.cs Projeto: x893/WDS
 public IOPH_DCP(ADTRecord adtRec, IAppMainWindow mainWin)
 {
     _adtRec = adtRec;
     _mainWin = mainWin;
     _teleFromWin = new Telegram(GlobalServices.maxCommandDataLen);
     _teleToWin = new Telegram(GlobalServices.maxReplyDataLen);
     _replyData = new DataBuffer(GlobalServices.maxReplyDataLen);
     _isSeries = false;
     _seriesExecStat = SeriesExecutionState.Stop;
     _taskState = TaskState.TaskReady_OK;
     int num = int.Parse(ConfigurationManager.AppSettings["DCPMaxDataLen"]);
     int num2 = int.Parse(ConfigurationManager.AppSettings["DCPMsgRepeatNr"]);
     int num3 = int.Parse(ConfigurationManager.AppSettings["DCPRecTimeout"]);
     byte num4 = byte.Parse(ConfigurationManager.AppSettings["DCPSOFByte"]);
     _dcpProtocolEngine = new DCPProtocol(this, num, num2, num3, 10, num4);
     _DCPRXMsg = new DCPFrame(num, num4);
     _DCPAnswerMsg = new DCPFrame(num, num4);
     _DCPTXMsg = new DCPFrame(num, num4);
     _DCPTXBuf = new DCPFrame(num, num4);
     if (adtRec.isUsbFtdiDevice())
     {
         _ddi = DDI_USB.instance();
     }
     else if (adtRec.isRS232Device())
     {
         _ddi = DDI_RS232.instance();
     }
     else if (adtRec.isTESTDevice())
     {
         _ddi = DDI_TEST.instance();
     }
     else if (adtRec.isHIDDevice())
     {
         _ddi = DDI_HID.instance();
     }
     else
     {
         GlobalServices.ErrMsg("IOPH_DCP.IOPH_DCP()", "FATAL ERROR: Unknown I/O port type, exit WDS!");
         Application.Exit();
     }
     _iot = new Thread(new ThreadStart(doDeviceIO));
     _iot.IsBackground = true;
     _iot.Name = "IOPH_DCP thread";
     _isTelegramRequest = false;
     _iot.Start();
 }
        /// <summary>
        /// Save Task to Xml File.
        /// </summary>
        /// <param name="task"></param>
        /// <param name="taskState"></param>
        public void SaveTask(ITaskModel task, TaskState taskState)
        {
            // build the root nodes
            var rootTask = _rootDocument.CreateElement("Task");

            // build the model nodes
            var startDate = _rootDocument.CreateElement("StartDate");
            startDate.InnerText = task.Start.Ticks.ToString();

            var endDate = _rootDocument.CreateElement("EndDate");
            endDate.InnerText = task.End.Ticks.ToString();

            var title = _rootDocument.CreateElement("Title");
            title.InnerText = task.Title ?? "";

            var id = _rootDocument.CreateElement("Id");
            id.InnerText = task.Id.ToString();

            var state = _rootDocument.CreateElement("State");
            state.InnerText = ((int)taskState).ToString();

            var lastBreak = _rootDocument.CreateElement("LastBreak");
            lastBreak.InnerText = task.LastBreak.Ticks.ToString();

            // Breaks
            var rootBreaks = _rootDocument.CreateElement("Breaks");
            foreach (var timeBreak in task.Breaks)
            {
                var pause = _rootDocument.CreateElement("Break");
                pause.InnerText = timeBreak.Ticks.ToString();
                rootBreaks.AppendChild(pause);
            }

            // Add new nodes to Task node and Tasknode to rootNode
            rootTask.AppendChild(startDate);
            rootTask.AppendChild(endDate);
            rootTask.AppendChild(title);
            rootTask.AppendChild(id);
            rootTask.AppendChild(state);
            rootTask.AppendChild(rootBreaks);
            rootTask.AppendChild(lastBreak);

            _rootDocument.GetElementsByTagName("Tasks")[0].AppendChild(rootTask);

            _rootDocument.SaveToFileAsync(_databaseXmlFile);
        }
Exemplo n.º 25
0
 public OctopusEnvironmentInfo(
     string id, string name, IReadOnlyCollection<OctopusMachineInfo> machines, DateTimeOffset? startTime, string duration,
     string errorMessage, TaskState state, string releaseVersion, string releaseNotes, string displayName,
     string username, string absoluteDeployLink)
 {
     Id = id;
     Name = name;
     Machines = machines;
     StartTime = startTime;
     Duration = duration;
     ErrorMessage = errorMessage;
     State = state;
     ReleaseVersion = releaseVersion;
     ReleaseNotes = releaseNotes;
     DisplayName = displayName;
     Username = username;
     AbsoluteDeployLink = absoluteDeployLink;
 }
        public void AddTask(string name, Action<object> action, object aState, CancellationTokenSource source)
        {
            CancellationToken token = source.Token;
            TaskState state = new TaskState(aState, token);

            Task task = new Task(x =>
            {
                TaskState t = (TaskState)x;
                action(t.State);
                if (t.Token.IsCancellationRequested)
                    t.Token.ThrowIfCancellationRequested();
            }, state, token);

            task.ContinueWith(x => CompleteTask(x));

            Tasks.Add(name, task);
            TaskCancellations.Add(task, source);
        }
Exemplo n.º 27
0
 public IOPH_LoadBoard(ADTRecord adtRec, IAppMainWindow mainWin)
 {
     this._adtRec = adtRec;
     this._mainWin = mainWin;
     this._teleFromWin = new Telegram(GlobalServices.maxCommandDataLen);
     this._teleToWin = new Telegram(GlobalServices.maxReplyDataLen);
     this._replyData = new DataBuffer(GlobalServices.maxReplyDataLen, Data_Type.ASCII);
     this._isSeries = false;
     this._seriesExecStat = SeriesExecutionState.Stop;
     this._taskEvent = new AutoResetEvent(false);
     this._taskState = TaskState.TaskReady_OK;
     if (adtRec.isUsbFtdiDevice())
     {
         this._ddi = DDI_USB.instance();
         this._isTestDevice = false;
     }
     else if (adtRec.isRS232Device())
     {
         this._ddi = DDI_RS232.instance();
         this._isTestDevice = false;
     }
     else if (adtRec.isTESTDevice())
     {
         this._ddi = DDI_TEST.instance();
         this._isTestDevice = true;
     }
     else if (adtRec.isHIDDevice())
     {
         this._ddi = DDI_HID.instance();
         this._isTestDevice = false;
     }
     else
     {
         GlobalServices.ErrMsg("IOPH_LoadBoard.IOPH_LoadBoard()", "FATAL ERROR: Unknown I/O port type, exit WDS!");
         GlobalServices.msgBox("FATAL ERROR: Unknown I/O port type, exit WDS!", "IOPH_LoadBoard.IOPH_LoadBoard()");
         Application.Exit();
     }
     this.ReadReplytimerDelegate = new TimerCallback(this.rxReadReplyTimerTickHandler);
     this._iot = new Thread(new ThreadStart(this.doDeviceIO));
     this._iot.IsBackground = true;
     this._iot.Name = "IOPH_LoadBoard thread";
     this._iot.Start();
 }
Exemplo n.º 28
0
        /// <summary>
        /// Constructor that is created from an RTM Task Series
        /// </summary>
        /// <param name="taskSeries">
        /// A <see cref="TaskSeries"/>
        /// </param>
        public RtmTask(TaskSeries taskSeries, RtmBackend be, string listID)
        {
            this.taskSeries = taskSeries;
            this.rtmBackend = be;
            this.category = be.GetCategory(listID);

            if(CompletionDate == DateTime.MinValue )
                state = TaskState.Active;
            else
                state = TaskState.Completed;
            notes = new List<INote>();

            if (taskSeries.Notes.NoteCollection != null) {
                foreach(Note note in taskSeries.Notes.NoteCollection) {
                    RtmNote rtmNote = new RtmNote(note);
                    notes.Add(rtmNote);
                }
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// called when the task is started. allows setup/cleanup to occur and delays to be used
        /// </summary>
        public virtual void TaskStarted() {
            ResetState();

            // if we are delayed then set ourself as paused then unpause after the delay
            if (delay > 0) {
                state = TaskState.Paused;

                var delayInMilliseconds = (int)(delay * 1000);
                new System.Threading.Timer(obj => {
                    lock (this) {
                        state = TaskState.Running;
                    }
                }, null, delayInMilliseconds, System.Threading.Timeout.Infinite);
            }
            else {
                // start immediately
                state = TaskState.Running;
            }
        }
Exemplo n.º 30
0
 public Environment(
     string id, string name, string version, DateTimeOffset started, TaskState state, 
     string branch, string octopusDeployLink, string deployedBy, 
     bool isDisabled,
     IEnumerable<Trello> branchRelatedTrellos, 
     IEnumerable<Trello> environmentTaggedTrellos,
     IEnumerable<TeamCityBuild> builds)
 {
     Id = id;
     Name = name;
     Version = version;
     Started = started;
     State = state;
     Branch = branch;
     OctopusDeployLink = octopusDeployLink;
     DeployedBy = deployedBy;
     IsDisabled = isDisabled;
     BranchRelatedTrellos = branchRelatedTrellos;
     EnvironmentTaggedTrellos = environmentTaggedTrellos;
     Builds = builds;
 }
Exemplo n.º 31
0
        // GET: /TaskState/Delete/<id>
        public ActionResult Delete(
            Int32?TaskStateID
            )
        {
            if (
                TaskStateID == null
                )
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }


            TaskState TaskState = new TaskState();

            TaskState.TaskStateID = System.Convert.ToInt32(TaskStateID);
            TaskState             = TaskStateData.Select_Record(TaskState);

            if (TaskState == null)
            {
                return(HttpNotFound());
            }
            return(View(TaskState));
        }
Exemplo n.º 32
0
    public static string GetTaskStatusHTML(TaskState state)
    {
        switch (state)
        {
        case TaskState.Running:
            return(Resources.BPMResource.Com_Processing);

        case TaskState.Approved:
            return(Resources.BPMResource.Com_Approved);

        case TaskState.Rejected:
            return(Resources.BPMResource.Com_Rejected);

        case TaskState.Aborted:
            return(Resources.BPMResource.Com_Aborted);

        case TaskState.Deleted:
            return(Resources.BPMResource.Com_Deleted);

        default:
            return(Resources.BPMResource.Com_UnknownStatus);
        }
    }
Exemplo n.º 33
0
    public static string GetTaskStateDisplayName(TaskState state)
    {
        switch (state)
        {
        case TaskState.Running:
            return(Resources.YZStrings.All_Running);

        case TaskState.Approved:
            return(Resources.YZStrings.All_Approved);

        case TaskState.Rejected:
            return(Resources.YZStrings.All_Rejected);

        case TaskState.Aborted:
            return(Resources.YZStrings.All_Aborted);

        case TaskState.Deleted:
            return(Resources.YZStrings.All_Deleted);

        default:
            return(Resources.YZStrings.All_UnknownStatus);
        }
    }
Exemplo n.º 34
0
    public void SetState(TaskState state)
    {
        m_State     = state;
        m_Text.text = BuildString(m_ApplianceName, state);

        Color color = m_IncompleteColor;

        switch (state)
        {
        case TaskState.Completed:
            color = m_CompleteColor;
            break;

        case TaskState.Failed:
            color = m_FailedColor;
            break;

        default:
            break;
        }

        m_Text.color = color;
    }
Exemplo n.º 35
0
        public IActionResult UpdateStatus([FromRoute] int id, [FromBody] TaskState status)
        {
            if (!ModelState.IsValid)
            {
                return(HandleBadRequest(ListModelErrors));
            }

            var project = _taskService.Get(id);

            if (project == null)
            {
                return(NotFound());
            }

            var result = _taskService.UpdateState(id, status);

            if (result.HasError)
            {
                return(HandleBadRequest(result.ErrorMessages));
            }

            return(Ok());
        }
Exemplo n.º 36
0
        public override TaskState Execute()
        {
            if (Predicate != null)
            {
                if (!Predicate.TryEvaluateToBool())
                {
                    return(TaskState.Failure);
                }
            }
            foreach (TreeTask <TBb> task in Children)
            {
                TaskState childStatus = task.Tick();
                switch (childStatus)
                {
                case TaskState.Running:
                    return(TaskState.Running);

                case TaskState.Failure:
                    return(TaskState.Failure);
                }
            }
            return(TaskState.Success);
        }
Exemplo n.º 37
0
 /// <summary>
 /// Attempts to cancel execution of this task.
 /// </summary>
 /// <remarks>
 /// This attempt will fail if the task has already completed, already been cancelled,
 /// or could not be cancelled for some other reason. If successful,
 /// and this task has not started when <see cref="ICancellable.Cancel()"/> is called,
 /// this task should never run.  If the task has already started,
 /// then the <paramref name="mayInterruptIfRunning"/> parameter determines
 /// whether the thread executing this task should be interrupted in
 /// an attempt to stop the task.
 /// </remarks>
 /// <param name="mayInterruptIfRunning"><c>true</c> if the thread executing this
 /// task should be interrupted; otherwise, in-progress tasks are allowed
 /// to complete
 /// </param>
 /// <returns> <c>false</c> if the task could not be cancelled,
 /// typically because it has already completed normally;
 /// <c>true</c> otherwise
 /// </returns>
 public virtual bool Cancel(bool mayInterruptIfRunning)
 {
     lock (this)
     {
         if (RanOrCancelled())
         {
             return(false);
         }
         _taskState = TaskState.Cancelled;
         if (mayInterruptIfRunning)
         {
             Thread r = _runningThread;
             if (r != null)
             {
                 r.Interrupt();
             }
         }
         _runningThread = null;
         Monitor.PulseAll(this);
     }
     Done();
     return(true);
 }
Exemplo n.º 38
0
        public ActionResult Edit(TaskState TaskState)
        {
            TaskState oTaskState = new TaskState();

            oTaskState.TaskStateID = System.Convert.ToInt32(TaskState.TaskStateID);
            oTaskState             = TaskStateData.Select_Record(TaskState);

            if (ModelState.IsValid)
            {
                bool bSucess = false;
                bSucess = TaskStateData.Update(oTaskState, TaskState);
                if (bSucess == true)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    ModelState.AddModelError("", "Can Not Update");
                }
            }

            return(View(TaskState));
        }
Exemplo n.º 39
0
        internal virtual bool PostUpdateEvaluate()
        {
            if (EvaluatingWhenFailure && State == TaskState.Failure ||
                EvaluatingWhenSuccess && State == TaskState.Success)
            {
                TaskState prevState = State;
                ResetState();
                TaskState potState = OnEvaluate();

                if (potState == TaskState.NotEvaluated)
                {
                    potState = TaskState.Running;
                }

                State = potState;
                if (prevState != potState)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 40
0
    internal void SetState(TaskState newState)
    {
        if (State == newState)
        {
            return;
        }

        State = newState;

        switch (newState)
        {
        case TaskState.Working:
            Init();
            break;

        case TaskState.Success:
            OnSuccess();
            CleanUp();
            break;

        case TaskState.Aborted:
            OnAbort();
            CleanUp();
            break;

        case TaskState.Failed:
            OnFail();
            CleanUp();
            break;

        case TaskState.Pending:
            break;

        default:
            throw new ArgumentOutOfRangeException(newState.ToString(), newState, null);
        }
    }
Exemplo n.º 41
0
        public TaskStatus(
            TaskId taskId,
            Guid taskInstanceId,
            long version,
            TaskState state,
            Uri self,
            Guid nodeId,
            HashSet <Lifespan> completedDriverGroups,
            IEnumerable <ExecutionFailureInfo> failures,
            int queuedPartitionDrivers,
            int runningPartitionDrivers,
            bool outputBufferOverutilized,
            DataSize physicalWrittenDataSize,
            DataSize memoryReservation,
            DataSize systemMemoryReservation
            )
        {
            ParameterCheck.OutOfRange(version >= MIN_VERSION, "version", $"The version cannot be less than the minimum version of {MIN_VERSION}.");
            ParameterCheck.OutOfRange(queuedPartitionDrivers >= 0, "queuedPartitionDrivers", "The queued partition drivers cannot be less than 0.");
            ParameterCheck.OutOfRange(runningPartitionDrivers >= 0, "runningPartitionDrivers", "The running partition drivers cannot be less than 0.");

            this.TaskId                = taskId ?? throw new ArgumentNullException("taskId");
            this.TaskInstanceId        = taskInstanceId;
            this.Version               = version;
            this.State                 = state;
            this.Self                  = self ?? throw new ArgumentNullException("self");
            this.NodeId                = nodeId;
            this.CompletedDriverGroups = completedDriverGroups ?? throw new ArgumentNullException("completedDriverGroups");

            this.QueuedPartitionedDrivers  = queuedPartitionDrivers;
            this.RunningPartitionedDrivers = runningPartitionDrivers;
            this.OutputBufferOverutilized  = outputBufferOverutilized;
            this.PhysicalWrittenDataSize   = physicalWrittenDataSize ?? throw new ArgumentNullException("physicalWrittenDataSize");
            this.MemoryReservation         = memoryReservation ?? throw new ArgumentNullException("memoryReservation");
            this.SystemMemoryReservation   = systemMemoryReservation ?? throw new ArgumentNullException("systemMemoryReservation");
            this.Failures = failures ?? throw new ArgumentNullException("failures");
        }
Exemplo n.º 42
0
        public static Taskk ToTask(TaskPostModel taskk)
        {
            TaskImportance taskImportance = TaskImportance.Low;

            if (taskk.Importance == "Medium")
            {
                taskImportance = TaskImportance.High;
            }
            if (taskk.Importance == "High")
            {
                taskImportance = TaskImportance.High;
            }

            TaskState taskState = TaskState.Open;

            if (taskk.State == "In Progress")
            {
                taskState = TaskState.InProgress;
            }
            if (taskk.Importance == "Closed")
            {
                taskState = TaskState.Closed;
            }


            return(new Taskk
            {
                Title = taskk.Title,
                Description = taskk.Description,
                Added = taskk.Added,
                Deadline = taskk.Deadline,
                ClosedAt = taskk.ClosedAt,
                Importance = taskImportance,
                State = taskState,
                Comments = taskk.Comments
            });
        }
Exemplo n.º 43
0
    /// <summary>
    /// 接收任务
    /// </summary>
    /// <param name="sTaskState"></param>
    public void AcceptTask(STaskState sTaskState)
    {
        int tempI = -1;

        for (int i = 0; i < m_sortedTask.Count; i++)
        {
            if (m_sortedTask[i].dwTaskID == sTaskState.dwTaskID)
            {
                tempI = i;
            }
        }
        if (tempI != -1)
        {
            m_sortedTask.RemoveAt(tempI);
        }
        TaskState taskState = new TaskState(sTaskState, m_taskNewConfigDataBase.GetTaskNewConfigData(sTaskState.dwTaskID));

        m_sortedTask.Add(taskState);
        if (m_taskNewConfigDataBase.GetTaskNewConfigData(sTaskState.dwTaskID).GuideGroup != "0") //当引导组不为0时,表示需要加入到快速引导列表
        {
            RefreshQuickTaskGuide();
        }
        RefreshTask();
        if (!m_lockTaskAutoTrigger)
        {
            //第一次下发的不处理//
            AutoTriggerTask(taskState);
        }
        else
        {
            m_lockTaskAutoTrigger = false;              //解锁 任务触发后,自动或手动
        }
        if (AcceptTaskAct != null)
        {
            AcceptTaskAct();
        }
    }
Exemplo n.º 44
0
    protected TableCell CreateStateCell(TaskState taskstate)
    {
        string imgfile = null;

        switch (taskstate)
        {
        case TaskState.Running:
            imgfile = "../Images/st_process.gif";
            break;

        case TaskState.Pause:
            imgfile = "../Images/st_pause.gif";
            break;

        case TaskState.Stopped:
            imgfile = "../Images/st_stop.gif";
            break;

        case TaskState.Approved:
            //imgfile = "stprocess.gif";
            break;

        case TaskState.Rejected:
            //imgfile = "stprocess.gif";
            break;
        }

        if (!String.IsNullOrEmpty(imgfile))
        {
            return(CreateImageCell(imgfile, 2));
        }
        else
        {
            return(CreateEmptyCell(2));
        }
    }
        public MockDatabaseImplementation()
        {
            User wcabrera0 = new User(0, "wcabrera0", "*****@*****.**", "9f4dca77c2be9c1549cb1c246cdbc34ff6785508");

            _users.Add(wcabrera0);

            User demo = new User(1, "demo", "*****@*****.**", "demo");

            _users.Add(demo);

            Role owner = new Role(0, "Owner", true, true, true, true);

            _roles.Add(owner);

            UserGroup desktopSupport = new UserGroup(0, wcabrera0, "Desktop Support", "Provide end user support");

            _userGroups.Add(desktopSupport);

            _userRoleInGroup.Add(new Tuple <User, UserGroup>(wcabrera0, desktopSupport), owner);
            _userRoleInGroup.Add(new Tuple <User, UserGroup>(demo, desktopSupport), owner);

            TaskState notStarted = new TaskState(0, "Not Started", "", "D3D3D3");

            _taskStates.Add(notStarted);

            List <TaskCategory> testTaskCategories = new List <TaskCategory>();
            TaskCategory        highPriority       = new TaskCategory(0, wcabrera0, "High Priority", "", "ffa500");

            testTaskCategories.Add(highPriority);

            DateTime date1 = new DateTime(2019, 12, 1, 0, 0, 0);
            DateTime date2 = new DateTime(2019, 11, 1, 0, 0, 0);
            DateTime date3 = new DateTime(2019, 12, 1, 0, 0, 0);

            _tasks.Add(new model.Task(0, "Testing", "A desc", desktopSupport, demo, notStarted, date1, date2, date3, testTaskCategories));
        }
Exemplo n.º 46
0
        public static Task ToTask(TaskPostDTO task)
        {
            TaskImportance TaskImportance = TaskImportance.Low;

            if (task.TaskImportance == "Medium")
            {
                TaskImportance = TaskImportance.Medium;
            }
            else if (task.TaskImportance == "Hight")
            {
                TaskImportance = TaskImportance.Hight;
            }

            TaskState TaskState = TaskState.Open;

            if (task.TaskState == "InProgress")
            {
                TaskState = TaskState.InProgress;
            }
            else if (task.TaskState == "Closed")
            {
                TaskState = TaskState.Closed;
            }

            return(new Task
            {
                Title = task.Title,
                Description = task.Description,
                DateAdded = task.DateAdded,
                Deadline = task.Deadline,
                TaskImportance = TaskImportance,
                TaskState = TaskState,
                DateClosed = task.DateClosed,
                Comments = task.Comments
            });
        }
Exemplo n.º 47
0
    public static string BuildString(string text, TaskState state)
    {
        string stateName = "";

        switch (state)
        {
        case TaskState.Incomplete:
            stateName = "";
            break;

        case TaskState.Completed:
            stateName = " - COMPLETED";
            break;

        case TaskState.Failed:
            stateName = " - FAILED";
            break;

        default:
            break;
        }

        return("- " + text + " " + stateName);
    }
Exemplo n.º 48
0
 public static string ValveControlFinished(string taskID, TaskState state)
 {
     try
     {
         MongoDBHelper <Task> mongo = new MongoDBHelper <Task>();
         QueryDocument        query = new QueryDocument();
         query.Add("TaskID", taskID);
         MongoCursor <Task> mongoCursor = mongo.Query(CollectionNameDefine.TaskCollectionName, query);
         var dataList = mongoCursor.ToList();
         if (dataList == null || dataList.Count == 0)
         {
             return("没有找到TaskID:【" + taskID + "】的任务。");
         }
         string result = "";
         Task   task   = dataList[0];
         task.Finished  = QuShi.getDate();
         task.TaskState = state;
         TaskManageDA tm = new TaskManageDA();
         result = tm.TaskCompile(task);
         if (result != "")
         {
             return(result);
         }
         Meter _meter = tm.QueryMeter(task.MeterMac);
         if (state == TaskState.Finished)
         {
             _meter.ValveState = task.TaskType == TaskType.TaskType_开阀 ? "0" : "1";
             result            = tm.UpdateMeter(_meter);
         }
         return(result);
     }
     catch (Exception e)
     {
         return(e.Message);
     }
 }
Exemplo n.º 49
0
    State getStart()
    {
        State state = TaskState.Create(delegate {
            TaskList tl = new TaskList();
            tl.push(FaceManager.Instance.photo(delegate(Texture2D t)
            {
                texture_ = t;
            }));
            tl.push(new TaskPack(delegate { return(_board.show(texture_)); }));

            return(tl);
        }, this.fsm_, delegate {
            if (texture_ != null)
            {
                return("scanning");
            }
            else
            {
                return("error");
            }
        });

        return(state);
    }
Exemplo n.º 50
0
        protected override void OnStart(string[] args)
        {
#if DEBUG
            Debugger.Launch();
#endif

            var registryKey = Registry.CurrentUser.OpenSubKey("Software\\hddnagger");
            if (registryKey == null)
            {
                throw new InvalidOperationException("Couldn't load or create registry node for the HddNagger service. Exiting.");
            }

            var parameters = ((string)registryKey.GetValue("parameters", string.Empty)).Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);

            registryKey.Close();

            if (parameters.Length < 1)
            {
                this.Log("No root paths were given. Exiting...", false);
                this.Stop();
                return;
            }

            this.state = TaskState.Working;
            this.secondsBetweenWrites = 10;

            for (var i = 0; i < parameters.Length; i++)
            {
                var id       = i;
                var rootPath = parameters[i];

                this.tasks.Add(Task.Factory.StartNew(() => DoWork(id, this.secondsBetweenWrites, rootPath, ref this.state)));
                this.Log($"Launched task number {id} with root path {rootPath}.", false);
                Thread.Sleep(1000);
            }
        }
Exemplo n.º 51
0
Arquivo: Shop.cs Projeto: gdgeek/shop
    private State getSelect()
    {
        StateWithEventMap select = TaskState.Create(delegate {
            TweenTask tt = new TweenTask(delegate() {
                TweenLocalPosition tlp = TweenLocalPosition.Begin(this._offset, 0.3f, new Vector3(-_select * Jianju_, 0, 0));

                return(tlp);
            });
            //TweenLocalPosition();

            /*
             * Task task = new Task();
             * task.init = delegate {
             *      Debug.Log(_select);
             * };
             * return task;*/
            return(tt);
        }, fsm_, "normal");

        select.onStart += delegate {
//			Debug.Log("select");
        };
        return(select);
    }
Exemplo n.º 52
0
        private TaskState RunSelector(BehaviourSelector parentTask)
        {
            if (parentTask.CanExecute())
            {
                TaskState state = RunTask(parentTask.GetChild(parentTask.CurrentChildIndex()));
                if (parentTask.HasLastChild())
                {
                    if (state != TaskState.Running)
                    {
                        state = TaskState.Success;
                    }
                }
                parentTask.OnChildExecuted(state);

                if (state == TaskState.Failure)
                {
                    state = RunParentTask(parentTask);
                }
                return(state);
            }

            parentTask.OnReset();
            return(TaskState.Failure);
        }
Exemplo n.º 53
0
 public void UpdateState(string guid, TaskState state)
 {
     using (OOCEntities db = new OOCEntities())
     {
         IQueryable <Task> result = from o in db.Task
                                    where o.guid == guid
                                    select o;
         if (!result.Any())
         {
             throw new FaultException("TASK_NOT_EXISTS");
         }
         Task task = result.First();
         task.state = (sbyte)state;
         if (state == TaskState.Running)
         {
             task.timeStarted = System.DateTime.Now;
         }
         if (state == TaskState.Completed)
         {
             task.timeFinished = System.DateTime.Now;
         }
         db.SaveChanges();
     }
 }
Exemplo n.º 54
0
 /// <summary>
 /// The entry point
 /// </summary>
 public virtual void Run()
 {
     if (_contextCarrier != null)
     {
         _contextCarrier.Restore();
     }
     lock (this)
     {
         if (_taskState != TaskState.Ready)
         {
             return;
         }
         _taskState     = TaskState.Running;
         _runningThread = Thread.CurrentThread;
     }
     try
     {
         SetCompleted(_callable.Call());
     }
     catch (Exception ex)
     {
         SetFailed(ex);
     }
 }
Exemplo n.º 55
0
        private StateBase IAmClient()
        {
            State state = TaskState.Create(delegate {
                Task task = new GDGeek.TaskWait(0.3f);
                TaskManager.PushBack(task, delegate
                {
                    NetworkSystem.SessionInfo sessionInfo = this.getSessionInfo();
                    if (sessionInfo != null && networkSystem_.running)
                    {
                        networkSystem_.join(sessionInfo);
                    }
                });
                return(task);
            }, this.fsm_, delegate {
                if (Root.Instance.model.hasGod)
                {
                    return("running");
                }
                return("whoIsGod");
            });


            return(state);
        }
Exemplo n.º 56
0
 /// <summary>
 /// completes the task with NO result.
 /// </summary>
 public void SetComplete()
 {
                 #if COOPER
     Completion w;
     lock (this) {
         if (this.state != TaskState.Running)
         {
             throw new Exception("Invalid state for task: " + this.state);
         }
         w = this.completion;
         this.completion = null;
         this.state      = TaskState.Done;
     }
     while (w != null)
     {
         w.Action.Step();
         w = w.Next;
     }
                 #else
     SpinLockEnter(ref @lock);
     if (this.state != TaskState.Running)
     {
         SpinLockExit(ref @lock);
         throw new Exception("Invalid state for task: " + this.state);
     }
     var w = this.completion;
     this.completion = null;
     this.state      = TaskState.Done;
     SpinLockExit(ref @lock);
     while (w != null)
     {
         w.Action.Step();
         w = w.Next;
     }
                 #endif
 }
Exemplo n.º 57
0
    //移出状态
    private State RemoveState()
    {
        bool flag = false;
        StateWithEventMap state = TaskState.Create(
            delegate
        {
            Task task = new Task();

            //在进行此任务之前先检查消除,执行完检查消除后才会执行此状态
            TaskManager.PushFront(task, delegate
            {
                flag = CheckAndRemove();
            });
            return(task);
        },
            fsm,
            delegate //使用委托返回下一个状态
        {
            return(flag ? "fall" : "input");
        }
            );

        return(state);
    }
Exemplo n.º 58
0
        protected override TaskState OnEvaluate()
        {
            if (this.State == TaskState.NotEvaluated)
            {
                cicleIndex     = 0;
                lastChildState = TaskState.NotEvaluated;
            }



            if ((lastChildState == TaskState.Success && abortType != AbortType.Success) ||
                (lastChildState == TaskState.Failure && abortType != AbortType.Failure))
            {
                Child.ResetState();
            }

            lastChildState = Child.Evaluate();

            if (lastChildState != TaskState.Running)
            {
                cicleIndex++;
            }

            if (cicles > 0 && cicleIndex >= cicles && lastChildState != TaskState.Running)
            {
                return(TaskState.Success);
            }

            if (lastChildState == TaskState.Success && abortType == AbortType.Success ||
                lastChildState == TaskState.Failure && abortType == AbortType.Failure)
            {
                return(lastChildState);
            }

            return(TaskState.Running);
        }
Exemplo n.º 59
0
        public string ChangeMeterFinished(string taskID, TaskState state)
        {
            string result     = "";
            string configName = System.Configuration.ConfigurationManager.AppSettings["defaultDatabase"];
            //Linq to SQL 上下文对象
            DataContext dd = new DataContext(System.Configuration.ConfigurationManager.ConnectionStrings[configName].ConnectionString);

            try
            {
                IoT_ChangeMeter dbinfo = dd.GetTable <IoT_ChangeMeter>().Where(p =>
                                                                               p.TaskID == taskID).SingleOrDefault();
                if (state == TaskState.Finished)
                {
                    dbinfo.FinishedDate = DateTime.Now;
                    dbinfo.State        = '3';
                }
                else if (state == TaskState.Undo)
                {
                    dbinfo.State        = '4';//撤销
                    dbinfo.FinishedDate = DateTime.Now;
                    new M_SetParameterService().UnSetParameter(taskID);
                }
                else
                {
                    return("未知状态");
                }
                // 更新操作
                dd.SubmitChanges();
            }
            catch (Exception e)
            {
                result = e.Message;
            }

            return("");
        }
Exemplo n.º 60
0
        public ContentResult ChangeState(int Id, string TaskState)
        {
            var       ticket      = this.Data.Tickets.GetById(Id);
            TaskState ticketState = TicketingSystem.Models.TaskState.ToDo;

            if (TaskState == "ToDo")
            {
                ticketState = (TaskState)System.Enum.Parse(typeof(TaskState), "InProgress");
            }
            else if (TaskState == "InProgress")
            {
                ticketState = (TaskState)System.Enum.Parse(typeof(TaskState), "ToDo");
            }
            else if (TaskState == "Done")
            {
                ticketState = (TaskState)System.Enum.Parse(typeof(TaskState), "Done");
                if (ticket.Assignee != null)
                {
                    var UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
                    var user   = this.Data.ApplicationUsers.All().FirstOrDefault(u => u.Id == UserId);
                    ticket.Assignee = user;
                    ticket.EndDate  = DateTime.UtcNow;
                }
            }

            ticket.TaskState = ticketState;

            this.Data.Tickets.Update(ticket);
            this.Data.SaveChanges();

            var jsonTicketState = JsonConvert.SerializeObject(ticketState, Formatting.None, new JsonSerializerSettings {
                Converters = new[] { new StringEnumConverter() }
            });

            return(this.Content(jsonTicketState, "application/json"));
        }