コード例 #1
0
        private static string GetXmlCommentsPath()
        {
            var assembly = TypeLocator.GetEntryPointAssembly();
            var xmlFile  = $@"{AppDomain.CurrentDomain.BaseDirectory}\{assembly.GetName().Name}.xml";

            return(File.Exists(xmlFile) ? xmlFile : null);
        }
コード例 #2
0
        private void LoadProcessors()
        {
            _processors = new Dictionary <string, IConnector>();

            var typeLocator = new TypeLocator();
            var types       = typeLocator.GetAllMatchingTypes(IsValidFilter);

            foreach (var type in types)
            {
                try
                {
                    var processor = Activator.CreateInstance(type) as IConnector;
                    if (processor != null &&
                        !string.IsNullOrEmpty(processor.Name) &&
                        !_processors.ContainsKey(processor.Name))
                    {
                        _processors.Add(processor.Name, processor);
                    }
                }
                catch (Exception e)
                {
                    Logger.ErrorFormat("Unable to create {0} while registering connections.{1}", type.FullName, e.Message);
                }
            }
        }
コード例 #3
0
        private IXamlLoader CreateXamlLoader()
        {
            var deps        = new Platform(new GtkEventSource(this), new GtkRenderSurface(this), textEngine);
            var typeLocator = new TypeLocator(() => ResourceStore, deps, () => XamlLoader.StringSourceValueConverter);

            return(new OmniGuiXamlLoader(assemblies, typeLocator, () => new StyleWatcher(ResourceStore.Styles)));
        }
コード例 #4
0
        private void PluginInit()
        {
            var types = TypeLocator.FindTypes("*plugin*.dll", typeof(PanelBase));

            foreach (Type type in types)
            {
                PluginInfo             info = new PluginInfo();
                PanelMetadataAttribute atty = type.GetAttribute <PanelMetadataAttribute>();
                info.PluginType = type;
                if (atty != null && !string.IsNullOrWhiteSpace(atty.DisplayName))
                {
                    info.Name = atty.DisplayName;
                }
                else
                {
                    info.Name = PascalCaseSplitter.Split(type.Name);
                }
                if (atty != null && !string.IsNullOrWhiteSpace(atty.IconPath))
                {
                    info.Icon = WPFHelpers.GetImage(atty.IconPath, info.PluginType.Assembly);
                }
                if (info.Icon == null)
                {
                    info.Icon = WPFHelpers.GetImage("images/puzzle-piece.png");
                }
                this.Invoke(() => Plugins.Add(info));
            }
            this.BeginInvoke(() => { if (SelectedPanel == null)
                                     {
                                         SelectedPanel = Plugins[0];
                                     }
                             });
        }
コード例 #5
0
        private static SortedDictionary <string, Command> GetCommandsInternal()
        {
            var commands        = new SortedDictionary <string, Command>();
            var typeLocator     = new TypeLocator();
            var allCommandTypes = typeLocator.GetAllMatchingTypes(
                t => t != null &&
                t.IsClass &&
                !t.IsAbstract &&
                t.IsVisible &&
                typeof(IConsoleCommand).IsAssignableFrom(t));

            foreach (var cmd in allCommandTypes)
            {
                var attr             = cmd.GetCustomAttributes(typeof(ConsoleCommandAttribute), false).FirstOrDefault() ?? new ConsoleCommandAttribute(CreateCommandFromClass(cmd.Name), Constants.GeneralCategory, $"Prompt_{cmd.Name}_Description");
                var assemblyName     = cmd.Assembly.GetName();
                var version          = assemblyName.Version.ToString();
                var commandAttribute = (ConsoleCommandAttribute)attr;
                var key = commandAttribute.Name.ToUpper();
                var localResourceFile = ((IConsoleCommand)Activator.CreateInstance(cmd))?.LocalResourceFile;
                commands.Add(key, new Command
                {
                    Category    = LocalizeString(commandAttribute.Category, localResourceFile),
                    Description = LocalizeString(commandAttribute.Description, localResourceFile),
                    Key         = key,
                    Name        = commandAttribute.Name,
                    Version     = version,
                    CommandType = cmd
                });
            }
            return(commands);
        }
コード例 #6
0
        public void LocatesAllServiceRouteMappers()
        {
            var assemblyLocator = new Mock<IAssemblyLocator>();

            //including the assembly with object ensures that the assignabliity is done correctly
            var assembliesToReflect = new IAssembly[2];
            assembliesToReflect[0] = new AssemblyWrapper(GetType().Assembly);
            assembliesToReflect[1] = new AssemblyWrapper(typeof (Object).Assembly);

            assemblyLocator.Setup(x => x.Assemblies).Returns(assembliesToReflect);

            var locator = new TypeLocator {AssemblyLocator = assemblyLocator.Object};

            List<Type> types = locator.GetAllMatchingTypes(ServicesRoutingManager.IsValidServiceRouteMapper).ToList();

            //if new ServiceRouteMapper classes are added to the assembly they willl likely need to be added here
            CollectionAssert.AreEquivalent(
                new[]
                    {
                        typeof (FakeServiceRouteMapper),
                        typeof (ReflectedServiceRouteMappers.EmbeddedServiceRouteMapper),
                        typeof (ExceptionOnCreateInstanceServiceRouteMapper),
                        typeof (ExceptionOnRegisterServiceRouteMapper)
                    }, types);
        }
コード例 #7
0
        private static IEnumerable <IModuleInjectionFilter> GetFilters()
        {
            var typeLocator          = new TypeLocator();
            IEnumerable <Type> types = typeLocator.GetAllMatchingTypes(IsValidModuleInjectionFilter);

            foreach (Type filterType in types)
            {
                IModuleInjectionFilter filter;
                try
                {
                    filter = Activator.CreateInstance(filterType) as IModuleInjectionFilter;
                }
                catch (Exception e)
                {
                    Logger.ErrorFormat("Unable to create {0} while registering module injection filters.  {1}", filterType.FullName,
                                       e.Message);
                    filter = null;
                }

                if (filter != null)
                {
                    yield return(filter);
                }
            }
        }
コード例 #8
0
        private static void CleanupDatabaseIfDirty(IExportImportRepository repository)
        {
            var exportDto = repository.GetSingleItem <ExportDto>();
            var isDirty   = exportDto.IsDirty;

            exportDto.IsDirty = true;
            repository.UpdateSingleItem(exportDto);
            if (!isDirty)
            {
                return;
            }

            var typeLocator = new TypeLocator();
            var types       = typeLocator.GetAllMatchingTypes(
                t => t != null && t.IsClass && !t.IsAbstract && t.IsVisible &&
                typeof(BasicExportImportDto).IsAssignableFrom(t));

            foreach (var type in from type in types
                     let typeName = type.Name
                                    where !CleanUpIgnoredClasses.Contains(typeName)
                                    select type)
            {
                try
                {
                    repository.CleanUpLocal(type.Name);
                }
                catch (Exception e)
                {
                    Logger.ErrorFormat(
                        "Unable to clear {0} while calling CleanupDatabaseIfDirty. Error: {1}",
                        type.Name,
                        e.Message);
                }
            }
        }
        public void RegisterRoutesIsCalledOnAllServiceRouteMappersEvenWhenSomeThrowExceptions()
        {
            FakeServiceRouteMapper.RegistrationCalls = 0;
            var assembly = new Mock <IAssembly>();

            assembly.Setup(x => x.GetTypes()).Returns(new[]
            {
                typeof(ExceptionOnRegisterServiceRouteMapper),
                typeof(ExceptionOnCreateInstanceServiceRouteMapper),
                typeof(FakeServiceRouteMapper)
            });
            var al = new Mock <IAssemblyLocator>();

            al.Setup(x => x.Assemblies).Returns(new[] { assembly.Object });
            var tl = new TypeLocator {
                AssemblyLocator = al.Object
            };
            var srm = new ServicesRoutingManager(new RouteCollection())
            {
                TypeLocator = tl
            };

            srm.RegisterRoutes();

            Assert.AreEqual(1, FakeServiceRouteMapper.RegistrationCalls);
        }
        public void LocatesAllServiceRouteMappers()
        {
            var assemblyLocator = new Mock <IAssemblyLocator>();

            //including the assembly with object ensures that the assignabliity is done correctly
            var assembliesToReflect = new IAssembly[2];

            assembliesToReflect[0] = new AssemblyWrapper(GetType().Assembly);
            assembliesToReflect[1] = new AssemblyWrapper(typeof(Object).Assembly);

            assemblyLocator.Setup(x => x.Assemblies).Returns(assembliesToReflect);

            var locator = new TypeLocator {
                AssemblyLocator = assemblyLocator.Object
            };

            List <Type> types = locator.GetAllMatchingTypes(ServicesRoutingManager.IsValidServiceRouteMapper).ToList();

            //if new ServiceRouteMapper classes are added to the assembly they willl likely need to be added here
            CollectionAssert.AreEquivalent(
                new[]
            {
                typeof(FakeServiceRouteMapper),
                typeof(ReflectedServiceRouteMappers.EmbeddedServiceRouteMapper),
                typeof(ExceptionOnCreateInstanceServiceRouteMapper),
                typeof(ExceptionOnRegisterServiceRouteMapper)
            }, types);
        }
