Пример #1
0
 public DelayedAction(Action action, TimeSpan durationToWaitTillExecution)
 {
     _threadLock   = new object();
     _action       = action;
     _waitDuration = durationToWaitTillExecution;
     _waitState    = WaitState.Idle;
 }
Пример #2
0
    public void Activate()
    {
        Active       = true;
        StartingTile = GetComponent <TileOccupier>().GetOccupiedTile();

        Engine.MapCursor.X = GetComponent <TileOccupier>().X;
        Engine.MapCursor.Y = GetComponent <TileOccupier>().Y;
        Engine.MapCursor.GoToTile();
        Engine.MapCursor.Show();

        MovePoints = 1;
        ActPoints  = 1;

        KO k = GetComponent <KO>();

        if (k != null)
        {
            k.Counter--;
        }

        CombatUnit c = GetComponent <CombatUnit>();

        if (!c.Guest && !c.Enemy)
        {
            Engine.CameraManager.SetTargetPosition(transform.position, .5f);
        }

        WaitState = WaitState.None;
        Engine.AssignControl(this);
    }
Пример #3
0
        private void ExecuteAction()
        {
            TimeSpan durationToSleep = TimeSpan.Zero;

            lock (_threadLock) {
                if (_lastPing.TimeElapsed() < _waitDuration)
                {
                    durationToSleep = _waitDuration.Subtract(DateTime.Now.Subtract(_lastPing));
                    if (durationToSleep.TotalMilliseconds < 0)
                    {
                        durationToSleep = TimeSpan.Zero;
                    }
                }
            }

            if (durationToSleep == TimeSpan.Zero)
            {
                try {
                    _action();
                } finally {
                    _waitState = WaitState.Idle;
                }
            }
            else
            {
                System.Threading.Thread.Sleep(durationToSleep);
                Tools.Threads.QueueAction(ExecuteAction);
            }
        }
        public virtual async Task OptimisticConcurrencyCheck()
        {
            // Simulates a state in which two read models have been loaded to memory
            // and each is updated independently. The read store should detect the
            // concurrent update, reload the read model and apply the updates once
            // again.
            // A decorated DelayingReadModelDomainEventApplier is used to introduce
            // a controlled delay and a set of AutoResetEvent is used to ensure
            // that the read store is in the desired state before continuing

            using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
            {
                // Arrange
                var id        = ThingyId.New;
                var waitState = new WaitState();
                await PublishPingCommandsAsync(id, 1, cts.Token).ConfigureAwait(false);

                // Arrange
                _waitStates[id.Value] = waitState;
                var delayedPublishTask = Task.Run(() => PublishPingCommandsAsync(id, 1, cts.Token), cts.Token);
                waitState.ReadStoreReady.WaitOne(TimeSpan.FromSeconds(10));
                _waitStates.Remove(id.Value);
                await PublishPingCommandsAsync(id, 1, cts.Token).ConfigureAwait(false);

                waitState.ReadStoreContinue.Set();
                await delayedPublishTask.ConfigureAwait(false);

                // Assert
                var readModel = await QueryProcessor.ProcessAsync(new ThingyGetQuery(id), cts.Token).ConfigureAwait(false);

                readModel.PingsReceived.Should().Be(3);
            }
        }
        public OutputDataPort    Progress;          // Value from [0,1], where 0 is at reset time, and 1 when reaching Duration

        private Execution CheckCompletion <TCtx>(TCtx ctx, ref WaitState state, bool ForceUpdate, Execution running) where TCtx : IGraphInstance
        {
            Execution Result = running;

            float duration = ctx.ReadFloat(Duration);

            if (state._elapsed >= duration)
            {
                state._elapsed = duration;
                Result         = Execution.Done;
            }

            if ((ForceUpdate) || (Result == Execution.Done))
            {
                // Write outputs
                ctx.Write(Elapsed, state._elapsed);
                ctx.Write(Progress, duration > 0f ? state._elapsed / duration : 1f);
                ctx.Trigger(Output);
            }

            // If we are transitionning from running -> Done, Trigger Done
            if ((running == Execution.Running) && (Result == Execution.Done))
            {
                ctx.Log("NodeId.StopWatch Done Trigger");
                ctx.Trigger(Done);
                state._elapsed = 0;
            }

            return(Result);
        }
