Exemple #1
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);
            });
        }
Exemple #2
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;
        }
Exemple #3
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);
        }
 /// <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);
     }
 }
Exemple #6
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);
        }
        /// <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]);
            }
        }
Exemple #8
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);
        }
        /// <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);
        }
Exemple #10
0
 public void CreateInstance_NullOrEmptyNif_InstanceCreated(string nullOrEmptyNif)
 {
     Assert.DoesNotThrows(() =>
     {
         var nif = ActivatorHelper.CreateInstance <Nif>(nullOrEmptyNif);
         Assert.NotNull(nif);
     });
 }
Exemple #11
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 }));
        }
Exemple #12
0
 public void CreateInstance_NotEmptyNif_InstanceCreated(string notEmptyNif)
 {
     Assert.DoesNotThrows(() =>
     {
         var nif = ActivatorHelper.CreateInstance <Nif>(notEmptyNif);
         Assert.NotNull(nif);
         Assert.Equal(notEmptyNif, nif.Value);
     });
 }
Exemple #13
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);
        }
        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 }));
        }
Exemple #15
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);
        }
Exemple #16
0
 public static IInterceptionConfiguration With <TInterceptor>(this IInterceptionConfiguration interceptionConfiguration, params object?[] parameters) where TInterceptor : IInterceptor
 {
     if (Guard.NotNull(parameters, nameof(parameters)).Length == 0)
     {
         interceptionConfiguration.With(NewFuncHelper <TInterceptor> .Instance());
     }
     else
     {
         interceptionConfiguration.With(ActivatorHelper.CreateInstance <TInterceptor>(parameters));
     }
     return(interceptionConfiguration);
 }
Exemple #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public static BaseTaskDataEditor GetDataEditor(Task task)
        {
            var type = TaskFinder.FindType(task);
            var attr = type.GetCustomAttribute <TaskDataEditorAttribute>();

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

            return(ActivatorHelper.CreateInstance(attr.ViewType) as BaseTaskDataEditor);
        }
Exemple #18
0
        /// <summary>
        /// Creates an instance of a service with arguments
        /// </summary>
        /// <param name="constructorArgumentValues">
        /// The constructor argument values.
        /// </param>
        /// <typeparam name="TService">
        /// The type of the service to resolve
        /// </typeparam>
        /// <returns>
        /// The <see cref="TService"/>.
        /// </returns>
        /// <exception cref="Exception">
        /// Throws an exception if service cannot be resolved
        /// </exception>
        public TService Instance <TService>(object[] constructorArgumentValues)
            where TService : class, IEntityProxyQuery
        {
            //// We may need to manage separate instances of these services if the constructor arguments are different
            //// so that we can assert the values returned are what we expect.
            var suffix   = string.Join(".", constructorArgumentValues.Select(x => x.ToString()));
            var cacheKey = this.GetCacheKey(typeof(TService), suffix);

            return((TService)this._cache.GetCacheItem(
                       cacheKey,
                       () =>
                       ActivatorHelper.CreateInstance <TService>(constructorArgumentValues)));
        }
Exemple #19
0
        /// <summary>
        /// Resolves a chain of tasks, where the tasks do not require have parameters in the constructor
        /// </summary>
        /// <typeparam name="T">The type of the task</typeparam>
        /// <param name="chainAlias">The 'configuration' alias of the chain.  This is the merchello.config value</param>
        /// <returns>A collection of instantiated of AttemptChainTask</returns>
        internal static IEnumerable <T> ResolveAttemptChainByAlias <T>(string chainAlias) where T : class, IAttemptChainTask <T>, new()
        {
            var types    = new List <T>();
            var typeList = GetTypesForChain(chainAlias).ToArray();

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

            types.AddRange(typeList.Select(type => ActivatorHelper.CreateInstance <T>()));

            return(types);
        }
        /// <summary>
        /// Creates the object instances for the types contained in the types collection.
        /// </summary>
        /// <returns>A list of objects of type <typeparamref name="TResolved"/>.</returns>
        protected virtual IEnumerable <TResolved> CreateInstances(object[] ctrArgs)
        {
            var instances = new List <TResolved>();

            foreach (var et in InstanceTypes)
            {
                var attempt = ActivatorHelper.CreateInstance <TResolved>(et, ctrArgs.ToArray());
                if (attempt.Success)
                {
                    instances.Add(attempt.Result);
                }
            }

            return(instances);
        }
 /// <summary>
 /// Builds the provider cache.
 /// </summary>
 private void BuildOfferProviderCache()
 {
     foreach (var type in InstanceTypes)
     {
         var attempt = ActivatorHelper.CreateInstance <IOfferProvider>(type, new object[] { _offerSettingsService });
         if (attempt.Success)
         {
             AddOrUpdateCache(attempt.Result);
         }
         else
         {
             LogHelper.Error <OfferProviderResolver>("Failed to instantiate type: " + type.Name, attempt.Exception);
         }
     }
 }