コード例 #11
0
        private Dictionary <Type, ServiceHostInfo> FindAllHosts()
        {
            var hosts = new Dictionary <Type, ServiceHostInfo>();

            foreach (Type type in TypeLocator.FindTypes(_dllSearchPattern, typeof(IServiceHost)))
            {
                ServiceHostInfo info = new ServiceHostInfo();

                Type interfaceType = (Type)type.GetMethod("GetInterfaceType", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy).Invoke(null, null);

                info.InterfaceType = interfaceType;
                info.Logger        = _logger;
                info.Host          = new ServiceHost(type);

                info.Host.Description.Behaviors.Add(new HostErrorHandlerBehavior(info));
                info.Host.Authorization.ServiceAuthorizationManager = new RoleBasedAuthorizationManager();

                ContractDescription contract = ContractDescription.GetContract(interfaceType);

                EndpointAddress endpoint = EndpointInformation.BuildEndpoint(new EndpointInformation(), ServerConnectionInformation.Instance, interfaceType);
                Binding         binding  = BindingInformation.BuildBinding(new BindingInformation(), ServerConnectionInformation.Instance);
                ServiceEndpoint service  = new ServiceEndpoint(contract, binding, endpoint);
                info.Host.AddServiceEndpoint(service);

                hosts.Add(interfaceType, info);
            }

            return(hosts);
        }
コード例 #12
0
        public static IEnumerable <BasePortableService> GetPortableImplementors()
        {
            var typeLocator = new TypeLocator();
            var types       = typeLocator.GetAllMatchingTypes(
                t => t != null && t.IsClass && !t.IsAbstract && t.IsVisible &&
                typeof(BasePortableService).IsAssignableFrom(t));

            foreach (var type in types)
            {
                BasePortableService portable2Type;
                try
                {
                    portable2Type = Activator.CreateInstance(type) as BasePortableService;
                }
                catch (Exception e)
                {
                    Logger.ErrorFormat("Unable to create {0} while calling BasePortableService implementors. {1}",
                                       type.FullName, e.Message);
                    portable2Type = null;
                }

                if (portable2Type != null)
                {
                    yield return(portable2Type);
                }
            }
        }