Пример #6
0
        protected override void GenerateMethod(Node node, StreamWriter stream, string indent)
        {
            base.GenerateMethod(node, stream, indent);

            WaitState waitState = node as WaitState;

            if (waitState == null)
            {
                return;
            }

            if (waitState.Time != null)
            {
                stream.WriteLine("{0}\t\tprotected override double GetTime(Agent pAgent)", indent);
                stream.WriteLine("{0}\t\t{{", indent);

                string retStr = RightValueCppExporter.GenerateCode(waitState.Time, stream, indent + "\t\t\t", string.Empty, string.Empty, "Time");

                if (!waitState.Time.IsPublic && (waitState.Time.IsMethod || waitState.Time.Var != null && waitState.Time.Var.IsProperty))
                {
                    retStr = string.Format("Convert.ToDouble({0})", retStr);
                }

                stream.WriteLine("{0}\t\t\treturn {1};", indent, retStr);
                stream.WriteLine("{0}\t\t}}", indent);
            }
        }
Пример #7
0
    public FSM_GameSystem(int fsmID) : base(fsmID)
    {
        //create State

        //Init
        InitState state_Init = new InitState((int)GameSystemState_ID.Init);

        state_Init.Initialize(this, null, () => { });

        //Ready
        ReadyState state_Ready = new ReadyState((int)GameSystemState_ID.Ready);

        state_Ready.Initialize(this, null, () => { });

        //SpawnNewBlock
        SpawnNewBlockState state_SpawnNewBlock = new SpawnNewBlockState((int)GameSystemState_ID.SpawnNewBlock);

        state_SpawnNewBlock.Initialize(this, null, () => { });

        //Wait
        WaitState state_Wait = new WaitState((int)GameSystemState_ID.Wait);

        state_Wait.Initialize(this, null, () => { });

        //JudgeEliminate
        JudgeEliminateState state_JudgeEliminate = new JudgeEliminateState((int)GameSystemState_ID.JudgeEliminate);

        state_JudgeEliminate.Initialize(this, null, () => { });

        //Eliminate
        EliminateState state_Eliminate = new EliminateState((int)GameSystemState_ID.Eliminate);

        state_Eliminate.Initialize(this, null, () => { });
    }
Пример #8
0
        /// <summary>
        /// Acquires a lock.
        /// </summary>
        /// <param name="newState">state to set</param>
        /// <param name="force">if true, don't wait for the lock but take it. This can be a risk!</param>
        private void setLock(WaitState newState,bool force)
        {
            if (force)
            {
                m_state = newState;
                return;
            }

            while (true)
            {
                try
                {
                    Monitor.Enter(m_todo);
                    if (m_state == WaitState.NULL)
                    {
                        m_state = newState;
                        return;
                    }
                }
                finally
                {
                    Monitor.Exit(m_todo);
                }

                Thread.Sleep(100);
            }
        }
Пример #9
0
 void Awake()
 {
     waitState    = new WaitState(this);
     lookForState = new LookForState(this);
     searchState  = new SearchState(this);
     navMeshAgent = GetComponent <NavMeshAgent> ();
 }
Пример #10
0
        /// <summary>
        /// Release the acquired lock.
        /// </summary>
        private void releaseLock()
        {
            try
            {
                Monitor.Enter(m_todo);
                m_state = WaitState.NULL;
            }
            finally
            {
                Monitor.Exit(m_todo);
            }

            if (m_todo.Count > 0)
            {
                AsyncEventDetail e;
                try
                {
                    Monitor.Enter(m_todo);
                    e = m_todo[0];
                    m_todo.Remove(e);
                }
                finally
                {
                    Monitor.Exit(m_todo);
                }

                executeAsyncEvent(e);
            }
        }
Пример #11
0
    // Start is called before the first frame update
    void Start()
    {
        var waitState = new WaitState();

        waitState.minWait = 1;

        ChangeState(waitState);
    }
Пример #12
0
 public override int Visit(WaitState waitState)
 {
     _currentContext.AssertIsValidInputPath(waitState.InputPath);
     _currentContext.AssertIsValidOutputPath(waitState.OutputPath);
     ValidateTransition(waitState.Transition);
     ValidateWaitFor(waitState.WaitFor);
     return(0);
 }
