private IEnumerator ActivatePositiveItemsSequentially(List <int> ids)
    {
        //activate positive items sequentially
        foreach (var id in ids)
        {
            if (Contexts.sharedInstance.game.GetEntityWithId(id) == null)
            {
                continue;
            }

            yield return(DoWait.WaitSeconds(0.08f));

            var posItem = Contexts.sharedInstance.game.GetEntityWithId(id);
            if (posItem == null)
            {
                continue;
            }

            var cellItem = _contexts.game.GetEntityWithCellItemId(
                new Tuple <int, int>(posItem.gridPosition.value.x, posItem.gridPosition.value.y));
            if (cellItem != null && cellItem.isCanBeActivatedByInnerMatch)
            {
                cellItem.isWillBeDestroyed = true;
            }

            ActivatorHelper.ActivateItem(posItem, ActivationReason.Tnt);
        }
    }
Esempio n. 2
0
        /// <summary> Inits the plug-in with configured factory data. </summary>
        /// <param name="factoryData"> Retrieved factory settings. This parameter is null if no configuration at all was found. </param>
        public void Init(string factoryData)
        {
            string logTypeName;

            try
            {
                // load the factoryData XML
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(factoryData);

                // obtain the logger element and inspect the 'type' attribute
                XmlElement   logElement       = (XmlElement)xmlDoc.GetElementsByTagName("log")[0];
                XmlAttribute logTypeAttribute = logElement.Attributes[0];
                logTypeName = logTypeAttribute.Value;
            }
            catch (Exception e)
            {
                DiagnosticLog.Error(e, "An exception was thrown while trying to parse the given XML configuration [{0}]",
                                    factoryData);
                return;
            }

            ILog log = ActivatorHelper.Instantiate <ILog>(logTypeName, DiagnosticLog);

            if (log != null)
            {
                this.Log = log;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Creates a line item of a particular type for a shipment rate quote
        /// </summary>
        /// <typeparam name="T">The type of the line item to create</typeparam>
        /// <param name="shipmentRateQuote">The <see cref="ShipmentRateQuote"/> to be translated to a line item</param>
        /// <returns>A <see cref="LineItemBase"/> of type T</returns>
        public static T AsLineItemOf <T>(this IShipmentRateQuote shipmentRateQuote) where T : LineItemBase
        {
            var extendedData = new ExtendedDataCollection();

            extendedData.AddShipment(shipmentRateQuote.Shipment);

            var ctrValues = new object[]
            {
                EnumTypeFieldConverter.LineItemType.Shipping.TypeKey,
                shipmentRateQuote.ShipmentLineItemName(),
                shipmentRateQuote.ShipMethod.ServiceCode,     // TODO this may not be unique (SKU) once multiple shipments are exposed
                1,
                shipmentRateQuote.Rate,
                extendedData
            };

            var attempt = ActivatorHelper.CreateInstance <LineItemBase>(typeof(T), ctrValues);

            if (attempt.Success)
            {
                return(attempt.Result as T);
            }

            LogHelper.Error <ILineItem>("Failed instiating a line item from shipmentRateQuote", attempt.Exception);

            throw attempt.Exception;
        }
Esempio n. 4
0
        /// <summary>
        /// Constructs the task chain
        /// </summary>
        protected virtual void ResolveChain(string chainConfigurationAlias)
        {
            // Types from the merchello.config file
            var typeList = ChainTaskResolver.GetTypesForChain(chainConfigurationAlias).ToArray();

            if (!typeList.Any())
            {
                return;
            }

            // instantiate each task in the chain
            TaskHandlers.AddRange(
                typeList.Select(
                    typeName => new AttemptChainTaskHandler <T>(
                        ActivatorHelper.CreateInstance <AttemptChainTaskBase <T> >(
                            typeName,
                            ConstructorArgumentValues.ToArray()).Result
                        )));

            // register the next task for each link (these are linear chains)
            foreach (var taskHandler in TaskHandlers.Where(task => TaskHandlers.IndexOf(task) != TaskHandlers.IndexOf(TaskHandlers.Last())))
            {
                taskHandler.RegisterNext(TaskHandlers[TaskHandlers.IndexOf(taskHandler) + 1]);
            }
        }
Esempio n. 5
0
        public static T DataLoader <T>(
            this IResolverContext context,
            string key)
            where T : class, IDataLoader
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException(
                          TypeResources.DataLoaderRegistry_KeyNullOrEmpty,
                          nameof(key));
            }

            if (TryGetDataLoader(context, key,
                                 out T dataLoader,
                                 out IDataLoaderRegistry registry))
            {
                return(dataLoader);
            }

            return(GetOrCreate <T>(key, registry, r => r.Register(
                                       key, ActivatorHelper.CreateInstanceFactory <T>())));
        }
        /// <summary>
        /// Builds the <see cref="IOfferProcessor"/>
        /// </summary>
        /// <param name="offer">
        /// The offer.
        /// </param>
        /// <returns>
        /// The <see cref="IOfferProcessor"/>.
        /// </returns>
        public IOfferProcessor Build(OfferBase offer)
        {
            var constraints = offer.Constraints;

            var constraintsType = offer.Reward.TypeGrouping;
            var rewardType      = offer.Reward.RewardType;

            var chainType =
                _instanceTypes.FirstOrDefault(
                    x => x.GetCustomAttribute <OfferConstraintChainForAttribute>(false).ConstraintType == constraintsType &&
                    x.GetCustomAttribute <OfferConstraintChainForAttribute>(false).RewardType == rewardType);

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


            var ctrArgs = new object[] { };
            var attempt = ActivatorHelper.CreateInstance <IOfferProcessor>(chainType, ctrArgs);

            if (!attempt.Success)
            {
                MultiLogHelper.Error <OfferProcessorFactory>("Failed to create instance of " + chainType.Name, attempt.Exception);
                return(null);
            }

            // initialize the processor
            attempt.Result.Initialize(constraints, offer.Reward);

            return(attempt.Result);
        }
 /// <summary>
 /// Builds the type cache.
 /// </summary>
 /// <param name="values">
 /// The values.
 /// </param>
 private void BuildCache(IEnumerable <Type> values)
 {
     foreach (var attempt in values.Select(type => ActivatorHelper.CreateInstance <DetachedValueCorrectionBase>(type, new object[] { })).Where(attempt => attempt.Success))
     {
         this.AddOrUpdateCache(attempt.Result);
     }
 }
    private void ActivateColorCubes(List <int> ids)
    {
        foreach (var id in ids)
        {
            var item = _contexts.game.GetEntityWithId(id);
            if (item == null)
            {
                continue;
            }

            if (item.hasRemoverId)
            {
                continue;
            }

            var cellItem = _contexts.game.GetEntityWithCellItemId(
                new Tuple <int, int>(item.gridPosition.value.x, item.gridPosition.value.y));
            if (cellItem != null && cellItem.isCanBeActivatedByInnerMatch)
            {
                cellItem.isWillBeDestroyed = true;
            }

            ActivatorHelper.ActivateItem(item, ActivationReason.Puzzle);
            var removerId = IdHelper.GetNewRemoverId();
            item.AddRemoverId(removerId);
        }
    }