コード例 #13
0
ファイル: TypeLocatorBehavior.cs プロジェクト: EdsonF/nextra
        public void Setup()
        {
            var implementationLocator = new TypeLocator<ISomeInterface>(Assembly.GetExecutingAssembly());
            var descendantLocator = new TypeLocator<SomeBaseClass>(Assembly.GetExecutingAssembly());

            implementations = implementationLocator.FindAll();
            descendants = descendantLocator.FindAll();
        }
コード例 #14
0
ファイル: OmniGuiView.cs プロジェクト: robertmuehsig/OmniGUI
        private IXamlLoader CreateXamlLoader()
        {
            var androidEventSource = new iOSEventSource(this);
            var deps        = new Platform(androidEventSource, new iOSRenderSurface(this), new iOSTextEngine());
            var typeLocator = new TypeLocator(() => ResourceStore, deps, () => XamlLoader.StringSourceValueConverter);

            return(new OmniGuiXamlLoader(Assemblies.AssembliesInAppFolder.ToArray(), typeLocator, () => new StyleWatcher(ResourceStore.Styles)));
        }
コード例 #15
0
        public void Setup()
        {
            var implementationLocator = new TypeLocator <ISomeInterface>(Assembly.GetExecutingAssembly());
            var descendantLocator     = new TypeLocator <SomeBaseClass>(Assembly.GetExecutingAssembly());

            _implementations = implementationLocator.FindAll();
            _descendants     = descendantLocator.FindAll();
        }
コード例 #16
0
        public void Run(IApplication appInstance)
        {
            appInstance.ReportHealthStateAction = (property, state, description) => { };
            appInstance.ReportRecurrentHealthStateAction = (property, state, timeToLive, description) => { };
            appInstance.GetCodePackageVersionFunction =
                () => TypeLocator.GetEntryPointAssembly().GetName().Version.ToString();
            appInstance.GetDataPackageVersionFunction = packageName => $"{packageName}.{DateTime.Now.Ticks}";

            Application.Instance = appInstance;
        }
コード例 #17
0
        private static IEnumerable <Type> GetAllMenuItemTypes()
        {
            var typeLocator = new TypeLocator();

            return(typeLocator.GetAllMatchingTypes(
                       t => t != null &&
                       t.IsClass &&
                       !t.IsAbstract &&
                       typeof(BaseMenuItem).IsAssignableFrom(t)));
        }
コード例 #18
0
        public MainPage()
        {
            InitializeComponent();

            Platform.Current = new UwpPlatform(this, Canvas);
            textEngine       = (Win2DTextEngine)Platform.Current.TextEngine;

            Loaded += OnLoaded;
            locator = new TypeLocator(() => ControlTemplates);
        }
コード例 #19
0
        private static IEnumerable <Type> GetAllApiControllers()
        {
            var typeLocator = new TypeLocator();

            return(typeLocator.GetAllMatchingTypes(
                       t => t != null &&
                       t.IsClass &&
                       !t.IsAbstract &&
                       t.IsVisible &&
                       typeof(PersonaBarApiController).IsAssignableFrom(t)));
        }
コード例 #20
0
        public void TryGetResourceDescriptor_Returns_False_If_Type_Is_IIdentifiable()
        {
            // Arrange
            var resourceType = typeof(String);

            // Act
            var isJsonApiResource = TypeLocator.TryGetResourceDescriptor(resourceType, out var _);

            // Assert
            Assert.False(isJsonApiResource);
        }
コード例 #21
0
        public void GetIdType_Correctly_Identifies_JsonApiResource()
        {
            // Arrange
            var type = typeof(Model);

            // Act
            var idType = TypeLocator.TryGetIdType(type);

            // Assert
            Assert.Equal(typeof(int), idType);
        }
コード例 #22
0
        public void GetIdType_Correctly_Identifies_NonJsonApiResource()
        {
            // Arrange
            var type = typeof(DerivedType);

            // Act
            var idType = TypeLocator.TryGetIdType(type);

            // Assert
            Assert.Null(idType);
        }