Пример #13
0
 public void DoMove()
 {
     GetComponent <Mover>().PreparePath(TargetTile);
     GetComponent <Mover>().PlayForward();
     WaitState = WaitState.Resolving;
     Engine.PathManager.ClearAll(false);
     Invoke("DoneMoving", GetComponent <Mover>().MoveTime());
 }
Пример #14
0
 public void SetCurStatu(bool isEnd, bool isWin = false)
 {
     if (item == null || item.Name == null)
     {
         return;
     }
     EnterIcon.spriteName = (isWin) ? "Ty_Legion_Shengli" : "Ty_Legion_Taotai";
     EnterIcon.gameObject.CustomSetActive(isEnd);
     WaitState.CustomSetActive(!isEnd);
 }
Пример #15
0
    void MemberWritten(string name = null, string value = null)
    {
        if (name != null)
        {
            m_namesStack.Push(name);
        }

        //Debug.LogWarning(name + "=" + value + "|" + m_state + ">>" + (m_memberEnum.Current != null ? m_memberEnum.Current.Name : ""));

        switch (m_state)
        {
        case WaitState.WaitForMembers:
        {
            m_memberEnum.MoveNext();
            IGenericMemberAcessor l_enumerationMember = m_memberEnum.Current;
            object l_createdObject = System.Activator.CreateInstance(l_enumerationMember.Type);

            OnFlush = () =>
            {
                l_enumerationMember.Value = l_createdObject;
            };

            if (l_createdObject is IGenericMemberAccessorCollection)
            {
                m_memberEnum = (l_createdObject as IGenericMemberAccessorCollection).Members.GetEnumerator();
            }

            m_memberEnum.MoveNext();
            m_state = WaitState.Field;
        }
        break;

        case WaitState.Field:
        {
            Debug.Log("Wait for field : " + name);
            m_latestName = name;
            m_state      = WaitState.Value;
        }
        break;

        case WaitState.Value:
        {
            if (m_latestName == m_memberEnum.Current.Name)
            {
                object o = null;
                m_memberEnum.Current.Value = o = Convert.ChangeType(value, m_memberEnum.Current.Type);
                //Debug.LogError("set value :: " + o);
                m_memberEnum.MoveNext();
            }

            m_state = WaitState.Field;
        }
        break;
        }
    }
Пример #16
0
        public void Save(WorldManager.SaveCallback callback = null)
        {
            Paused = true;
            var waitforsave = new WaitState(Game, "Saving...", () => SaveThreadRoutine());

            if (callback != null)
            {
                waitforsave.OnFinished += (bool b, WaitStateException e) => callback(b, e);
            }
            GameStateManager.PushState(waitforsave);
        }
Пример #17
0
 public void Ping()
 {
     lock (_threadLock) {
         _lastPing = DateTime.Now;
         if (_waitState == WaitState.Idle)
         {
             _waitState = WaitState.Waiting;
             Tools.Threads.QueueAction(ExecuteAction);
         }
     }
 }
        //private bool requestedPause = false;

        /// <summary>
        /// Runs only once at the start of the state.
        /// </summary>
        protected override void Enter()
        {
            // Reset flow control
            waitState = WaitState.Waiting;
            // Reset flags
            gm.StartEnable = false;
            gm.StopHUDCountDown();
            counting = false;
            //requestedPause = false;
            base.Enter();
        }
 protected override FSM BuildStateMachine()
 {
     STATE_MOVING = new FSM.State(OnMovingUpdate, OnMovingEnter)
     {
         Name = "Moving"
     };
     STATE_TURNING = new WaitState(TurnTime, STATE_MOVING)
     {
         Name = "Turning", OnExit = OnTurningExit
     };
     return(new FSM(STATE_MOVING));
 }
Пример #20
0
        protected override void GenerateConstructor(Node node, StreamWriter stream, string indent, string className)
        {
            base.GenerateConstructor(node, stream, indent, className);

            WaitState waitState = node as WaitState;

            if (waitState == null)
            {
                return;
            }

            stream.WriteLine("{0}\t\t\tm_ignoreTimeScale = {1};", indent, waitState.IgnoreTimeScale ? "true" : "false");
        }