Esempio n. 9
0
    private void ActivateColorCube(GameEntity cube, int removerId)
    {
        var color   = cube.color.Value;
        var cubePos = cube.gridPosition.value;

        var cellItem = _contexts.game.GetEntityWithCellItemId(new Tuple <int, int>(cubePos.x, cubePos.y));

        if (cellItem != null && cellItem.isCanBeActivatedByInnerMatch)
        {
            cellItem.isWillBeDestroyed = true;
        }

        int x = cubePos.x;
        int y = cubePos.y;

        var positions = new[]
        {
            new Vector2Int(x - 1, y),
            new Vector2Int(x + 1, y),
            new Vector2Int(x, y - 1),
            new Vector2Int(x, y + 1),
        };

        for (int i = 0; i < positions.Length; i++)
        {
            var pos = positions[i];
            if (!InBounds(pos))
            {
                continue;
            }

            ActivatorHelper.TryActivateItemWithNear(_contexts, pos, removerId, color);
        }
    }
Esempio n. 10
0
        static void Main(string[] args)
        {
            try
            {
                Portfolio original = Portfolio.Open(PortfolioId.GenerateId(), AccountType.Cheque, Money.Amount(100));
                original.CreditAccount(AccountType.Cheque, Money.Amount(50));
                IEnumerable <DomainEvent> changes = ((IAggregate)original).GetUncommittedEvents();

                Portfolio copy = ActivatorHelper.CreateInstanceUsingNonPublicConstructor <Portfolio>(original.Identity);
                ((IAggregate)copy).LoadFromHistory(changes);
                original.CreditAccount(AccountType.Cheque, Money.Amount(5));

                var copyBalance     = copy.GetAccountBalance(AccountType.Cheque);
                var originalBalance = original.GetAccountBalance(AccountType.Cheque);

                if (originalBalance == copyBalance)
                {
                    throw new Exception("Balances should not match");
                }

                if (original != copy)
                {
                    throw new Exception("Aggregates should match by identity");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }

            Console.ReadKey();
        }
Esempio n. 11
0
        /// <summary>
        /// Converts a line item of one type to a line item of another type
        /// </summary>
        /// <typeparam name="T">The specific type of <see cref="ILineItem"/></typeparam>
        /// <param name="lineItem">The line item</param>
        /// <returns>A <see cref="LineItemBase"/> of type T</returns>
        public static T AsLineItemOf <T>(this ILineItem lineItem) where T : class, ILineItem
        {
            var ctrValues = new object[]
            {
                lineItem.LineItemTfKey,
                lineItem.Name,
                lineItem.Sku,
                lineItem.Quantity,
                lineItem.Price,
                lineItem.ExtendedData
            };


            var attempt = ActivatorHelper.CreateInstance <LineItemBase>(typeof(T), ctrValues);

            if (!attempt.Success)
            {
                LogHelper.Error <ILineItem>("Failed to convertion ILineItem", attempt.Exception);
                throw attempt.Exception;
            }

            attempt.Result.Exported = lineItem.Exported;

            return(attempt.Result as T);
        }
Esempio n. 12
0
        public static void Run()
        {
            CodeTimer.Initialize();
            var type = typeof(MessageTest <CmdTest>);
            var ctor = type.GetConstructors()[2];
            ObjectActivator <object> createdActivator = ActivatorHelper.GetActivator <object>(ctor);
            var    input  = new CmdTest();
            var    header = new MessageHeaderTest();
            object tmpObj = null;
            var    count  = 1000000;

            CodeTimer.Time("new instance", count, () =>
            {
                tmpObj = new MessageTest <CmdTest>(input, header);
            });

            CodeTimer.Time("exp tree", count, () =>
            {
                tmpObj = createdActivator(input, header);
            });

            CodeTimer.Time("Activator.CreateInstance", count, () =>
            {
                tmpObj = Activator.CreateInstance(type, input, header);
            });

            CodeTimer.Time("exp tree2", count, () =>
            {
                tmpObj = ActivatorHelper.CreateInstance(type, input, header);
            });
        }
Esempio n. 13
0
    protected override void Execute(List <GameEntity> entities)
    {
        foreach (var tntTnt in entities)
        {
            tntTnt.isSpawnAnimationStarted = false;
            tntTnt.isSpawnAnimationEnded   = false;

            var pos       = tntTnt.gridPosition.value;
            var radius    = tntTnt.tntTnt.Radius;
            var removerId = IdHelper.GetNewRemoverId();

            for (int x = pos.x - radius; x <= pos.x + radius; x++)
            {
                for (int y = pos.y - radius; y <= pos.y + radius; y++)
                {
                    CellHelper.UnBlockFallAt(new Vector2Int(x, y));

                    ActivatorHelper.TryActivateItemWithPositive(new Vector2Int(x, y), removerId,
                                                                ActivationReason.Tnt);
                }
            }

            tntTnt.isWillBeDestroyed = true;

            WaitHelper.Reduce(WaitType.Input, WaitType.Turn, WaitType.CriticalAnimation);
        }
    }
Esempio n. 14
0
        /// <summary>
        /// Creates an instance of an Umbraco Surface controller from scratch
        /// when no existing ControllerContext is present
        /// </summary>
        /// <param name="routeData">
        /// The route Data.
        /// </param>
        /// <typeparam name="T">
        /// Type of the controller to create
        /// </typeparam>
        /// <returns>
        /// A surface controller of type T
        /// </returns>
        public static T CreateSurfaceController <T>(RouteData routeData = null)
            where T : SurfaceController
        {
            // Create an MVC Controller Context
            var umbracoContext = GetUmbracoContext();

            var umbracoHelper = new UmbracoHelper(umbracoContext);

            var attempt = ActivatorHelper.CreateInstance <T>(typeof(T), new object[] { umbracoContext, umbracoHelper });

            if (!attempt.Success)
            {
                var data = MultiLogger.GetBaseLoggingData();
                data.AddCategory("SurfaceController");
                MultiLogHelper.Error <SurfaceControllerActivationHelper>("Failed to create render controller", attempt.Exception, data);
                throw attempt.Exception;
            }

            var controller = attempt.Result;

            if (routeData == null)
            {
                routeData = new RouteData();
            }

            if (!routeData.Values.ContainsKey("controller") && !routeData.Values.ContainsKey("Controller"))
            {
                routeData.Values.Add(
                    "controller",
                    controller.GetType().Name.ToLower().Replace("controller", string.Empty));
            }

            controller.ControllerContext = new ControllerContext(umbracoContext.HttpContext, routeData, controller);
            return(controller);
        }
        static void Main(string[] args)
        {
            var original = Portfolio.Open(PortfolioId.GenerateId(), AccountType.Cheque, Money.Amount(100));

            original.CreditAccount(AccountType.Cheque, Money.Amount(50));
            var memento = ((IAggregate)original).GetSnapshot();

            var copy = ActivatorHelper.CreateInstanceUsingNonPublicConstructor <Portfolio>(memento.Identity);

            ((IAggregate)copy).RestoreSnapshot(memento);
            copy.CreditAccount(AccountType.Cheque, Money.Amount(5));

            var copyBalance     = copy.GetAccountBalance(AccountType.Cheque);
            var originalBalance = original.GetAccountBalance(AccountType.Cheque);

            if (originalBalance == copyBalance)
            {
                throw new Exception("Balances should not match");
            }

            if (original != copy)
            {
                throw new Exception("Aggregates should match by identity");
            }
        }
Esempio n. 16
0
        private ITisServiceCreator InstanciateCreator(
            ITisServiceInfo oServiceInfo)
        {
            // Get creator type
            string sCreatorType =
                oServiceInfo.ServiceCreatorType;

            // Create Creator instance
            object oObjCreator = ActivatorHelper.CreateInstance(
                sCreatorType,
                EmptyArrays.ObjectArray);

            ITisServiceCreator oCreator = null;

            try
            {
                // Try to cast
                oCreator = (ITisServiceCreator)oObjCreator;
            }
            catch (InvalidCastException oExc)
            {
                throw new TisException(
                          oExc, // Inner
                          "Object [{0}] doesn't implements ITisServiceCreator",
                          oObjCreator);
            }

            return(oCreator);
        }
        public static ILogHelperLoggingBuilder WithProvider <TLogProvider>(this ILogHelperLoggingBuilder loggingBuilder, params object[] ctorParams) where TLogProvider : ILogHelperProvider
        {
            Guard.NotNull(loggingBuilder, nameof(loggingBuilder));

            loggingBuilder.AddProvider(ActivatorHelper.CreateInstance <TLogProvider>(ctorParams));
            return(loggingBuilder);
        }
Esempio n. 18
0
        /// <summary>
        /// The create instance.
        /// </summary>
        /// <param name="providerSettings">
        /// The provider settings.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt"/>.
        /// </returns>
        private Attempt <GatewayProviderBase> CreateInstance(IGatewayProviderSettings providerSettings)
        {
            var providerType = InstanceTypes.FirstOrDefault(x => x.GetCustomAttribute <GatewayProviderActivationAttribute>(false).Key == providerSettings.Key);

            return(providerSettings == null ?
                   Attempt <GatewayProviderBase> .Fail(new Exception(string.Format("Failed to find type for provider {0}", providerSettings.Name))) :
                   ActivatorHelper.CreateInstance <GatewayProviderBase>(providerType, new object[] { _gatewayProviderService, providerSettings, _runtimeCache }));
        }
Esempio n. 19
0
        private bool EvaluateConstructorExists()
        {
            bool constructorExists = false;

            constructorExists = ActivatorHelper.ConstructorExists(_assemblyName, _completeTypeName, _parameterTypes);

            return(constructorExists);
        }
Esempio n. 20
0
 public void CreateInstance_NullOrEmptyNif_InstanceCreated(string nullOrEmptyNif)
 {
     Assert.DoesNotThrows(() =>
     {
         var nif = ActivatorHelper.CreateInstance <Nif>(nullOrEmptyNif);
         Assert.NotNull(nif);
     });
 }
Esempio n. 21
0
        static void Main(string[] args)
        {
            var n    = 3000000;
            var stop = Stopwatch.StartNew();

            for (int i = 0; i < n; i++)
            {
                var instance = new Program2(i);
            }

            Console.WriteLine(stop.ElapsedMilliseconds);

            stop = Stopwatch.StartNew();

            for (int i = 0; i < n; i++)
            {
                var instance = Activator.CreateInstance(typeof(Program2), i);
            }

            Console.WriteLine(stop.ElapsedMilliseconds);

            stop = Stopwatch.StartNew();
            for (int i = 0; i < n; i++)
            {
                var ctor     = ActivatorHelper.GetActivator <Program2>();
                var instance = ctor(i);
            }

            Console.WriteLine(stop.ElapsedMilliseconds);

            stop = Stopwatch.StartNew();
            for (int i = 0; i < n; i++)
            {
                var ctor     = LazyActivatorHelper.Instance.GetActivator <Program2>();
                var instance = ctor(i);
            }

            Console.WriteLine(stop.ElapsedMilliseconds);


            //var key = CacheHelper.GetKey(MethodBase.GetCurrentMethod(), 1, 2, bool.TrueString, false);
            //var ms = (DateTime.Now.Millisecond);
            //Console.WriteLine(ms);
            //CacheFactory.Current.Add(key, ms);

            //Console.WriteLine("aaa");

            //Console.WriteLine(CacheFactory.Current.Get<int>(key));


            //Console.WriteLine(typeof(Program).FullName);
            ////Log.ThreadVariablesContext.Set("url", "http://abc.com");
            //Log.Debug("b");
            //Log.Warn("Asdfasfasf");
            //Log.Error("Asdfasfasf");
            //Log.Info("Asdfasfasf");
            //Log.Fatal("Asdfasfasf");
        }
Esempio n. 22
0
 public void CreateInstance_NotEmptyNif_InstanceCreated(string notEmptyNif)
 {
     Assert.DoesNotThrows(() =>
     {
         var nif = ActivatorHelper.CreateInstance <Nif>(notEmptyNif);
         Assert.NotNull(nif);
         Assert.Equal(notEmptyNif, nif.Value);
     });
 }
Esempio n. 23
0
        /// <summary>
        /// Gets an instantiated offer component by it's definition.
        /// </summary>
        /// <param name="definition">
        /// The definition.
        /// </param>
        /// <returns>
        /// The <see cref="OfferComponentBase"/>.
        /// </returns>
        public OfferComponentBase GetOfferComponent(OfferComponentDefinition definition)
        {
            var type    = this.GetTypeByComponentKey(definition.ComponentKey);
            var ctlArgs = new object[] { definition };

            var attempt = ActivatorHelper.CreateInstance <OfferComponentBase>(type, ctlArgs);

            return(attempt.Success ? attempt.Result : null);
        }
        public static bool Register <T>(
            this IDataLoaderRegistry registry)
            where T : class, IDataLoader
        {
            Func <IServiceProvider, T> createInstance =
                ActivatorHelper.CreateInstanceFactory <T>();

            return(registry.Register(typeof(T).FullName, createInstance));
        }
Esempio n. 25
0
        public static bool Register <T>(
            this IDataLoaderRegistry registry,
            string key)
            where T : class, IDataLoader
        {
            Func <IServiceProvider, T> createInstance =
                ActivatorHelper.CompileFactory <T>();

            return(registry.Register(key, createInstance));
        }
        /// <summary>
        /// Finds best constructor, least parameter
        /// </summary>
        /// <param name="type">type</param>
        /// <param name="parameterTypes"></param>
        /// <returns>Matching constructor or default one</returns>
        public static ConstructorInfo?GetConstructor(this Type type, params Type[]?parameterTypes)
        {
            if (parameterTypes == null || parameterTypes.Length == 0)
            {
                return(GetEmptyConstructor(type));
            }

            ActivatorHelper.FindApplicableConstructor(type, parameterTypes, out var ctor, out _);
            return(ctor);
        }
        private Uri UmbracoAssembleUrl(DomainAndUri domainUri, string path, Uri current, UrlProviderMode mode)
        {
            // This method is private in umbraco, but we want to use their!
            DefaultUrlProvider provider = ActivatorHelper.CreateInstance <DefaultUrlProvider>();

            return(ActivatorHelper.GetPrivateMethodReturnValueOfInstance <Uri>(
                       instance: provider,
                       methodName: "AssembleUrl",
                       methodArguments: new object[] { domainUri, path, current, mode }));
        }
Esempio n. 28
0
        /// <summary>
        /// Creates a single instance of TResolved
        /// </summary>
        /// <param name="type">
        /// The type.
        /// </param>
        /// <param name="ctrArgs">
        /// The constructor args.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt"/>.
        /// </returns>
        protected virtual Attempt <TResolved> CreateInstance(Type type, object[] ctrArgs)
        {
            var attempt = ActivatorHelper.CreateInstance <TResolved>(type, ctrArgs.ToArray());

            if (!attempt.Success)
            {
                LogHelper.Debug <TResolver>(string.Format("Failed to resolve type {0}", type.Name));
            }

            return(attempt);
        }
    private void ProcessGodTouch(Vector2Int touchPos, int removerId)
    {
        var item = _contexts.game.GetItemWithPosition(touchPos);

        if (item == null || item.hasFalling)
        {
            return;
        }

        ActivatorHelper.TryActivateItemWithPositive(touchPos, removerId, ActivationReason.God);
    }
Esempio n. 30
0
        //
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion


        /// <summary>
        ///A test for Instantiate
        ///</summary>
        public void InstantiateTestHelper <T>()
        {
            string typeName = string.Empty; // TODO: Initialize to an appropriate value
            ILog   log      = null;         // TODO: Initialize to an appropriate value
            T      expected = default(T);   // TODO: Initialize to an appropriate value
            T      actual;

            actual = ActivatorHelper.Instantiate <T>(typeName, log);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }