Beispiel #1
0
 // Update is called once per frame
 void LateUpdate()
 {
     if (mActive && !particleSystem.IsAlive())
     {
         PoolController.ReleaseAuto(transform);
     }
 }
Beispiel #2
0
        // Code that runs on entering the state.
        public override void OnEnter()
        {
#if POOLMANAGER
            Debug.LogError("Not implemented!");
#else
            Transform t = PoolController.Spawn(group.Value, type.Value, name.IsNone ? type.Value : name.Value, parent.Value == null ? null : parent.Value.transform);
#endif
            if (t != null)
            {
                if (!toGameObject.IsNone)
                {
                    toGameObject.Value = t.gameObject;
                }

                if (!position.IsNone)
                {
                    t.position = position.Value;
                }
            }
            else
            {
                Debug.LogWarning("Unable to spawn: " + type.Value + " group: " + group.Value);
            }

            Finish();
        }
Beispiel #3
0
    public override void Setup()
    {
        pipeList       = new List <AbstractControl>();
        pipeLinkedList = new LinkedList <AbstractControl>();
        for (int i = 0; i < 3; i++)
        {
            Vector3 pos;
            if (i == 0)
            {
                pos = new Vector3(gameView.localPosition.x + 40, gameView.localPosition.y + GetRandomLocalY());
            }
            else
            {
                pos = new Vector3(gameView.localPosition.x + i * 40 + GetRandomLocalX(),
                                  gameView.localPosition.y + GetRandomLocalY());
            }

            pipeControl = PoolController.Use(ControlPrefab, pos) as PipeControl;
            pipeControl.PipeOffScreen += OnPipeOffScreen;
            pipeLinkedList.AddLast(pipeControl);
            pipeList.Add(pipeControl);
        }
        if (!startGame)
        {
            StopPipe();
        }
    }
Beispiel #4
0
 public static HubTuple New(IListWindow window)
 {
     var pc = PoolController.Get(ListElementPool.Instance);
     var le = pc.Get<HubTuple>(window.TupleContainer.transform);
     le._Window = (AbstractWindow)window;
     return le;
 }
Beispiel #5
0
    Projectile Fire()
    {
        if (chargeLevel < 0 || chargeLevel >= projectiles.Length)
        {
            return(null);
        }

        GameObject projectilePrefab = projectiles[chargeLevel];

        if (projectilePrefab == null)
        {
            return(null);
        }

        GameObject go = PoolController.Activate(projectilePrefab, transform.position, transform.rotation);

        if (go != null)
        {
            // Successfully shot!!!
            energy = 0;
            chargeTimer.SetTime(chargeDelay);
            isCharging = false;
            AudioController.Instance.PlayOneShot(fireClip);
            return(go.GetComponent <Projectile>());
        }
        else
        {
            return(null);
        }
    }
    IEnumerator DoRelease()
    {
        bool kinematic = false;

        if (rigidbody)
        {
            kinematic                 = rigidbody.isKinematic;
            rigidbody.velocity        = Vector3.zero;
            rigidbody.angularVelocity = Vector3.zero;
            rigidbody.isKinematic     = true;
        }

        if (releaseDelay > 0)
        {
            yield return(new WaitForSeconds(releaseDelay));
        }
        else
        {
            yield return(new WaitForFixedUpdate());
        }

        transform.position = Vector3.zero;
        transform.rotation = Quaternion.identity;

        if (rigidbody)
        {
            rigidbody.isKinematic = kinematic;
        }

        PoolController.ReleaseAuto(transform);
    }
    public void DropCoins()
    {
        int coinCount = Random.Range(coinsMin, coinsMax);

        for (int i = 0; i < coinCount; i++)
        {
            GameObject obj = poolYard.pool_item_Coin.GetPoolObject();
            if (obj == null)
            {
                return;
            }
            obj.transform.position = transform.position + (Vector3)(Random.insideUnitCircle * lootDropRadius);
            obj.transform.rotation = transform.rotation;
            obj.SetActive(true);
        }

        if (DropsLoot)
        {
            PoolController theLootPool = lootTable[Random.Range(0, 3)];
            GameObject     obj;
            obj = theLootPool.GetPoolObject();
            if (obj == null)
            {
                return;
            }
            obj.transform.position = transform.position + (Vector3)(Random.insideUnitCircle * lootDropRadius);
            obj.transform.rotation = transform.rotation;
            obj.SetActive(true);
        }
    }