Пример #21
0
        /// <summary>
        /// Resets internal state.
        /// </summary>
        public void reset()
        {
            if (m_todo != null)
            {
                m_todo.Clear();
            }

            if (m_ovpnMParser != null)
            {
                m_ovpnMParser.reset();
            }

            m_state       = WaitState.NULL;
            m_releaselock = true;
        }
Пример #22
0
        protected override void GenerateMember(Node node, StreamWriter stream, string indent)
        {
            base.GenerateMember(node, stream, indent);

            WaitState waitState = node as WaitState;

            if (waitState == null)
            {
                return;
            }

            if (waitState.Time != null)
            {
                RightValueCppExporter.GenerateClassMember(waitState.Time, stream, indent, "Time");
            }
        }
Пример #23
0
        protected override void GenerateConstructor(Node node, StreamWriter stream, string indent, string className)
        {
            base.GenerateConstructor(node, stream, indent, className);

            WaitState waitState = node as WaitState;

            if (waitState == null)
            {
                return;
            }

            if (waitState.Time != null)
            {
                RightValueCppExporter.GenerateClassConstructor(node, waitState.Time, stream, indent, "Time");
            }
        }
Пример #24
0
    protected override void Start()
    {
        base.Start();
        WaitState        waitState  = new WaitState(this, 0.5f);
        GeneralMoveState moveState  = new GeneralMoveState(this, startPos, endPos, 2f, LeanTweenType.easeInOutSine);
        Transition       waitToMove = new Transition(waitState, moveState, () => waitState.isFinished);
        Transition       moveToWait = new Transition(moveState, waitState, () => moveState.isFinished);

        AddState("wait", waitState);
        AddState("move", moveState);
        SetStartState(waitState);
        transitions.Add(waitToMove);
        transitions.Add(moveToWait);
        // Transition transition = new Transition(locateIdleState, null, () =>
        // );
    }
Пример #25
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            var obj  = JObject.Load(reader);
            var type = obj["Type"].Value <string>();

            State.IBuilder <State> result = null;

            switch (Enum.Parse(typeof(StateType), type))
            {
            case StateType.Choice:
                result = ChoiceState.GetBuilder();
                break;

            case StateType.Fail:
                result = FailState.GetBuilder();
                break;

            case StateType.Parallel:
                result = ParallelState.GetBuilder();
                break;

            case StateType.Pass:
                result = PassState.GetBuilder();
                break;

            case StateType.Succeed:
                result = SucceedState.GetBuilder();
                break;

            case StateType.Task:
                result = TaskState.GetBuilder();
                break;

            case StateType.Wait:
                result = WaitState.GetBuilder();
                break;

            case StateType.Map:
                result = MapState.GetBuilder();
                break;
            }

            serializer.Populate(obj.CreateReader(), result);

            return(result);
        }
Пример #26
0
    protected override FSM BuildStateMachine()
    {
        STATE_SHOOT_ONE = new WaitState(shootingTime)
        {
            OnExit = Shoot,
        };

        STATE_MOVING_TO = new WaitState(movingTime, STATE_SHOOT_ONE)
        {
            OnEnter = OnMovingToEnter,
            OnExit  = OnMovingToExit
        };

        STATE_SHOOT_ONE.NextState = STATE_MOVING_TO;

        return(new FSM(STATE_NO_ACTION));
    }
Пример #27
0
    private void Awake()
    {
        idleState    = new IdleState(this);
        patrolState  = new PatrolSate(this);
        chaseState   = new ChaseState(this);
        attackState  = new AttackState(this);
        waitState    = new WaitState(this);
        searchState  = new SearchState(this);
        alertState   = new AlertState(this);
        protectState = new ProtectState(this);
        stunnedState = new StunnedState(this);

        //For color testing
        auxMesh = GetComponent <MeshRenderer>();
        //
        playerDetection = GetComponent <PlayerDetection>();
        attackRange     = playerDetection.attackRadius;
    }
Пример #28
0
    protected override FSM BuildStateMachine()
    {
        STATE_MOVING = new FSM.State(OnMovingUpdate)
        {
            Name = "Moving", OnExit = StopCar
        };
        STATE_AIMING = new TimedState(3.0f, OnAimUpdate)
        {
            Name    = "Aiming",
            OnEnter = StartAiming
        };
        STATE_SHOOTING = new WaitState(2, STATE_MOVING)
        {
            Name = "Shooting", OnEnter = Shoot, OnExit = SelectRandomDirection
        };

        return(new FSM(STATE_NO_ACTION));
    }