Exemple #22
0
        internal static IEnumerable <IShipment> PackageBasket(this IBasket basket, IMerchelloContext merchelloContext, IAddress destination)
        {
            var defaultStrategy = MerchelloConfiguration.Current.GetStrategyElement(Constants.StrategyTypeAlias.DefaultPackaging).Type;

            var ctoArgValues = new object[] { merchelloContext, basket.Items, destination, basket.VersionKey };
            var strategy     = ActivatorHelper.CreateInstance <PackagingStrategyBase>(defaultStrategy, ctoArgValues);

            if (!strategy.Success)
            {
                LogHelper.Error <PackagingStrategyBase>("PackageBasket failed to instantiate the defaultStrategy.", strategy.Exception);
                throw strategy.Exception;
            }

            return(basket.PackageBasket(merchelloContext, destination, strategy.Result));
        }
Exemple #23
0
        /// <summary>
        /// Quotes a single GatewayShipMethod for a shipment rate
        /// </summary>
        /// <param name="shipment">The <see cref="IShipment"/> used to generate the rate quote</param>
        /// <param name="shippingGatewayMethod">The <see cref="IShippingGatewayMethod"/> used to generate the rate quote</param>
        /// <returns>The <see cref="IShipmentRateQuote"/></returns>
        public virtual IShipmentRateQuote QuoteShipMethodForShipment(IShipment shipment, IShippingGatewayMethod shippingGatewayMethod)
        {
            var ctrValues = new object[] { shipment, new[] { shippingGatewayMethod }, RuntimeCache };

            var typeName = MerchelloConfiguration.Current.GetStrategyElement(Constants.StrategyTypeAlias.DefaultShipmentRateQuote).Type;

            var attempt = ActivatorHelper.CreateInstance <ShipmentRateQuoteStrategyBase>(typeName, ctrValues);

            if (!attempt.Success)
            {
                LogHelper.Error <ShippingGatewayProviderBase>("Failed to instantiate strategy " + typeName, attempt.Exception);
                throw attempt.Exception;
            }

            return(QuoteShippingGatewayMethodsForShipment(attempt.Result).FirstOrDefault());
        }
Exemple #24
0
        /// <summary>
        /// The get offer component.
        /// </summary>
        /// <param name="definition">
        /// The definition.
        /// </param>
        /// <typeparam name="T">
        /// The type of component to be returned
        /// </typeparam>
        /// <returns>
        /// The <see cref="T"/>.
        /// </returns>
        /// <remarks>
        /// TODO decide if this should be removed - probably be more useful if it did not require a definition
        /// and simply returned an new instantion of the type T
        /// </remarks>
        internal T GetOfferComponent <T>(OfferComponentDefinition definition) where T : OfferComponentBase
        {
            var typeOfT = typeof(T);
            var type    = _instanceTypes.FirstOrDefault(x => x.IsAssignableFrom(typeOfT));

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

            var ctlArgs = new object[] { definition };

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

            return(attempt.Success ? attempt.Result as T : null);
        }
Exemple #25
0
        public override object CreateService()
        {
            ITisServiceInfo serviceInfo = Context.ServicesHost.CheckedGetServiceInfo(
                Context.ApplicationName,
                Context.ServiceKey.ServiceName);

            string serviceImplType = serviceInfo.ServiceImplType;

            object service = ActivatorHelper.CreateInstance(
                serviceImplType,
                GetConstructorParams());

            OnPostServiceCreate(service);

            return(service);
        }
Exemple #26
0
        public override ITaxCalculationResult CalculateTaxForInvoice(IInvoice invoice, IAddress taxAddress)
        {
            var ctrValues = new object[] { invoice, taxAddress, TaxMethod };

            var typeName = MerchelloConfiguration.Current.GetStrategyElement(Constants.StrategyTypeAlias.DefaultInvoiceTaxRateQuote).Type;

            var attempt = ActivatorHelper.CreateInstance <TaxCalculationStrategyBase>(typeName, ctrValues);

            if (!attempt.Success)
            {
                LogHelper.Error <FixedRateTaxationGatewayProvider>("Failed to instantiate the tax calculation strategy '" + typeName + "'", attempt.Exception);
                throw attempt.Exception;
            }

            return(CalculateTaxForInvoice(attempt.Result));
        }