コード例 #23
0
        public void GetIdentifiableTypes_Locates_Identifiable_Resource()
        {
            // Arrange
            var resourceType = typeof(Model);

            // Act
            var results = TypeLocator.GetIdentifiableTypes(resourceType.Assembly);

            // Assert
            Assert.Contains(results, r => r.ResourceType == resourceType);
        }
コード例 #24
0
        public void TryGetResourceDescriptor_Returns_False_If_Type_Is_IIdentifiable()
        {
            // Arrange
            var resourceType = typeof(String);

            // Act
            var descriptor = TypeLocator.TryGetResourceDescriptor(resourceType);

            // Assert
            Assert.Null(descriptor);
        }
コード例 #25
0
        private static IEnumerable <Type> GetAllEventTypes <T>() where T : class
        {
            var typeLocator = new TypeLocator();

            return(typeLocator.GetAllMatchingTypes(
                       t => t != null &&
                       t.IsClass &&
                       !t.IsAbstract &&
                       t.IsVisible &&
                       typeof(T).IsAssignableFrom(t) &&
                       (IgnoreVersionMatchCheck(t) || VersionMatched(t))));
        }
コード例 #26
0
        public void GetIdType_Correctly_Identifies_NonJsonApiResource()
        {
            // Arrange
            var  type           = typeof(DerivedType);
            Type expectedIdType = null;

            // Act
            var idType = TypeLocator.GetIdType(type);

            // Assert
            Assert.Equal(expectedIdType, idType);
        }
コード例 #27
0
        private (bool isJsonApiResource, Type idType) GetIdType(Type resourceType)
        {
            var possible = TypeLocator.GetIdType(resourceType);

            if (possible.isJsonApiResource)
            {
                return(possible);
            }

            _validationResults.Add(new ValidationResult(LogLevel.Warning, $"{resourceType} does not implement 'IIdentifiable<>'. "));

            return(false, null);
        }
コード例 #28
0
        public void TryGetResourceDescriptor_Returns_True_If_Type_Is_IIdentifiable()
        {
            // Arrange
            var resourceType = typeof(Model);

            // Act
            var isJsonApiResource = TypeLocator.TryGetResourceDescriptor(resourceType, out var descriptor);

            // Assert
            Assert.True(isJsonApiResource);
            Assert.Equal(resourceType, descriptor.ResourceType);
            Assert.Equal(typeof(int), descriptor.IdType);
        }
コード例 #29
0
        public void GetIdType_Correctly_Identifies_NonJsonApiResource()
        {
            // arrange
            var  type          = typeof(DerivedType);
            Type exextedIdType = null;

            // act
            var result = TypeLocator.GetIdType(type);

            // assert
            Assert.NotNull(result);
            Assert.False(result.isJsonApiResource);
            Assert.Equal(exextedIdType, result.idType);
        }
コード例 #30
0
        public void GetIdType_Correctly_Identifies_JsonApiResource()
        {
            // arrange
            var type          = typeof(Model);
            var exextedIdType = typeof(int);

            // act
            var result = TypeLocator.GetIdType(type);

            // assert
            Assert.NotNull(result);
            Assert.True(result.isJsonApiResource);
            Assert.Equal(exextedIdType, result.idType);
        }
コード例 #31
0
        public void GetIdentifiableTypes_Only_Contains_IIdentifiable_Types()
        {
            // Arrange
            var resourceType = typeof(Model);

            // Act
            var resourceDescriptors = TypeLocator.GetIdentifiableTypes(resourceType.Assembly);

            // Assert
            foreach (var resourceDescriptor in resourceDescriptors)
            {
                Assert.True(typeof(IIdentifiable).IsAssignableFrom(resourceDescriptor.ResourceType));
            }
        }
