예제 #1
0
        protected override void Initialize(bool initData)
        {
            base.Initialize(initData);

            if (initData)
            {
                // available row selection types
                var types = ReflectionService.GetNonAbstractSubclassesOf(typeof(IRowSelection));
                _rowSelectionSimpleTypes     = new SelectableListNodeList();
                _rowSelectionCollectionTypes = new SelectableListNodeList();
                foreach (var type in types)
                {
                    if (typeof(IRowSelectionCollection).IsAssignableFrom(type))
                    {
                        _rowSelectionCollectionTypes.Add(new SelectableListNode(type.Name, type, false));
                    }
                    else
                    {
                        _rowSelectionSimpleTypes.Add(new SelectableListNode(type.Name, type, false));
                    }
                }

                // RS entries
                _rsEntryList = new List <RSEntry>();
                ConvertRowSelectionToListOfRSEntries(_doc, _rsEntryList, 0);
                AmendRSEntryListWithDetailControllers(_rsEntryList);
            }

            if (null != _view)
            {
                _view.InitRowSelections(_rsEntryList, _rowSelectionSimpleTypes, _rowSelectionCollectionTypes);
            }
        }
예제 #2
0
 public RightControllerService(ICommonDataService dataService, CoreDbContext context,
                               ReflectionService reflectionService)
 {
     DataService        = dataService;
     _context           = context;
     _reflectionService = reflectionService;
 }
        public async Task TaskWithValueInterfaceReturnTest(ServiceImplementationGenerator implementationGenerator, IClientSerializer clientSerializer, Fixture fixture)
        {
            var request = new ImplementationRequest
            {
                InterfaceType         = typeof(ITestInterface),
                SingleParameterToBody = true,
                DefaultSerializer     = clientSerializer
            };

            var type = implementationGenerator.GenerateImplementationForInterface(request);

            var testInterface = (ITestInterface)fixture.Locate(type);

            var a = 5;
            var b = 5;

            fixture.Locate <IRpcExecutionService>().ExecuteMethodWithValue <int>(Arg.Any <RpcExecuteInformation>(),
                                                                                 Arg.Any <string>(), Arg.Any <object>(), Arg.Any <CancellationToken?>()).Returns(callInfo =>
            {
                var value = callInfo.ArgAt <object>(2);

                var properties = ReflectionService.GetPropertiesFromObject(value);

                var aValue = (int)properties[nameof(a)];
                var bValue = (int)properties[nameof(b)];

                return(aValue + bValue);
            });


            var value = await testInterface.Add(5, 5);


            Assert.Equal(a + b, value);
        }
 public SQLitePlatformGeneric()
 {
     SQLiteApi         = new SQLiteApiGeneric();
     StopwatchFactory  = new StopwatchFactory();
     ReflectionService = new ReflectionService();
     VolatileService   = new VolatileService();
 }