Beispiel #8
0
        public PoolController GetPoolController(Fsm fsm, bool createIfNotFound)
        {
            PoolController poolCtrl = null;

            switch (from)
            {
            case FromType.Owner:
                if (fsm == null)
                {
                    return(null);
                }
                if (fsm.Owner == null)
                {
                    return(null);
                }

                poolCtrl = fsm.Owner.GetComponent <PoolController>();
                if (!poolCtrl && createIfNotFound)
                {
                    poolCtrl = fsm.Owner.gameObject.AddComponent <PoolController>();
                }
                break;

            case FromType.GameObject:
                if (gameObject == null)
                {
                    return(null);
                }
                if (gameObject.IsNone || gameObject.Value == null)
                {
                    return(null);
                }

                poolCtrl = gameObject.Value.GetComponent <PoolController>();
                if (!poolCtrl && createIfNotFound)
                {
                    poolCtrl = gameObject.Value.AddComponent <PoolController>();
                }
                break;

            case FromType.Group:
                if (groupName == null)
                {
                    return(null);
                }
                if (groupName.IsNone || string.IsNullOrEmpty(groupName.Value))
                {
                    return(null);
                }

                poolCtrl = PoolController.GetPool(groupName.Value);
                if (!poolCtrl && createIfNotFound)
                {
                    poolCtrl = PoolController.CreatePool(groupName.Value);
                }
                break;
            }

            return(poolCtrl);
        }
Beispiel #9
0
 void OnEntityStateChange(EntityBase ent)
 {
     if ((EntityState)ent.state == EntityState.Dead)
     {
         PoolController.Spawn(deathSpawnGroup, deathSpawnType, deathSpawnType, null, ent.transform.position, Quaternion.identity);
     }
 }
 private void MakeInstance()
 {
     if (Instance == null)
     {
         Instance = this;
     }
 }
Beispiel #11
0
    void Awake() {
        mInstance = this;

        mCtrl = GetComponent<PoolController>();

        foreach(Group grp in groups)
            grp.ComputeItemRange();
    }
Beispiel #12
0
        public static ConsoleElement New(IListWindow window)
        {
            var pc = PoolController.Get(ListElementPool.Instance);
            var le = pc.Get <ConsoleElement>(window.TupleContainer.transform);

            le._Window = (AbstractWindow)window;
            return(le);
        }
Beispiel #13
0
 private void Awake()
 {
     Instance = this;
     if (InitializeOnAwake)
     {
         Initialize();
     }
 }
Beispiel #14
0
 void OnLand(PlatformerController ctrl)
 {
     if (state != (int)EntityState.Invalid)
     {
         Vector2 p = transform.position;
         PoolController.Spawn("fxp", "landdust", "landdust", null, p);
     }
 }
Beispiel #15
0
        public static Drone Load(SDrone data)
        {
            var d = PoolController.Get(ObjectPool.Instance).Get <Drone>(null, true);

            d.gameObject.SetActive(true);

            return(d.LoadState(data));
        }
Beispiel #16
0
    GameObject ShootAtPlayer()
    {
        GameObject spawnedObject = PoolController.Activate(objectToSpawn, transform.position, transform.rotation);
        Unit       spawnedUnit   = spawnedObject.GetComponent <Unit>();

        spawnedUnit.TurnThisTowards(Player.Instance.transform.position);
        return(spawnedObject);
    }