コード例 #32
0
        /// <summary>
        /// Discovers the implemented hooks for a model.
        /// </summary>
        /// <returns>The implemented hooks for model.</returns>
        void DiscoverImplementedHooksForModel()
        {
            Type parameterizedResourceDefinition = typeof(ResourceDefinition <TEntity>);
            var  derivedTypes = TypeLocator.GetDerivedTypes(typeof(TEntity).Assembly, parameterizedResourceDefinition).ToList();


            var implementedHooks = new List <ResourceHook>();
            var enabledHooks     = new List <ResourceHook>()
            {
                ResourceHook.BeforeImplicitUpdateRelationship
            };
            var  disabledHooks = new List <ResourceHook>();
            Type targetType    = null;

            try
            {
                targetType = derivedTypes.SingleOrDefault(); // multiple containers is not supported
            }
            catch
            {
                throw new JsonApiSetupException($"It is currently not supported to" +
                                                "implement hooks across multiple implementations of ResourceDefinition<T>");
            }
            if (targetType != null)
            {
                foreach (var hook in _allHooks)
                {
                    var method = targetType.GetMethod(hook.ToString("G"));
                    if (method.DeclaringType != parameterizedResourceDefinition)
                    {
                        implementedHooks.Add(hook);
                        var attr = method.GetCustomAttributes(true).OfType <LoadDatabaseValues>().SingleOrDefault();
                        if (attr != null)
                        {
                            if (!_databaseValuesAttributeAllowed.Contains(hook))
                            {
                                throw new JsonApiSetupException($"DatabaseValuesAttribute cannot be used on hook" +
                                                                $"{hook.ToString("G")} in resource definition  {parameterizedResourceDefinition.Name}");
                            }
                            var targetList = attr.value ? enabledHooks : disabledHooks;
                            targetList.Add(hook);
                        }
                    }
                }
            }
            ImplementedHooks            = implementedHooks.ToArray();
            DatabaseValuesDisabledHooks = disabledHooks.ToArray();
            DatabaseValuesEnabledHooks  = enabledHooks.ToArray();
        }
コード例 #33
0
        public void LocateAllMatchingTypes()
        {
            var assembly = new Mock<IAssembly>();
            assembly.Setup(x => x.GetTypes()).Returns(new[] {typeof(TypeLocatorTests), typeof(ServiceRoutingManagerTests)});
            var assemblyLocator = new Mock<IAssemblyLocator>();
            assemblyLocator.Setup(x => x.Assemblies).Returns(new[] {assembly.Object});

            var typeLocator = new TypeLocator {AssemblyLocator = assemblyLocator.Object};

            var types = typeLocator.GetAllMatchingTypes(x => true).ToList();

            CollectionAssert.AreEquivalent(new[]{typeof(TypeLocatorTests), typeof(ServiceRoutingManagerTests)}, types);
            assembly.Verify(x => x.GetTypes(), Times.Once());
            assemblyLocator.Verify(x => x.Assemblies, Times.Once());
        }
コード例 #34
0
 internal ServicesRoutingManager(RouteCollection routes)
 {
     _routes = routes;
     TypeLocator = new TypeLocator();
 }
コード例 #35
0
        public void RegisterRoutesIsCalledOnAllServiceRouteMappersEvenWhenSomeThrowExceptions()
        {
            FakeServiceRouteMapper.RegistrationCalls = 0;
            var assembly = new Mock<IAssembly>();
            assembly.Setup(x => x.GetTypes()).Returns(new[]
                                                          {
                                                              typeof (ExceptionOnRegisterServiceRouteMapper),
                                                              typeof (ExceptionOnCreateInstanceServiceRouteMapper),
                                                              typeof (FakeServiceRouteMapper)
                                                          });
            var al = new Mock<IAssemblyLocator>();
            al.Setup(x => x.Assemblies).Returns(new[] {assembly.Object});
            var tl = new TypeLocator {AssemblyLocator = al.Object};
            var srm = new ServicesRoutingManager(new RouteCollection()) {TypeLocator = tl};

            srm.RegisterRoutes();

            Assert.AreEqual(1, FakeServiceRouteMapper.RegistrationCalls);
        }