예제 #5
0
        private TDestination MapSingleObject <TDestination>(object src)
        {
            var Constructor = ReflectionService.Make().GetConstructorForType <TDestination>(typeof(TDestination));

            if (Constructor.IsNull)
            {
                return(default);
        public void OnViewReady()
        {
            var reflectionService = new ReflectionService();

            var moduleTypes = reflectionService.GetTypes<IManagementModule>();

            foreach (var type in moduleTypes)
            {
                if (!type.HasDefaultConstructor())
                {
                    Log.Warning(string.Format(ManagementResources.ManagementModuleInitializerHasNoDefaultConstructor, type.FullName));
                }
                else
                {
                    var module = ((IManagementModule) Activator.CreateInstance(type));

                    module.Configure(managementConfiguration);

                    foreach (ManagementModulePresenter presenter in module.Presenters)
                    {
                        presenter.TaskQueue = taskQueue;
                        presenter.ManagementConfiguration = managementConfiguration;

                        view.AddManagementModulePresenter(presenter);

                        presenters.Add(presenter);
                    }
                }
            }
        }
 public SQLitePlatformWinRT(string directoryPath)
 {
     SQLiteApi         = new SQLiteApiWinRT(directoryPath);
     VolatileService   = new VolatileService();
     StopwatchFactory  = new StopwatchFactory();
     ReflectionService = new ReflectionService();
 }
예제 #8
0
        protected override void Initialize(bool initData)
        {
            base.Initialize(initData);

            if (initData)
            {
                // predefined styles
                string[] names = G3DPlotStyleCollectionTemplates.GetAvailableNames();
                _predefinedStyleSetsAvailable = new SelectableListNodeList();
                for (int i = 0; i < names.Length; ++i)
                {
                    _predefinedStyleSetsAvailable.Add(new SelectableListNode(names[i], i, false));
                }

                // single styles
                _singleStylesAvailable = new SelectableListNodeList();
                Type[] avtypes = ReflectionService.GetNonAbstractSubclassesOf(typeof(IG3DPlotStyle));
                for (int i = 0; i < avtypes.Length; i++)
                {
                    if (avtypes[i] != typeof(G3DPlotStyleCollection))
                    {
                        _singleStylesAvailable.Add(new SelectableListNode(Current.Gui.GetUserFriendlyClassName(avtypes[i]), avtypes[i], false));
                    }
                }

                BuildCurrentStyleListNodeList();
            }

            if (null != _view)
            {
                _view.InitializePredefinedStyles(_predefinedStyleSetsAvailable);
                _view.InitializeAvailableStyleList(_singleStylesAvailable);
                _view.InitializeStyleList(_currentItems);
            }
        }
예제 #9
0
        public TDestination Map <TDestination>(object src)
        {
            if (ReflectionService.Make().Implements <IEnumerable, TDestination>())
            {
                var type = typeof(TDestination);

                var entityType = type.GenericTypeArguments[0];

                var list = new DynamicList(entityType);

                var srcEnumerable = (IEnumerable)src;

                var constructor = ReflectionService.Make().GetConstructorForType(entityType);

                foreach (var item in srcEnumerable)
                {
                    var entity = constructor.Construct();

                    MapProperties(item, entity);

                    list.Add(entity);
                }

                return(list.Cast <TDestination>());
            }

            return(MapSingleObject <TDestination>(src));
        }
예제 #10
0
        /// <summary>
        /// Inizializza la l'instanza del client tramite reflection cercando e caricando il tipo dagli assembly caricati dall'applicazione
        /// Non viene instanziato nel caso in cui i parametri sono nulli
        /// </summary>
        public void Initialize()
        {
            logger.Debug("WSClient " + Name + " Initialization");
            //Recupero il tipo del client dagli assembly caricati a runtime
            var type = ReflectionService.GetTypeFromAsseblies(Name);

            if (type != null)
            {
                var initializedParameters = GetTypedParameters();

                //creo un'instanza della classe solo nel caso in cui il tipo ha un construttore senza parametri o la proprietà ConstructorParameters è definita
                if (ReflectionService.ExistConstructorWithoutParams(type) || !ReflectionService.ExistConstructorWithoutParams(type) && ConstructorParameters != null)
                {
                    Instance = Activator.CreateInstance(type: type, args: initializedParameters.ToArray());
                }
                else //Segnalo nel log come avere informazioni sui parametri del client
                {
                    logger.Info("WSClient : " + Name + "Attenzione parametri del construttore non impostati, richiamare il metodo BaseProxy.GetClientConstructorInfo(nomeServizio) /r/n per avere ulteriori informazioni in merito a cosa sia obbligatorio per instanziare la classe");
                }
            }
            else
            {
                logger.Debug("Type of : " + Name);
                throw new ArgumentNullException("Type of : " + Name);
            }
        }
예제 #11
0
 public SQLitePlatformAndroid()
 {
     SQLiteApi         = new SQLiteApiAndroid();
     StopwatchFactory  = new StopwatchFactory();
     ReflectionService = new ReflectionService();
     VolatileService   = new VolatileService();
 }
예제 #12
0
        /// <summary>
        /// Tests to see if a type has an attribute
        /// </summary>
        /// <param name="attributeType"></param>
        /// <param name="attributeFilter"></param>
        /// <returns></returns>
        public TypesThatConfiguration HaveAttribute(Type attributeType, Func <Attribute, bool> attributeFilter = null)
        {
            var notValue = GetNotAndingValue();
            Func <Type, bool> newFilter;

            if (attributeFilter != null)
            {
                var localFunc = attributeFilter;

                newFilter = t => t.GetTypeInfo().GetCustomAttributes(true).
                            Where(a => ReflectionService.CheckTypeIsBasedOnAnotherType(a.GetType(), attributeType)).
                            Any(a => localFunc((Attribute)a))
                            == notValue;
            }
            else
            {
                newFilter = t => t.GetTypeInfo().GetCustomAttributes(attributeType, true).
                            Any(a => ReflectionService.CheckTypeIsBasedOnAnotherType(a.GetType(), attributeType))
                            == notValue;
            }

            Add(newFilter);

            return(this);
        }
        /// <summary>
        ///
        /// </summary>
        public static void RegisterAllModules(this ContainerBuilder containerBuilder, params string[] searchPatterns)
        {
            ReflectionService reflectionService = new ReflectionService();

            Log.Trace("Searching for and registering all Autofac Modules");
            List <Assembly> assemblies = reflectionService.GetLocalAssemblies(searchPatterns);

            Log.Trace(m => m(
                          "Found {0} assemblies: {1}"
                          , assemblies.Count
                          , assemblies.ToCsv(", ", a => a.GetName().Name)));

            List <Type> allTypesFromAllAssemblies = reflectionService.GetAllTypes(assemblies);

            List <Type> candidateAutofacAssemblyTypes = (
                from t in allTypesFromAllAssemblies
                .Where(type => typeof(Autofac.Module).IsAssignableFrom(type))
                .Where(type => type.GetConstructor(Type.EmptyTypes) != null)
                select t
                ).ToList();

            Log.Trace(m => m("Found {0} candidate AutofacModule types: {1}", candidateAutofacAssemblyTypes.Count, candidateAutofacAssemblyTypes.ToCsv(", ", t => t.FullName)));

            candidateAutofacAssemblyTypes
            .Select(Activator.CreateInstance)
            .Cast <IModule>()
            .ToList()
            .ForEach(module =>
            {
                Log.Trace(m => m("Registering Autofac Module: '{0}'", module.GetType().FullName));
                containerBuilder.RegisterModule(module);
            });
        }
        public override void Execute(ServiceBusConfiguration configuration)
        {
            var factoryTypes = new List <Type>();

            ReflectionService.GetAssemblies(AppDomain.CurrentDomain.BaseDirectory).ForEach(assembly => factoryTypes.AddRange(ReflectionService.GetTypes <IQueueFactory>(assembly)));

            foreach (var type in factoryTypes.Union(ReflectionService.GetTypes <IQueueFactory>()))
            {
                try
                {
                    type.AssertDefaultConstructor(string.Format(Resources.DefaultConstructorRequired,
                                                                "Queue factory", type.FullName));

                    var instance = (IQueueFactory)Activator.CreateInstance(type);

                    if (!configuration.Queues.ContainsQueueFactory(instance.Scheme))
                    {
                        configuration.Queues.RegisterQueueFactory(instance);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warning(string.Format("Queue factory not instantiated: {0}", ex.Message));
                }
            }
        }
        public TInterface Provide <TInterface>(params object[] args)
        {
            var constructor = ReflectionService.Make()
                              .FilterAlloweImplementers <IEnTierGeneric>()
                              .FindConstructor <TInterface>(args);

            return(constructor.Construct());
        }
예제 #16
0
 public SQLitePlatformOSX()
 {
     SQLiteApi         = new SQLiteApiOSX();
     StopwatchFactory  = new StopwatchFactory();
     ReflectionService = new ReflectionService();
     //TODO: The original VolatileService is slightly different on OSX. There's no indication as to whether this was done for compilation reasons, or OSX just behaves differently. So, in future we may need to dependency inject the VolatileService for OSX. If that happens, the VolatileService is available in the original SQLite PCL repo.
     VolatileService = new VolatileService();
 }
예제 #17
0
        public void GetMetadataTypeShouldNotReturnType()
        {
            var target = new ReflectionService();
            var type   = typeof(TestModel);
            var actual = target.GetMetadataType(type);

            Assert.IsNull(actual);
        }
예제 #18
0
        public void GetElementTypeShouldReturnException()
        {
            var classType = typeof(ComplexModel);

            var target = new ReflectionService();

            Assert.ThrowsException <ArgumentException>(() => target.GetElementType(classType));
        }
예제 #19
0
        public void StringShouldNotReturnIsCollection()
        {
            var target     = new ReflectionService();
            var stringType = typeof(string);
            var actual     = target.IsCollection(stringType);

            Assert.IsFalse(actual);
        }
예제 #20
0
        public void InvokeGenericMethod_StaticNoopMethod_Success()
        {
            var service = new ReflectionService();

            var result = service.InvokeGenericMethod(typeof(Demo), null, "NoopStaticGeneric", new[] { typeof(int) });

            result.ShouldBeNull();
        }
예제 #21
0
        public void GetPropertiesInheritClass()
        {
            var values = ReflectionService.GetPropertiesFromObject(new InheritTestClass());

            Assert.Equal(2, values.Count);
            Assert.Equal(1, values["PropOne"]);
            Assert.Equal(2, values["PropTwo"]);
        }
예제 #22
0
        public void GetPropertiesFromObject()
        {
            var values = ReflectionService.GetPropertiesFromObject(new { Test = "Property", Value = 4 });

            Assert.Equal(2, values.Count);
            Assert.Equal("Property", values["Test"]);
            Assert.Equal(4, values["Value"]);
        }
예제 #23
0
        /// <summary>
        /// Applies null check and disposal scope tracking logic to an expression
        /// </summary>
        /// <param name="scope"></param>
        /// <param name="request"></param>
        /// <param name="expression"></param>
        /// <param name="allowDisposableTracking"></param>
        /// <returns></returns>
        public static Expression ApplyNullCheckAndAddDisposal(IInjectionScope scope, IActivationExpressionRequest request, Expression expression, bool allowDisposableTracking)
        {
            if (expression.Type != request.ActivationType &&
                !ReflectionService.CheckTypeIsBasedOnAnotherType(expression.Type, request.ActivationType))
            {
                expression = Expression.Convert(expression, request.ActivationType);
            }

            if (!allowDisposableTracking)
            {
                if (request.DefaultValue != null)
                {
                    var method = typeof(ExpressionUtilities).GetRuntimeMethods()
                                 .FirstOrDefault(m => m.Name == "ValueOrDefault");

                    var closedMethod = method.MakeGenericMethod(request.ActivationType);

                    return(Expression.Call(closedMethod, expression, Expression.Constant(request.DefaultValue.DefaultValue, request.ActivationType)));
                }

                if (!scope.ScopeConfiguration.Behaviors.AllowInstanceAndFactoryToReturnNull &&
                    request.IsRequired)
                {
                    var closedMethod = CheckForNullMethodInfo.MakeGenericMethod(request.ActivationType);

                    return(Expression.Call(closedMethod,
                                           Expression.Constant(request.GetStaticInjectionContext()),
                                           expression));
                }

                return(expression);
            }
            if (request.DefaultValue != null)
            {
                var method = typeof(ExpressionUtilities).GetRuntimeMethods()
                             .FirstOrDefault(m => m.Name == "AddToDisposableScopeOrDefault");

                var closedMethod = method.MakeGenericMethod(request.ActivationType);

                return(Expression.Call(closedMethod, request.DisposalScopeExpression, expression, Expression.Constant(request.DefaultValue.DefaultValue, request.ActivationType)));
            }

            if (scope.ScopeConfiguration.Behaviors.AllowInstanceAndFactoryToReturnNull ||
                !request.IsRequired)
            {
                var closedMethod = AddToDisposalScopeMethodInfo.MakeGenericMethod(request.ActivationType);

                return(Expression.Call(closedMethod, request.DisposalScopeExpression, expression));
            }
            else
            {
                var closedMethod = CheckForNullAndAddToDisposalScopeMethodInfo.MakeGenericMethod(request.ActivationType);

                return(Expression.Call(closedMethod,
                                       request.DisposalScopeExpression,
                                       Expression.Constant(request.GetStaticInjectionContext()), expression));
            }
        }
예제 #24
0
        public static IBootstrapConfiguration Configuration()
        {
            var result  = new BootstrapConfiguration();
            var section = ConfigurationSectionProvider.Open <BootstrapSection>("shuttle", "bootstrap");

            var reflectionService = new ReflectionService();

            if (section != null)
            {
                result.Scan = section.Scan;

                foreach (BootstrapAssemblyElement assemblyElement in section.Assemblies)
                {
                    var assembly = reflectionService.FindAssemblyNamed(assemblyElement.Name);

                    if (assembly == null)
                    {
                        throw new ConfigurationErrorsException(
                                  string.Format(Resources.AssemblyNameNotFound, assemblyElement.Name));
                    }

                    result.AddAssembly(assembly);
                }
            }

            if (result.Scan != BootstrapScan.None)
            {
                foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    result.AddAssembly(assembly);
                }
            }

            switch (result.Scan)
            {
            case BootstrapScan.All:
            {
                foreach (var assembly in reflectionService.GetAssemblies())
                {
                    result.AddAssembly(assembly);
                }

                break;
            }

            case BootstrapScan.Shuttle:
            {
                foreach (var assembly in reflectionService.GetMatchingAssemblies("^Shuttle\\."))
                {
                    result.AddAssembly(assembly);
                }

                break;
            }
            }

            return(result);
        }
예제 #25
0
        public void GetMetadataTypeShouldReturnType()
        {
            var target   = new ReflectionService();
            var type     = typeof(ComplexModel);
            var actual   = target.GetMetadataType(type);
            var expected = typeof(ComplexMetadata);

            Assert.AreEqual(expected, actual);
        }
예제 #26
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="extraData">extra data</param>
        public InjectionContext(object extraData)
        {
            ExtraData  = extraData;
            SharedData = new InjectionContextSharedData();

            _extraDataProperties = extraData != null?
                                   ReflectionService.GetPropertiesFromObject(extraData, casing : ReflectionService.PropertyCasing.Lower) :
                                       ImmutableHashTree <string, object> .Empty;
        }
예제 #27
0
        public void SetUp()
        {
            _typeAssemblerMock    = MockRepository.GenerateStrictMock <ITypeAssembler>();
            _typeCacheMock        = MockRepository.GenerateStrictMock <ITypeCache>();
            _constructorCallCache = MockRepository.GenerateStrictMock <IConstructorCallCache>();
            _constructorForAssembledTypeCacheMock = MockRepository.GenerateStrictMock <IConstructorForAssembledTypeCache>();

            _service = new ReflectionService(_typeAssemblerMock, _typeCacheMock, _constructorCallCache, _constructorForAssembledTypeCacheMock);
        }
예제 #28
0
        public void SetUp()
        {
            _typeAssemblerMock    = new Mock <ITypeAssembler> (MockBehavior.Strict);
            _typeCacheMock        = new Mock <ITypeCache> (MockBehavior.Strict);
            _constructorCallCache = new Mock <IConstructorCallCache> (MockBehavior.Strict);
            _constructorForAssembledTypeCacheMock = new Mock <IConstructorForAssembledTypeCache> (MockBehavior.Strict);

            _service = new ReflectionService(_typeAssemblerMock.Object, _typeCacheMock.Object, _constructorCallCache.Object, _constructorForAssembledTypeCacheMock.Object);
        }
예제 #29
0
        public void InvokeGenericMethod_ObjectTypeIsNull_ThrowException()
        {
            var service = new ReflectionService();

            var exception = Assert.Throws <ArgumentNullException>(() => service.InvokeGenericMethod(null, null, null, null));

            exception.ShouldNotBeNull();
            exception.ParamName.ShouldBe("objectType");
        }
예제 #30
0
        public void InvokeGenericMethod_NonGenericStaticMethod_ThrowException()
        {
            var service = new ReflectionService();

            var exception = Assert.Throws <MethodNotFoundException>(() => service.InvokeGenericMethod(typeof(Demo), null, "NonGenericStaticMethodDemo", new[] { typeof(int) }));

            exception.ShouldNotBeNull();
            exception.MethodName.ShouldBe("NonGenericStaticMethodDemo");
        }
예제 #31
0
        public void ListShouldReturnIsCollection()
        {
            var target = new ReflectionService();

            var listType = typeof(List <ComplexModel>);

            var actual = target.IsCollection(listType);

            Assert.IsTrue(actual);
        }
        public override void Initialize(IServiceBus bus)
        {
            _messageHandlerTypes.Clear();

            var reflectionService = new ReflectionService();

            foreach (var type in reflectionService.GetTypes(typeof(IMessageHandler<>)))
            {
                if (type.GetConstructor(Type.EmptyTypes) != null)
                {
                    AddMessageHandlerType(type);
                }
                else
                {
                    _log.Warning(string.Format(ESBResources.DefaultMessageHandlerFactoryNoDefaultConstructor, type.FullName));
                }
            }
        }
예제 #33
0
 protected RegistrationTask()
 {
     ReflectionService = new ReflectionService();
 }
예제 #34
0
        public static IServiceBus StartEndpoint()
        {
            var starters = new ReflectionService().GetTypes<IStartEndpoint>().ToList();

            if (starters.Count != 1)
            {
                throw new ApplicationException(string.Format(ESBResources.StartEndpointException, starters.Count()));
            }

            var type = starters.ElementAt(0);

            type.AssertDefaultConstructor(string.Format(ESBResources.StartEndpointRequiresDefaultConstructor, type.FullName));

            return ((IStartEndpoint)Activator.CreateInstance(type)).Start();
        }
        private void InitializeDataStoreRepository()
        {
            Log.Debug("Initializing DataStoreRepositoryType.");

            if (string.IsNullOrEmpty(DataStoreRepositoryType))
            {
                Log.Warning(ManagementResources.NoDataStoreRepositoryTypeSpecified);

                return;
            }

            Log.Information(string.Format(ManagementResources.AttemptCreationOfDataStoreRepository, DataStoreRepositoryType));

            try
            {
                var type = new ReflectionService().GetType(
                    candidate =>
                    candidate.Name.Equals(DataStoreRepositoryType, StringComparison.InvariantCultureIgnoreCase)
                    ||
                    candidate.AssemblyQualifiedName.Equals(DataStoreRepositoryType, StringComparison.InvariantCultureIgnoreCase));

                if (type == null)
                {
                    Log.Error(string.Format(ManagementResources.DataStoreRepositoryTypeNotFound, DataStoreRepositoryType));

                    return;
                }

                dataStoreRepository = (IDataStoreRepository)Activator.CreateInstance(type);

                HasDataStoreRepository = true;

                Log.Information(string.Format(ManagementResources.DataStoreRepositoryCreationSuccessful, DataStoreRepositoryType));
            }
            catch (Exception ex)
            {
                Log.Error(string.Format(ManagementResources.DataStoreRepositoryCreationException, DataStoreRepositoryType, ex.CompactMessages()));
            }
        }
예제 #36
0
 /// <summary>
 /// Create an instance of class reflection provider
 /// </summary>
 /// <param name="service">The service</param>
 /// <param name="container">The reflection data source</param>
 public ReflectionProvider(ReflectionService service, DefaultContainer container)
     : base(new DataServiceProviderArgs(service, container, null, true)) {}