Beispiel #17
0
        public BaseProcedurePool()
        {
            m_poolCtrl = new PoolController(this);

            m_typeInfoDict     = new Dictionary <string, MessageTypeInfo>();
            m_typePairDict     = new Dictionary <string, string>();
            m_recvCallbackDict = new Dictionary <string, Action <object> >();
            //m_sendFunctionDict	= new Dictionary<string, Action<object>>();
        }
Beispiel #18
0
    void OnLanded(PlatformerController ctrl)
    {
        mJump         = false;
        mLastJumpTime = Time.fixedTime;

        Vector2 p = transform.position;

        PoolController.Spawn("fxp", "landdust", "landdust", null, p);
    }
 void Awake()
 {
     poolYard  = GameObject.FindGameObjectWithTag("PoolYard").GetComponent <PoolYard>();
     lootTable = new PoolController[] {
         poolYard.pool_item_Page,
         poolYard.pool_item_Potion,
         poolYard.pool_item_Attack
     };
 }
Beispiel #20
0
        public static NoFlyZone Load(SNoFlyZone data)
        {
            var nfz = PoolController.Get(ObjectPool.Instance).Get <NoFlyZone>(null, true);

            nfz.InPool = false;
            nfz._Data  = new NFZData(data, nfz);
            SimManager.AllNFZ.Add(nfz.UID, nfz);
            return(nfz);
        }
        public void ControllerPerformedSpecifiedNumberOfAttempts_ControllerStopsReattempting()
        {
            _controller = new PoolController<TestKey, TestResource>(_settings, _noObjectPoolMock.Object);
            _noObjectDirection.AttemptsNumber = 7;

            _controller.Obtain(_key, out _outPoolObject, _noObjectDirection);

            _noObjectPoolMock.Verify(x => x.TryObtain(_key, out _outPoolObject, It.IsAny<Func<TestKey, TestResource>>()), Times.Exactly(7));
        }
 // Update is called once per frame
 void Update()
 {
     if (mSpawned && mActive)
     {
         if (!mAnimDat.isPlaying)
         {
             PoolController.ReleaseAuto(transform);
         }
     }
 }
    public override void ReusePrefab()
    {
        AbstractControl lastearth = earthList[earthList.Count - 1];
        Vector3         pos       = new Vector2(lastearth.transform.localPosition.x + scalePref,
                                                lastearth.transform.localPosition.y);
        AbstractControl go = PoolController.Use(ControlPrefab, pos) as EarthControl;

        earthList.Add(go);
        earthList.Remove(earthList[earthList.Count - 1]);
    }
    public override void ReusePrefab()
    {
        AbstractControl lastBgControl = backGroundList[backGroundList.Count - 1];
        Vector3         pos           = new Vector2(lastBgControl.transform.localPosition.x + scalePref,
                                                    lastBgControl.transform.localPosition.y);
        AbstractControl go = PoolController.Use(ControlPrefab, pos) as BackgroundControl;

        backGroundList.Add(go);
        backGroundList.Remove(backGroundList[backGroundList.Count - 1]);
    }
        public void AllAttemptsWereTriedAndPoolDidNotFindAvailableObject_ControllerReturnsDefault()
        {
            _controller = new PoolController<TestKey, TestResource>(_settings, _noObjectPoolMock.Object);
            _noObjectDirection.AttemptsNumber = 3;
            _noObjectDirection.OneIntervalBetweenAttemptsInSeconds = 0;

            var getStatus = _controller.Obtain(_key, out _outPoolObject, _noObjectDirection);

            Assert.That(getStatus, Is.False);
            Assert.That(_outPoolObject, Is.Null);
        }
Beispiel #26
0
 private void Awake()
 {
     if (instance == null)
     {
         instance = this;
     }
     else
     {
         Destroy(gameObject);
     }
 }
Beispiel #27
0
    void Awake()
    {
        mInstance = this;

        mCtrl = GetComponent <PoolController>();

        foreach (Group grp in groups)
        {
            grp.ComputeItemRange();
        }
    }
Beispiel #28
0
    void OnBuddyHPChange(Stats aStat, float delta)
    {
        int deadInd = -1;
        int stunInd = -1;

        for (int i = 0; i < mBuddyStats.Length; i++)
        {
            if (mBuddyStats[i] == aStat)
            {
                if (aStat.lastDamageSource && aStat.lastDamageSource.stun)
                {
                    stunInd = i;
                }

                if (aStat.curHP <= 0)
                {
                    deadInd = i;
                    mNumDead++;
                }
            }
        }

        if (deadInd != -1)
        {
            buddies[deadInd].SetActive(false);
            Vector3 pt = buddies[deadInd].collider.bounds.center;
            pt.z = 0.0f;
            PoolController.Spawn(deathSpawnGroup, mDeathSpawnType, mDeathSpawnType, null, pt, Quaternion.identity);
        }

        projectile.SetActive(mNumDead == 0);

        if (mNumDead == mBuddyStats.Length)
        {
            state = (int)EntityState.Dead;
        }
        else
        {
            if (deadInd != -1)
            {
                for (int i = 0; i < mBuddyAnims.Length; i++)
                {
                    if (i != deadInd)
                    {
                        mBuddyAnims[i].Play("sad");
                    }
                }
            }
            else if (stunInd != -1)
            {
                state = (int)EntityState.Stun;
            }
        }
    }
Beispiel #29
0
    public void Start()
    {
        res = GameObject.FindObjectOfType <PlayerResources>();
        StartCoroutine("Cooldown");

        // Handle visuals

        GameObject.FindObjectOfType <WeaponVisController>().AddWeapon(weaponType);

        pool = GameObject.FindObjectOfType <PoolController>();
    }
Beispiel #30
0
    public override void ReusePrefab()
    {
        AbstractControl lastPipe = pipeList[pipeList.Count - 1];
        Vector3         pos      = new Vector2(lastPipe.transform.localPosition.x + GetRandomLocalX(),
                                               gameView.transform.localPosition.y + GetRandomLocalY());
        AbstractControl go = PoolController.Use(ControlPrefab, pos) as PipeControl;

        pipeList.Add(go);
        pipeList.Remove(pipeList[pipeList.Count - 1]);
        pipeLinkedList.AddLast(go);
    }
Beispiel #31
0
 public void OpenInfoWindow()
 {
     if (InfoWindow == null)
     {
         InfoWindow        = PoolController.Get(WindowPool.Instance).Get <JobWindow>(UIManager.Transform);
         InfoWindow.Source = this;
     }
     else
     {
         InfoWindow.transform.SetAsLastSibling();
     }
 }
Beispiel #32
0
        public static Hub Load(SHub data, List <SDrone> drones, List <SBattery> batteries)
        {
            Hub hub = PoolController.Get(ObjectPool.Instance).Get <Hub>(null, true);

            hub.transform.position = data.position;
            hub.transform.SetParent(null);
            hub.gameObject.SetActive(true);
            hub.InPool = false;
            SimManager.AllHubs.Add(hub.UID, hub);

            hub._Data = new HubData(data, hub, drones, batteries);
            return(hub);
        }
Beispiel #33
0
    public virtual GameObject Spawn(Quaternion spawnRotation)
    {
        Unit _unit = objectToSpawn.GetComponent <Unit>();

        if (_unit != null)
        {
            return(PoolController.Activate(objectToSpawn, transform.position, spawnRotation));
        }
        else
        {
            Debug.LogError("[UnitSpawner] objectToSpawn is not a Unit!");
            return(null);
        }
    }