Exemple #27
0
        /// <summary>
        ///
        /// </summary>
        public bool Execute()
        {
            if (_taskType == null)
            {
                return(false);
            }

            var task = (ITask)ActivatorHelper.CreateInstance(_taskType);

            if (task == null)
            {
                return(false);
            }

            TaskArgumentInitializer.SetArguments(task, Task.GetTaskData());
            return(task.Execute());
        }
Exemple #28
0
        public override void Execute()
        {
            bool typeExists        = false;
            bool constructorExists = false;

            if (_parameterTypes == null &&
                _parameters != null)
            {
                //try to get parameter types from values
                //this is not working with null values (use SetParameterTypes when you have errors)
                _parameterTypes = ActivatorHelper.GetParameterTypes(_parameters);
            }

            typeExists = ActivatorHelper.TypeExists(_assemblyName, _completeTypeName);

            if (!typeExists)
            {
                MessageBox.ShowError("Funktion nicht gefunden",
                                     string.Format("Die Funktion [{0}, {1}] konnte nicht gefunden werden.", _assemblyName,
                                                   _completeTypeName), "Funktion ungültig");
            }

            if (typeExists && HasParameters)
            {
                constructorExists = EvaluateConstructorExists();

                if (!constructorExists)
                {
                    MessageBox.ShowError("Konstruktor nicht gefunden",
                                         string.Format("Der Konstruktor für den Typ [{0}, {1}] konnte nicht gefunden werden.",
                                                       _assemblyName, _completeTypeName), "Konstruktor ungültig");
                }
            }

            if (typeExists)
            {
                _applicationCommandInstance = ActivatorHelper.CreateInstance(_assemblyName, _completeTypeName,
                                                                             _parameters, _parameterTypes);

                if (_applicationCommandInstance != null && _applicationCommandInstance is IApplicationCommand)
                {
                    ((IApplicationCommand)_applicationCommandInstance).Execute();
                }
            }
        }
Exemple #29
0
        /// <summary>
        /// Converts an anonymous basket to a customer basket.
        /// </summary>
        /// <param name="anonymousBasket">
        /// The anonymous basket.
        /// </param>
        /// <param name="customerBasket">
        /// The customer basket.
        /// </param>
        private static void ConvertBasket(IBasket anonymousBasket, IBasket customerBasket)
        {
            var type = Type.GetType(
                MerchelloConfiguration.Current.GetStrategyElement(
                    "DefaultAnonymousBasketConversionStrategy").Type);

            var attempt = ActivatorHelper.CreateInstance <BasketConversionBase>(
                type,
                new object[] { anonymousBasket, customerBasket });

            if (!attempt.Success)
            {
                MultiLogHelper.Error <CustomerContext>("Failed to convert anonymous basket to customer basket", attempt.Exception);
                return;
            }

            attempt.Result.Merge();
        }
Exemple #30
0
        /// <summary>
        /// Returns a collection of all available <see cref="IShipmentRateQuote"/> for a given shipment
        /// </summary>
        /// <param name="shipment">The <see cref="IShipmentRateQuote"/></param>
        /// <param name="tryGetCached">
        /// If set true the strategy will try to get a quote from cache
        /// </param>
        /// <returns>A collection of <see cref="IShipmentRateQuote"/></returns>
        public virtual IEnumerable <IShipmentRateQuote> QuoteShippingGatewayMethodsForShipment(IShipment shipment, bool tryGetCached = true)
        {
            var gatewayShipMethods = GetShippingGatewayMethodsForShipment(shipment);

            var ctrValues = new object[] { shipment, gatewayShipMethods.ToArray(), RuntimeCache };

            var typeName = MerchelloConfiguration.Current.GetStrategyElement(Constants.StrategyTypeAlias.DefaultShipmentRateQuote).Type;

            var attempt = ActivatorHelper.CreateInstance <ShipmentRateQuoteStrategyBase>(typeName, ctrValues);

            if (!attempt.Success)
            {
                MultiLogHelper.Error <ShippingGatewayProviderBase>("Failed to instantiate strategy " + typeName, attempt.Exception);
                throw attempt.Exception;
            }

            return(QuoteShippingGatewayMethodsForShipment(attempt.Result, tryGetCached));
        }