Пример #29
0
    // Constructor
    public RecruitmentPattern(Unit unit)
    {
        _unit = unit;

        waitBehavior    = new WaitBehavior(_unit);
        seekBehavior    = new SeekBehavior(_unit);
        pursuitBehavior = new PursuitBehavior(_unit);

        waitState           = new WaitState(this, waitBehavior);
        followLeaderState   = new FollowLeaderState(this, seekBehavior);
        holdPositionState   = new HoldPositionState(this, waitBehavior);
        defendPositionState = new DefendPositionState(this, pursuitBehavior);
        attackEnemyState    = new AttackEnemyState(this, pursuitBehavior);
        attackTargetState   = new AttackLeaderTargetState(this, seekBehavior);
        workState           = new WorkState(this, waitBehavior);

        currentState = waitState;
    }
    public override void _Ready()
    {
        cannon             = GetNode <Position2D>("Cannon");
        animationPlayer    = GetNode <AnimationPlayer>("AnimationPlayer");
        bulletCaseParticle = GetNode <CPUParticles2D>("BulletCaseParticle");
        shootSound         = GetNode <AudioStreamPlayer2D>("ShootAudioPlayer");


        STATE_READY = new FSM.State(WeaponReadyUpdate)
        {
            Name = "Ready"
        };
        STATE_TIMEOUT = new WaitState(TimeoutDuration, STATE_READY)
        {
            Name = "Reloading"
        };
        machine = new FSM(STATE_READY);
    }
        private void cmdExport_Click(object sender, EventArgs e)
        {
            Uri collectionUri = new Uri(txtCollectionUri.Text);
            string teamProject = txtTeamProject.Text;

            SaveFileDialog dlg = new SaveFileDialog();
            dlg.CheckPathExists = true;
            dlg.Title = "Export Area/Iteration structure";
            dlg.DefaultExt = ".nodes";
            dlg.Filter = "TFS Node Structure (*.nodes)|*.nodes";
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                string filename = dlg.FileName;

                var networkCredential = new NetworkCredential("username", "password");
                var basicAuthCredential = new BasicAuthCredential(networkCredential);
                var tfsCredential = new TfsClientCredentials(basicAuthCredential);

                using(var tfs = new TfsTeamProjectCollection(collectionUri, tfsCredential))
                //using (var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(collectionUri))
                using (WaitState waitState = new WaitState(this))
                {
                    tfs.Authenticate();
                    tfs.EnsureAuthenticated();

                    //  get the configuration server
                    var svr = tfs.ConfigurationServer;

                    //  get the configuration service
                    var svc = tfs.GetService<TeamSettingsConfigurationService>();

                    // get the common structure service
                    var css = tfs.GetService<ICommonStructureService4>();

                    //  get the spotlabs project
                    var prj = css.GetProjectFromName(txtTeamProject.Text);

                    //  get the configurations
                    var cfg = svc.GetTeamConfigurationsForUser(new[] { prj.Uri }).Single<TeamConfiguration>();

                    //  get the settings
                    var opt = cfg.TeamSettings;

                    //  get the iteration schedule
                    var schedule = css.GetIterationDates(prj.Uri);

                    Console.WriteLine(opt.ToString());

                    var store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
                    var proj = store.Projects[teamProject];

                    using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
                    using (StreamWriter writer = new StreamWriter(fs))
                    {
                        writer.WriteLine("NODES");
                        writer.WriteLine(String.Format("{0}, Version {1}", Application.ProductName, Application.ProductVersion));
                        writer.WriteLine("Copyright (C) 2010 " + Application.CompanyName);

                        if (chkAreaStructure.Checked)
                        {
                            WriteNodes(proj.AreaRootNodes, writer, "A");
                        }

                        if (chkIterationStructure.Checked)
                        {
                            WriteNodes(proj.IterationRootNodes, writer, "I");
                        }

                        writer.Close();
                    }
                }

                MessageBox.Show("Export successful.");
            }
        }