Beispiel #34
0
    void Start()
    {
        Obstacle = (GameObject)Resources.Load("Prefabs/Obstacle");

        GameController = Instantiate((GameObject) Resources.Load("Prefabs/GameController"));
        ObstacleGen = Instantiate((GameObject)Resources.Load("Prefabs/ObstacleGenerator"));
        pool = GameController.GetComponent<PoolController>();
        obstacleGenerator = ObstacleGen.GetComponent<ObstacleGenerator>();

        pool.setObstacles(Obstacle);
        obstacleGenerator.setPoolController(pool);

        pool.enabled = true;
        obstacleGenerator.enabled = true;
    }
        public ThreadPool(ThreadPoolSettings settings, IThreadPoolTaskResultNotifier taskResultNotifier = null)
        {
            _settings = settings;
            _taskResultNotifier = taskResultNotifier;
            _poolController = CreateThreadPoolControllerInstance();

            _noIdleWorkerDirection = new DirectionIfNoObjectIsAvailable<int, ThreadWorker>
            {
                CreateDelegateIfNoObjectIsAvailable = CreateWorker,
                AttemptsNumber = _settings.WaitingSettings != null
                                 ? _settings.WaitingSettings.WaitingsNumber + 1
                                 : 1,
                OneIntervalBetweenAttemptsInSeconds = _settings.WaitingSettings != null
                                                      ? _settings.WaitingSettings.OneWaitingTimespanInSeconds
                                                      : 0,
            };

            _managerThread = new Thread(AssignTasksToWorkers)
            {
                Name = ConfigurationManager.AppSettings["managerThreadName"],
                IsBackground = true,
            };
            _managerThread.Start();
        }
        public void ReleaseWasCalled_ControllerForgotsObjectToKeyMapping()
        {
            _settings.CallingReleaseOperationWillHappen = true;
            _controller = new PoolController<TestKey, TestResource>(_settings, _successPoolMock.Object);

            _controller.Obtain(_key, out _outPoolObject, null);
            _controller.Release(_outPoolObject);

            Assert.That(_controller.ObtainedObjectToItsKey.Count, Is.EqualTo(0));
        }
        public void ReleasingOfNotObtainedObject_DetailedExceptionIsThrown()
        {
            _settings.CallingReleaseOperationWillHappen = true;
            _controller = new PoolController<TestKey, TestResource>(_settings, _successPoolMock.Object);

            var resource = new TestResource(string.Empty);
            var hintException = Assert.Throws<InvalidPoolOperationException<TestKey, TestResource>>(
                () => _controller.Release(resource));

            Assert.That(hintException.Message, Is.EqualTo("Only obtained objects are allowed to be released"));
            Assert.That(hintException.Key, Is.Null);
            Assert.That(hintException.Object, Is.EqualTo(resource));
        }
        public void ReleaseWasCalled_PoolIsCalled()
        {
            _settings.CallingReleaseOperationWillHappen = true;
            _controller = new PoolController<TestKey, TestResource>(_settings, _successPoolMock.Object);
            TestResource outResource1;
            TestResource outResource2;
            TestResource outResource3;
            var key1 = new TestKey { Identifier = 100 };
            var key2 = new TestKey { Identifier = 200 };

            _controller.Obtain(key1, out outResource1, null);
            _controller.Obtain(key1, out outResource2, null);
            _controller.Obtain(key2, out outResource3, null);
            _controller.Release(outResource1);
            _controller.Release(outResource2);
            _controller.Release(outResource3);

            _successPoolMock.Verify(x => x.Release(key1, outResource1), Times.Once);
            _successPoolMock.Verify(x => x.Release(key1, outResource2), Times.Once);
            _successPoolMock.Verify(x => x.Release(key2, outResource3), Times.Once);
        }
 public void setPoolController(PoolController pool)
 {
     this.pool = pool;
 }
        public void ObtainWasCalled_PoolIsCalled_ProvidedObjectIsReturned()
        {
            _controller = new PoolController<TestKey, TestResource>(_settings, _successPoolMock.Object);

            var getStatus = _controller.Obtain(_key, out _outPoolObject, null);

            Assert.That(getStatus, Is.True);
            Assert.That(_outPoolObject.Value, Is.EqualTo(_key.Identifier + " 1"));
            _successPoolMock.Verify(x => x.TryObtain(_key, out _outPoolObject, null), Times.Once);
        }
        public void ReleasingWasNotPromised_ControllerIgnoresDirectionToWaitAndOrderPoolToCreateNewObject()
        {
            _settings.CallingReleaseOperationWillHappen = false;
            _controller = new PoolController<TestKey, TestResource>(_settings, _successPoolMock.Object);
            Func<TestKey, TestResource> createDelegate = key => new TestResource(Mocks.Pool.ResourceValueAfterWaitings);
            var directionToWaitForAvailableObject = new DirectionIfNoObjectIsAvailable<TestKey, TestResource>
            {
                AttemptsNumber = 5,
                OneIntervalBetweenAttemptsInSeconds = 10,
                CreateDelegateIfNoObjectIsAvailable = createDelegate,
            };

            _controller.Obtain(_key, out _outPoolObject, directionToWaitForAvailableObject);

            _successPoolMock.Verify(x => x.TryObtain(_key, out _outPoolObject, createDelegate), Times.Once);
            _successPoolMock.Verify(x => x.TryObtain(_key, out _outPoolObject, null), Times.Never);
        }
        public void ReleasingWasNotPromised_ControllerDoesNotRememberObtainedObjects()
        {
            _settings.CallingReleaseOperationWillHappen = false;
            _controller = new PoolController<TestKey, TestResource>(_settings, _successPoolMock.Object);

            _controller.Obtain(_key, out _outPoolObject, null);

            Assert.That(_controller.ObtainedObjectToItsKey.Count, Is.EqualTo(0));
        }
        public void ReleasingWasPromised_ControllerCanRecallKeyForEachObtainedValue()
        {
            _settings.CallingReleaseOperationWillHappen = true;
            _controller = new PoolController<TestKey, TestResource>(_settings, _successPoolMock.Object);
            TestResource outResource1;
            TestResource outResource2;
            TestResource outResource3;
            var key1 = new TestKey { Identifier = 100 };
            var key2 = new TestKey { Identifier = 200 };

            _controller.Obtain(key1, out outResource1, null);
            _controller.Obtain(key1, out outResource2, null);
            _controller.Obtain(key2, out outResource3, null);

            Assert.That(_controller.ObtainedObjectToItsKey[outResource1], Is.EqualTo(key1));
            Assert.That(_controller.ObtainedObjectToItsKey[outResource2], Is.EqualTo(key1));
            Assert.That(_controller.ObtainedObjectToItsKey[outResource3], Is.EqualTo(key2));
        }
        public void CreateDelegateIsSpecified_PoolIsCalledWithIt_ButOnlyLastTime()
        {
            Func<TestKey, TestResource> createDelegate = key => new TestResource("on fifth call");
            int curCallNumber = 0;
            TestResource orderControllingOutResource;
            var callsOrderControllingPoolMock = new Mock<IPool<TestKey, TestResource>>(MockBehavior.Strict);
            callsOrderControllingPoolMock.Setup(x => x.TryObtain(_key, out orderControllingOutResource, null))
                                         .Returns(false)
                                         .Callback(() => Assert.That(++curCallNumber, Is.InRange(1, 4)));
            callsOrderControllingPoolMock.Setup(x => x.TryObtain(_key, out orderControllingOutResource, createDelegate))
                                         .OutCallback((TestKey key, out TestResource outResource, Func<TestKey,TestResource> createDel)
                                             => outResource = createDelegate(key))
                                         .Returns<TestKey, TestResource, Func<TestKey, TestResource>>((key, outResource, createDel) => true)
                                         .Callback(() => Assert.That(++curCallNumber, Is.EqualTo(5)));
            _controller = new PoolController<TestKey, TestResource>(_settings, callsOrderControllingPoolMock.Object);

            _noObjectDirection.AttemptsNumber = 5;
            _noObjectDirection.CreateDelegateIfNoObjectIsAvailable = createDelegate;
            var getStatus = _controller.Obtain(_key, out _outPoolObject, _noObjectDirection);

            Assert.That(getStatus, Is.True);
            Assert.That(_outPoolObject.Value, Is.EqualTo("on fifth call"));
            callsOrderControllingPoolMock.Verify(x => x.TryObtain(_key, out _outPoolObject, null), Times.Exactly(4));
            callsOrderControllingPoolMock.Verify(x => x.TryObtain(_key, out _outPoolObject, createDelegate), Times.Once);
            callsOrderControllingPoolMock.Verify(x => x.TryObtain(It.IsAny<TestKey>(), out _outPoolObject, It.IsAny<Func<TestKey, TestResource>>()),
                                                 Times.Exactly(5));
        }
        private PoolController<int, ThreadWorker> CreateThreadPoolControllerInstance()
        {
            var workerActions = new ObjectActionsBasedOnDelegateOrInterface<ThreadWorker>(new ExplicitlyDefinedObjectActions<ThreadWorker>());
            var objectUtilizer = new ObjectUtilizer<int, ThreadWorker>();

            var basicPoolSettings = new PoolItemsStorageSettings
            {
                AllowOnlyOneUserPerObject = true,
                BalancingStrategy = _settings.BalancingStrategy,
                MaxObjectsCountPerKey = _settings.MaxWorkersCount,
                ThrowIfCantCreateObjectBecauseOfReachedLimit = false,
            };
            var basicPool = new PoolItemsStorage<int, ThreadWorker>(basicPoolSettings, workerActions, objectUtilizer);

            var stateMonitoringSettings = new PWObjectStateMonitoringSettings
            {
                MaxObjectIdleTimeSpanInSeconds = _settings.MaxObjectIdleTimeSpanInSeconds,
                MaxObjectLifetimeInSeconds = _settings.MaxObjectIdleTimeSpanInSeconds,
                TimeSpanBetweenRevivalsInSeconds = _settings.MonitorTimeSpanInSeconds,
            };
            var stateMonitoringPool = new PWObjectStateMonitoringWrapper<int, ThreadWorker>(stateMonitoringSettings,
                                                                                            basicPool,
                                                                                            workerActions,
                                                                                            objectUtilizer);

            var singleUsePool = new PWSingleUseEnforcingWrapper<int, ThreadWorker>(stateMonitoringPool);

            var autoReleasingPool = new PWAutoReleasingWrapper<int, ThreadWorker>(singleUsePool);

            var poolControllerSettings = new PoolControllerSettings
            {
                CallingReleaseOperationWillHappen = true,
            };
            var controller = new PoolController<int, ThreadWorker>(poolControllerSettings, autoReleasingPool);
            autoReleasingPool.SetPoolController(controller);
            return controller;
        }
        public void NullNoObjectDirection_ControllerPerformsOneAttemptsWithoutCreateDelegate()
        {
            _controller = new PoolController<TestKey, TestResource>(_settings, _noObjectPoolMock.Object);

            _controller.Obtain(_key, out _outPoolObject, null);

            _noObjectPoolMock.Verify(x => x.TryObtain(_key, out _outPoolObject, null), Times.Once);
        }
        public void ReattempsIntervalIsSpecified_ControllerWaitsBeforeReattempt()
        {
            _controller = new PoolController<TestKey, TestResource>(_settings, _noObjectThreeTimesPoolMock.Object);

            _noObjectDirection.AttemptsNumber = 8;
            _noObjectDirection.OneIntervalBetweenAttemptsInSeconds = 1;

            var stopwatch = Stopwatch.StartNew();
            var getStatus = _controller.Obtain(_key, out _outPoolObject, _noObjectDirection);
            stopwatch.Stop();

            Assert.That(stopwatch.ElapsedMilliseconds, Is.InRange(2900, 4000));
            Assert.That(getStatus, Is.True);
            Assert.That(_outPoolObject.Value, Is.EqualTo(Mocks.Pool.ResourceValueAfterWaitings));
        }
        public void NumberOfAttemptsIsSpecified_PoolIsRecalledAndFinalResultIsGood()
        {
            _controller = new PoolController<TestKey, TestResource>(_settings, _noObjectThreeTimesPoolMock.Object);

            _noObjectDirection.AttemptsNumber = 5;
            var getStatus = _controller.Obtain(_key, out _outPoolObject, _noObjectDirection);

            Assert.That(getStatus, Is.True);
            Assert.That(_outPoolObject.Value, Is.EqualTo(Mocks.Pool.ResourceValueAfterWaitings));
            _noObjectThreeTimesPoolMock.Verify(x => x.TryObtain(_key, out _outPoolObject, null), Times.Exactly(4));
        }
        public void PoolThrew_ControllerStopsReattemptingAndThrowDetailedPoolException()
        {
            _controller = new PoolController<TestKey, TestResource>(_settings, _throwingPoolMock.Object);

            _noObjectDirection.AttemptsNumber = 3;
            var internalErrorException = Assert.Throws<PoolException<TestKey>>(() =>
                _controller.Obtain(_key, out _outPoolObject, _noObjectDirection));

            var expectedMessage = string.Format("Something failed during attempt #1 of obtaining object with key='{0}'. " +
                                                "Look at inner exception for details", _key);
            Assert.That(internalErrorException.Message, Is.EqualTo(expectedMessage));
            Assert.That(internalErrorException.Key, Is.EqualTo(_key));
            Assert.That(internalErrorException.InnerException, Is.TypeOf<ObjectCreationFailedException<TestKey, TestResource>>());
            _throwingPoolMock.Verify(x => x.TryObtain(_key, out _outPoolObject, null), Times.Once);
        }
        public void ReleasingWasNotPromisedAndPoolThrew_AttemptsNumberInExceptionIsEqualToOne()
        {
            _settings.CallingReleaseOperationWillHappen = false;
            _controller = new PoolController<TestKey, TestResource>(_settings, _throwingPoolMock.Object);

            _noObjectDirection.AttemptsNumber = 8;
            _noObjectDirection.OneIntervalBetweenAttemptsInSeconds = 0;
            var internalErrorException = Assert.Throws<PoolException<TestKey>>(() =>
                _controller.Obtain(_key, out _outPoolObject, _noObjectDirection));

            var expectedMessage = string.Format("Something failed during attempt #1 of obtaining object with key='{0}'. " +
                                                "Look at inner exception for details", _key);
            Assert.That(internalErrorException.Message, Is.EqualTo(expectedMessage));
        }
        public void ReleasingWasNotPromisedButWasCalled_ExceptionWithHintToPromiseReleasingIsThrown()
        {
            _settings.CallingReleaseOperationWillHappen = false;
            _controller = new PoolController<TestKey, TestResource>(_settings, _successPoolMock.Object);

            var resource = new TestResource(string.Empty);
            var hintException = Assert.Throws<InvalidPoolOperationException<TestKey, TestResource>>(
                () => _controller.Release(resource));

            var expectedMessage = "In order to release objects promise it by setting " +
                                  "PoolControllerSettings.CallingReleaseOperationWillHappen to " +
                                  "true. Currently it's false";
            Assert.That(hintException.Message, Is.EqualTo(expectedMessage));
            Assert.That(hintException.Key, Is.Null);
            Assert.That(hintException.Object, Is.EqualTo(resource));
        }