Пример #32
0
        protected bool readBytes( NetworkStream ns, MemoryStream response, String waitFor, bool machresponseend )
        {
            bool error = false;
            byte[] readBytes = new byte[client.ReceiveBufferSize];
            int nbytes = 0;
            String lastBoundary = System.String.Empty;
            WaitState state = new WaitState(true);
            Timer aTimer = new System.Threading.Timer(new TimerCallback(this.StopWaiting), state, Timeout.Infinite,  Timeout.Infinite);

            if ( log.IsDebugEnabled ) log.Debug ( "Reading response" );
            // We wait until data is available but only if Stream is open
            // We setup a timer that stops the loop after x seconds
            for ( aTimer.Change(this.timeoutResponse,  Timeout.Infinite); !error && ns.CanRead && ns.CanWrite && !ns.DataAvailable && state.Status; ){Thread.Sleep(50);}
            state.Status = true;

            // If I can read from NetworkStream and there is
            // some data, I get it
            for ( aTimer.Change(this.timeoutResponse,  Timeout.Infinite); !error && ns.CanRead && state.Status && (ns.DataAvailable || !(lastBoundary.Equals(waitFor)) ) ; nbytes = 0) {
                try {
                    if ( ns.DataAvailable ) {
            #if MONO
                        // Reinitialize buffer to make mono happy
                        readBytes = new byte[client.ReceiveBufferSize];
            #endif
                        nbytes = ns.Read( readBytes, 0, client.ReceiveBufferSize );
                    } else
                        Thread.Sleep(50);
                } catch ( Exception e ) {
                    error = true;
                    nbytes = 0;
                    lastErrorMessage = "Read error";
                    if ( log.IsErrorEnabled ) log.Error ( lastErrorMessage, e );
                }
                if ( !error && nbytes>0 ) {
                    if ( log.IsDebugEnabled ) log.Debug ( "Read " + nbytes + " bytes" );
                    response.Write( readBytes, 0, nbytes );
                    // Only test waitfor secuence if there is no data for reading
                    // and there are enouth data available for comparing
                    if ( !ns.DataAvailable && response.Length>waitFor.Length ) {
                        // The waitfor text must be the last portion of the response
                        if ( machresponseend ) {
                            response.Seek(response.Length - waitFor.Length, SeekOrigin.Begin);
                            response.Read(readBytes,  0, waitFor.Length);
                            lastBoundary = Encoding.ASCII.GetString(readBytes, 0, waitFor.Length);
                        // The waitfor text must be in the begining of the last line of the response
                        } else {
                            response.Seek(0, SeekOrigin.Begin);
                            StreamReader reader = new StreamReader(response);
                            String line = System.String.Empty;
                            for ( System.String tmp=reader.ReadLine(); tmp!=null ; line=tmp, tmp=reader.ReadLine() ) {}
                            if ( line!=null && line.Length>=waitFor.Length )
                                lastBoundary = line.Substring(0, waitFor.Length);
                            reader.DiscardBufferedData();
                            reader=null;
                            response.Seek (0, SeekOrigin.End);
                        }
                    }
                    // Reset timer
                    aTimer.Change(this.timeoutResponse,  Timeout.Infinite);
                    state.Status = true;
                }
            }
            response.Flush();
            if ( log.IsDebugEnabled ) log.Debug ( String.Concat("Reading response finished. Error: ", error) );
            // Discard response if there has been a read error.
            if ( error )
                response.SetLength(0);
            else if ( response.Length==0 )
                error = true;
            return !error;
        }
Пример #33
0
        /// <summary>
        /// Release the acquired lock.
        /// </summary>
        private void releaseLock()
        {
            try
            {
                Monitor.Enter(m_todo);
                m_state = WaitState.NULL;
            }
            finally
            {
                Monitor.Exit(m_todo);
            }

            if (m_todo.Count > 0)
            {
                AsyncEventDetail e;
                try
                {
                    Monitor.Enter(m_todo);
                    e = m_todo[0];
                    m_todo.Remove(e);
                }
                finally
                {
                    Monitor.Exit(m_todo);
                }

                executeAsyncEvent(e);
            }
        }
        /// <summary>
        /// Resets internal state.
        /// </summary>
        public void reset() {
            m_pkcs11count = 0;

            if(m_pkcs11details != null)
                m_pkcs11details.Clear();

            if(m_todo != null)
                m_todo.Clear();

            if (m_ovpnMParser != null)
                m_ovpnMParser.reset();

            m_state = WaitState.NULL;
            m_releaselock = true;
        }
Пример #35
0
        /// <summary>
        /// Acquires a lock.
        /// </summary>
        /// <param name="newState">state to set</param>
        /// <param name="force">if true, don't wait for the lock but take it. This can be a risk!</param>
        private void setLock(WaitState newState, bool force)
        {
            if (force)
            {
                m_state = newState;
                return;
            }

            while (true)
            {
                try
                {
                    Monitor.Enter(m_todo);
                    if (m_state == WaitState.NULL)
                    {
                        m_state = newState;
                        return;
                    }
                }
                finally
                {
                    Monitor.Exit(m_todo);
                }

                Thread.Sleep(100);
            }
        }
Пример #36
0
 /// <summary>
 /// Acquires a lock. Waits, until the lock is possible.
 /// </summary>
 /// <param name="newState">state to set</param>
 private void setLock(WaitState newState)
 {
     setLock(newState, false);
 }
Пример #37
0
        /// <summary>
        /// Resets internal state.
        /// </summary>
        public void reset()
        {
            m_logs.logDebugLine(5, "resetting logic");

            m_pkcs11count = 0;

            if (m_pkcs11details != null)
                m_pkcs11details.Clear();

            if (m_todo != null)
                m_todo.Clear();

            if (m_ovpnMParser != null)
                m_ovpnMParser.reset();

            m_state = WaitState.NULL;
            m_releaselock = true;
        }
        private void cmdImport_Click(object sender, EventArgs e)
        {
            Uri collectionUri = new Uri(txtCollectionUri.Text);
            string teamProject = txtTeamProject.Text;

            OpenFileDialog dlg = new OpenFileDialog();
            dlg.CheckFileExists = true;
            dlg.Title = "Import Area/Iteration structure";
            dlg.DefaultExt = ".nodes";
            dlg.Filter = "TFS Node Structure (*.nodes)|*.nodes";
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                string filename = dlg.FileName;

                var networkCredential = new NetworkCredential("username", "password");
                var basicAuthCredential = new BasicAuthCredential(networkCredential);
                var tfsCredential = new TfsClientCredentials(basicAuthCredential);
                using (var tfs = new TfsTeamProjectCollection(collectionUri, tfsCredential))
                //using (var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(collectionUri, new UICredentialsProvider()))
                using (WaitState waitState = new WaitState(this))
                {
                    tfs.Authenticate();
                    tfs.EnsureAuthenticated();

                    WorkItemStore store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
                    Project proj = store.Projects[teamProject];

                    NodeInfo rootAreaNode = null;
                    NodeInfo rootIterationNode = null;

                    var css = (ICommonStructureService4)tfs.GetService(typeof(ICommonStructureService4));
                    foreach (NodeInfo info in css.ListStructures(proj.Uri.ToString()))
                    {
                        if (info.StructureType == "ProjectModelHierarchy")
                        {
                            rootAreaNode = info;
                        }
                        else if (info.StructureType == "ProjectLifecycle")
                        {
                            rootIterationNode = info;
                        }
                    }

                    using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
                    using (StreamReader reader = new StreamReader(fs))
                    {
                        string nextLine = reader.ReadLine();
                        if (nextLine != "NODES")
                        {
                            MessageBox.Show("Wrong file format!");
                            return;
                        }

                        reader.ReadLine();
                        reader.ReadLine();

                        while (!reader.EndOfStream)
                        {
                            nextLine = reader.ReadLine();
                            if (nextLine.StartsWith("A") && chkAreaStructure.Checked)
                            {
                                CreateNode(css, nextLine.Substring(2), rootAreaNode);
                            }
                            else if (nextLine.StartsWith("I") && chkIterationStructure.Checked)
                            {
                                CreateNode(css, nextLine.Substring(2), rootIterationNode);
                            }
                            else
                            { // Ignore other lines
                            }
                        }
                        reader.Close();
                    }

                    MessageBox.Show("Import successful.");
                }
            }
        }
Пример #39
0
 protected Coroutine Start()
 {
     mState = WaitState.Run;
     return WaitHelp.Instance.StartCoroutine(this);
 }