/// <summary> /// WPFモジュールのインストール /// </summary> /// <returns></returns> static bool InstallWpfInApp() { TypeFinder finder = new TypeFinder(); Type t = finder.GetType("Codeer.Friendly.Windows.Wpf.Grasp.WpfAnalyzer"); if (t != null) { return true; } //参照 List<string> reference = new List<string>(); reference.Add(typeof(TargetAppInitializer).Assembly.Location); reference.Add(typeof(AppVar).Assembly.Location); reference.Add("System.dll"); reference.Add("System.Drawing.dll"); foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { switch (asm.GetName().Name) { case "PresentationCore": case "PresentationFramework": case "WindowsBase": case "System.Xaml": reference.Add(asm.Location); break; } } CompilerResults compilerResults = CspCompiler.Compile(reference.ToArray(), Resources.WpfAnalyzer); return !compilerResults.Errors.HasErrors; }
public IContainer BuildContainer() { lock (_locker) { if (_configured) return _container; var builder = new ContainerBuilder(); //type finder var typeFinder = new TypeFinder(); builder.Register(c => typeFinder); //find IDependencyRegistar implementations var drTypes = typeFinder.FindClassesOfType<IDependencyRegistar>(); foreach (var t in drTypes) { dynamic dependencyRegistar = Activator.CreateInstance(t); dependencyRegistar.Register(builder, typeFinder); } //event OnContainerBuilding(new ContainerBuilderEventArgs(builder)); _container = builder.Build(); //event OnContainerBuildingComplete(new ContainerBuilderEventArgs(builder)); _configured = true; return _container; } }
public void Find() { TypeFinder Finder = new TypeFinder(); List<System.Type> Types = Finder.Find<TypeToFindBase>(); Assert.AreEqual(18, Types.Count()); }
public Task Invoke(HttpContext httpContext) { ILibraryManager libraryManager = httpContext.GetService<ILibraryManager>(); var typeFinder = new TypeFinder(libraryManager); var assemb = typeFinder.GetLoadedAssemblies(); foreach (var a in assemb) { System.Diagnostics.Debug.WriteLine("Assembly:>>" + a.FullName); } return _next(httpContext); }
/// <summary> /// Register all controllers found in the specified assemblies /// </summary> /// <param name="containerBuilder"></param> /// <param name="assemblies"></param> /// <param name="typeFinder"></param> /// <returns></returns> public static IContainerBuilder RegisterControllers(this IContainerBuilder containerBuilder, IEnumerable<Assembly> assemblies, TypeFinder typeFinder) { //TODO: Include extenders! foreach (var type in typeFinder.FindClassesOfType<IController>(assemblies) .Where(t => t.Name.EndsWith("Controller"))) { containerBuilder.For(type).KnownAsSelf(); } return containerBuilder; }
internal int FindOrAddAuto(Type type, bool demand, bool addWithContractOnly, bool addEvenIfAutoDisabled) { TypeFinder predicate = new TypeFinder(type); int key = types.IndexOf(predicate); if (key < 0) { // check for proxy types Type underlyingType = ResolveProxies(type); if (underlyingType != null) { predicate = new TypeFinder(underlyingType); key = types.IndexOf(predicate); type = underlyingType; // if new added, make it reflect the underlying type } } if (key < 0) { MetaType metaType; // try to recognise a few familiar patterns... if ((metaType = RecogniseCommonTypes(type)) == null) { // otherwise, check if it is a contract bool shouldAdd = autoAddMissingTypes || addEvenIfAutoDisabled; if (!shouldAdd || ( addWithContractOnly && MetaType.GetContractFamily(type, null) == MetaType.AttributeFamily.None) ) { if (demand) ThrowUnexpectedType(type); return key; } metaType = Create(type); } bool weAdded = false; lock (types) { // double-checked int winner = types.IndexOf(predicate); if (winner < 0) { ThrowIfFrozen(); key = types.Add(metaType); weAdded = true; } else { key = winner; } } if (weAdded) metaType.ApplyDefaultBehaviour(); } return key; }
public IController CreateController(RequestContext requestContext, string controllerName) { var tf = new TypeFinder(); var types = tf.FindClassesOfType<ControllerBase>(new[] { Assembly.GetExecutingAssembly() }); var controllerTypes = types.Where(x => x.Name.Equals(controllerName + "Controller", StringComparison.InvariantCultureIgnoreCase)); var t = controllerTypes.SingleOrDefault(); if (t == null) return null; return Activator.CreateInstance(t) as IController; }
public static void Bootstrap() { using (new FunctionLogger(Log)) { TypeFinder Finder = new TypeFinder(Assembly.GetCallingAssembly()); foreach (Type Bootstrapper in Finder.Find<IBootstrapper>()) { Log.InfoFormat("Bootstrapping: {0}", Bootstrapper.FullName); IBootstrapper Instance = (IBootstrapper)Activator.CreateInstance(Bootstrapper); Instance.Initialise(); } } }
/// <summary> /// Register all model binders found in the specified Assemblies which are registered to types based /// on the ModelBinderForAttribute. /// </summary> /// <param name="containerBuilder"></param> /// <param name="assemblies"></param> /// <param name="typeFinder"></param> /// <returns></returns> public static IContainerBuilder RegisterModelBinders(this IContainerBuilder containerBuilder, IEnumerable<Assembly> assemblies, TypeFinder typeFinder) { foreach (var type in typeFinder.FindClassesOfType<IModelBinder>(assemblies)) { var register = containerBuilder.For(type) .KnownAs<IModelBinder>(); foreach (ModelBinderForAttribute item in type.GetCustomAttributes(typeof(ModelBinderForAttribute), true)) { register.WithMetadata<ModelBinderMetadata, Type>(prop => prop.BinderType, item.TargetType); ModelBinders.Binders.Add(item.TargetType, new ModelBinderAdapter(item.TargetType)); } } return containerBuilder; }
public void Benchmark_Finding_First_Type_In_Assemblies() { var timer = new Stopwatch(); var assemblies = new[] { //both contain the type this.GetType().Assembly, typeof (MandatoryPropertyEditor).Assembly, //these dont contain the type typeof(StandardAnalyzer).Assembly, typeof(NSubstitute.Substitute).Assembly, typeof(Remotion.Linq.DefaultQueryProvider).Assembly, typeof(NHibernate.IdentityEqualityComparer).Assembly, typeof(System.Guid).Assembly, typeof(NUnit.Framework.Assert).Assembly, typeof(Microsoft.CSharp.CSharpCodeProvider).Assembly, typeof(System.Xml.NameTable).Assembly, typeof(System.Configuration.GenericEnumConverter).Assembly, typeof(System.Web.SiteMap).Assembly, typeof(System.Data.SQLite.CollationSequence).Assembly, typeof(System.Web.Mvc.ActionResult).Assembly, typeof(Umbraco.Hive.LazyRelation<>).Assembly, typeof(Umbraco.Framework.DependencyManagement.AbstractContainerBuilder).Assembly, typeof(FixedIndexedFields).Assembly, typeof(Umbraco.Framework.Persistence.DefaultAttributeTypeRegistry).Assembly, typeof(Umbraco.Framework.Security.FixedPermissionTypes).Assembly }; //we'll use PropertyEditors for this tests since there are some int he text Extensions project var finder = new TypeFinder(); timer.Start(); var found1 = finder.FindClassesOfType<PropertyEditor, AssemblyContainsPluginsAttribute>(assemblies); timer.Stop(); Console.WriteLine("Total time to find propery editors (" + found1.Count() + ") in " + assemblies.Count() + " assemblies using AssemblyContainsPluginsAttribute: " + timer.ElapsedMilliseconds); timer.Start(); var found2 = finder.FindClassesOfType<PropertyEditor>(assemblies); timer.Stop(); Console.WriteLine("Total time to find propery editors (" + found2.Count() + ") in " + assemblies.Count() + " assemblies without AssemblyContainsPluginsAttribute: " + timer.ElapsedMilliseconds); }
public void UmbracoAreaRegistrationReceivesMetadataFromIoC() { var codeBase = Assembly.GetExecutingAssembly().CodeBase; var uri = new Uri(codeBase); var path = uri.LocalPath; var binFolder = Path.GetDirectoryName(path); var settingsFile = new FileInfo(Path.Combine(binFolder, "web.config")); var autofacBuilder = new AutofacContainerBuilder(); autofacBuilder.ForFactory( context => new UmbracoSettings(settingsFile)) .KnownAsSelf(); autofacBuilder.For<UmbracoAreaRegistration>() .KnownAsSelf() .WithResolvedParam(context => context.Resolve<IRouteHandler>("TreeRouteHandler")); //why is this here? var typeFinder = new TypeFinder(); var componentRegistrar = new UmbracoComponentRegistrar(); componentRegistrar.RegisterEditorControllers(autofacBuilder, typeFinder); componentRegistrar.RegisterMenuItems(autofacBuilder, typeFinder); //componentRegistrar.RegisterPackageActions(autofacBuilder, typeFinder); componentRegistrar.RegisterPropertyEditors(autofacBuilder, typeFinder); componentRegistrar.RegisterSurfaceControllers(autofacBuilder, typeFinder); componentRegistrar.RegisterTreeControllers(autofacBuilder, typeFinder); //build the container var container = autofacBuilder.Build(); var result = container.Resolve<UmbracoAreaRegistration>(); Assert.IsNotNull(result); }
private void BootPermissions() { const string ROOT_NAMESPACE = "Fido.Action.Models."; using (new FunctionLogger(Log)) { var ModelTypes = new TypeFinder().Find<ILogicModel>().Where(t => t.Namespace.StartsWith(ROOT_NAMESPACE)); foreach (var ModelType in ModelTypes) { var ModelInstance = (ILogicModel)Activator.CreateInstance(ModelType); var Area = string.Join(string.Empty, ModelType.Namespace.Skip(ROOT_NAMESPACE.Length)); if (ModelInstance.ReadAccess == Access.Permissioned) Ensure(Function.Read, ModelType.Name, Area); if (ModelInstance.WriteAccess == Access.Permissioned) Ensure(Function.Write, ModelType.Name, Area); } var RoleService = ServiceFactory.CreateService<IRoleService>(); RoleService.SetAdministrationRole("Administrator"); } }
public object AcquireObject(string className) { return(AcquireObject(TypeFinder.ResolveType(className))); }
public restExtension(string extensionAlias, string methodName) { bool allowed = false; bool fromFile = true; XmlDocument baseDoc = new XmlDocument(); //RESTExtension document... baseDoc.Load(IOHelper.MapPath(SystemFiles.RestextensionsConfig)); XmlNode baseExt = baseDoc.SelectSingleNode("/RestExtensions/ext [@alias='" + extensionAlias + "']/permission [@method='" + methodName + "']"); //if not there.. it's not allowed... if (baseExt != null) { //Access for all ? if (baseExt.Attributes["allowAll"] != null) { if (baseExt.Attributes["allowAll"].Value.ToString().ToLower() == "true") { allowed = true; } } if (!allowed) { //Member Based permissions.. check for group, type and ID... Member currentMem = Member.GetCurrentMember(); //not basic.. and not logged in? - out.. if (currentMem == null) { allowed = false; } else //do member authentication stuff... { allowed = memberAuthentication(baseExt, currentMem); } } } else { //check for RestExtensionAttribute foreach (Type t in TypeFinder.FindClassesMarkedWithAttribute(typeof(RestExtension))) { var temp = t.GetCustomAttributes(typeof(RestExtension), false).OfType <RestExtension>(); if (temp.Where(x => x.GetAlias() == extensionAlias) .Any()) { MethodInfo mi = t.GetMethod(methodName); if (mi != null) { //check allowed var attributes = mi.GetCustomAttributes(typeof(RestExtensionMethod), false).OfType <RestExtensionMethod>(); //check to make sure the method was decorated properly if (attributes.Any()) { fromFile = false; var attribute = attributes.First(); allowed = attribute.allowAll; if (!allowed) { //Member Based permissions.. check for group, type and ID... Member currentMem = Member.GetCurrentMember(); //not basic.. and not logged in? - out.. if (currentMem == null) { allowed = false; } else { //do member authentication stuff... allowed = memberAuthentication(attribute, currentMem); } } if (allowed) { this.isAllowed = true; this.alias = extensionAlias; this.assembly = t.Assembly; this.method = t.GetMethod(methodName); this.type = t; this.returnXML = attribute.returnXml; } } } } } } if (allowed) { if (fromFile) { XmlNode extNode = baseDoc.SelectSingleNode("/RestExtensions/ext [@alias='" + extensionAlias + "']"); string asml = extNode.Attributes["assembly"].Value; string assemblyPath = IOHelper.MapPath(string.Format("{0}/{1}.dll", SystemDirectories.Bin, asml.TrimStart('/'))); Assembly returnAssembly = System.Reflection.Assembly.LoadFrom(assemblyPath); string returnTypeName = extNode.Attributes["type"].Value; Type returnType = returnAssembly.GetType(returnTypeName); if (baseExt.Attributes["returnXml"] != null && baseExt.Attributes["returnXml"].Value.ToLower() == "false") { this.returnXML = false; } this.isAllowed = true; this.alias = extensionAlias; this.assembly = returnAssembly; this.method = returnType.GetMethod(methodName); this.type = returnType; } } else { this.isAllowed = false; } }
public InboundSectionReader(TypeFinder typeFinder, EndpointSectionReader endpointSectionReader, ErrorPoliciesSectionReader errorPoliciesSectionReader, InboundSettingsSectionReader inboundSettingsSectionReader) : base(typeFinder, endpointSectionReader) { _errorPoliciesSectionReader = errorPoliciesSectionReader; _inboundSettingsSectionReader = inboundSettingsSectionReader; }
public MvcTypesDemandBuilder(TypeFinder typeFinder) { _typeFinder = typeFinder; }
/// <summary> /// Register all controllers found in the specified Assembly /// </summary> /// <param name="containerBuilder"></param> /// <param name="assembly"></param> /// <param name="typeFinder"></param> /// <returns></returns> public static IContainerBuilder RegisterControllers(this IContainerBuilder containerBuilder, Assembly assembly, TypeFinder typeFinder) { return(containerBuilder.RegisterControllers(new[] { assembly }, typeFinder)); }
public void WithParam() { var methodDefinitions = TypeFinder.Find <SimpleMethod>().FindMethodDefinitions("MethodWithParam", null); Assert.Single(methodDefinitions); }
public IEnumerable <Type> FindClassesOfType(Type type, bool onlyConcreteClasses = true) { return(TypeFinder.FindClassesOfType(type, onlyConcreteClasses)); }
private static void ApplyArrayToProperty(SerializedProperty property, List <Transform> transforms) { if (transforms.Count == 0) { return; } for (var i = 0; i < transforms.Count; i++) { property.InsertArrayElementAtIndex(i); property.GetArrayElementAtIndex(i).objectReferenceValue = transforms[i].gameObject.GetComponent(TypeFinder.GetType("DynamicBoneCollider")); } property.serializedObject.ApplyModifiedPropertiesWithoutUndo(); }
/// <summary> /// Stores the value with the correct data type in Examine /// </summary> /// <param name="serializationDefinition"></param> /// <param name="key"></param> /// <param name="val"></param> /// <param name="d"></param> private void StoreFieldValue(IAttributeSerializationDefinition serializationDefinition, string key, object val, IDictionary <string, ItemField> d) { if (val == null) { return; } switch (serializationDefinition.DataSerializationType) { case DataSerializationTypes.Guid: case DataSerializationTypes.String: case DataSerializationTypes.LongString: case DataSerializationTypes.Boolean: //through the serialization type is string, we still need to detect the 'real' type to see how to convert it to a string. For example, // a date shouldn't just be a ToString() since we want to preserve as much information as possible. var valType = val.GetType(); if (TypeFinder.IsTypeAssignableFrom <DateTime>(valType)) { var dt = (DateTime)val; //convert to the roundtrip date/time format http://msdn.microsoft.com/en-us/library/az4se3k1.aspx#Roundtrip d.Add(key, new ItemField(dt.ToString("o"))); } else if (TypeFinder.IsTypeAssignableFrom <DateTimeOffset>(valType)) { var dt = (DateTimeOffset)val; //convert to the roundtrip date/time format http://msdn.microsoft.com/en-us/library/az4se3k1.aspx#Roundtrip d.Add(key, new ItemField(dt.ToString("o"))); } else { d.Add(key, new ItemField(val.ToString())); } break; case DataSerializationTypes.SmallInt: case DataSerializationTypes.LargeInt: d.Add(key, new ItemField(val) { DataType = FieldDataType.Int }); break; case DataSerializationTypes.Decimal: d.Add(key, new ItemField(val) { DataType = FieldDataType.Double }); break; case DataSerializationTypes.Date: d.Add(key, new ItemField(val) { DataType = FieldDataType.DateTime }); break; case DataSerializationTypes.ByteArray: throw new NotImplementedException(); default: throw new ArgumentOutOfRangeException(); } }
/// <summary> /// Returns the enumerable of all extension method info's in the app domain = USE SPARINGLY!!! /// </summary> /// <returns></returns> /// <remarks> /// We cache this as a sliding 5 minute exiration, in unit tests there's over 1100 methods found, surely that will eat up a bit of memory so we want /// to make sure we give it back. /// </remarks> private static IEnumerable <MethodInfo> GetAllExtensionMethodsInAppDomain(IRuntimeCacheProvider runtimeCacheProvider) { if (runtimeCacheProvider == null) { throw new ArgumentNullException("runtimeCacheProvider"); } return(runtimeCacheProvider.GetCacheItem <MethodInfo[]>(typeof(ExtensionMethodFinder).Name, () => TypeFinder.GetAssembliesWithKnownExclusions() // assemblies that contain extension methods .Where(a => a.IsDefined(typeof(ExtensionAttribute), false)) // types that contain extension methods .SelectMany(a => a.GetTypes() .Where(t => t.IsDefined(typeof(ExtensionAttribute), false) && t.IsSealed && t.IsGenericType == false && t.IsNested == false)) // actual extension methods .SelectMany(t => t.GetMethods(BindingFlags.Static | BindingFlags.Public) .Where(m => m.IsDefined(typeof(ExtensionAttribute), false))) // and also IEnumerable<T> extension methods - because the assembly is excluded .Concat(typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public)) //If we don't do this then we'll be scanning all assemblies each time! .ToArray(), //only cache for 5 minutes timeout: TimeSpan.FromMinutes(5), //each time this is accessed it will be for 5 minutes longer isSliding: true)); }
private void CollectReplacementsForTypes(IEnumerable <TypeDefinition> typeDefinitions, TypeFinder typeFinder, ISymbolTranslator symbolTranslator) { foreach (KeyValuePair <TypeDefinition, CustomAttribute> typePair in FindAnnotated(typeDefinitions, "DecoyAttribute")) { TypeDefinition type = typePair.Key; CustomAttribute decoyAttribute = typePair.Value; string @namespace = GetAttributeFieldValue(decoyAttribute, "namespace", ""); string scrambledName = (string)decoyAttribute.ConstructorArguments[0].Value; string translatedScrambledName = symbolTranslator.TranslateType(scrambledName); TypeDefinition targetType = typeFinder(@namespace, translatedScrambledName); typeReplacements.Add(type.FullName, target.ImportReference(targetType)); if (type.GenericParameters.Count > 0) { Dictionary <string, GenericParameter> genericReplacementsForThisType = new Dictionary <string, GenericParameter>(); for (int i = 0; i < type.GenericParameters.Count; i++) { genericReplacementsForThisType.Add(type.GenericParameters[i].FullName, targetType.GenericParameters[i]); } genericParameterReplacements.Add(type.FullName, genericReplacementsForThisType); } CollectMethodReplacementsInType(type, targetType, symbolTranslator.GetMethodTranslator(scrambledName)); CollectFieldReplacementsInType(type, targetType, symbolTranslator.GetFieldTranslator(scrambledName)); // Recurse for nested types. CollectReplacementsForTypes(type.NestedTypes, (dummy, typeName) => targetType.NestedTypes.First(t => t.Name == typeName), symbolTranslator.GetTranslatorForNestedTypes(scrambledName)); } }
public void TypeFinder_FindInAssemblies_Throws_NotFound(string typeName) { Assert.Throws <TypeNotFoundException>(() => TypeFinder.FindInAssemblies(typeName, assembliesToFindIn)); }
public Type TypeFinder_FindInAssemblies(string typeName) { return(TypeFinder.FindInAssemblies(typeName, assembliesToFindIn)); }
/// <summary>Builds the dependency demands required by this implementation. </summary> /// <param name="builder">The <see cref="IContainerBuilder"/> .</param> /// <param name="builderContext"></param> public void Build(IContainerBuilder builder, IBuilderContext builderContext) { //raise the building event OnContainerBuilding(new ContainerBuilderEventArgs(builder)); //register all of the abstract web types builder.AddDependencyDemandBuilder(new WebTypesDemandBuilder(_httpApp)); var typeFinder = new TypeFinder(); builder.ForInstanceOfType(typeFinder) .ScopedAs.Singleton(); //register the rebel settings builder.ForFactory(x => RebelSettings.GetSettings()) .KnownAsSelf() .ScopedAs.Singleton(); //only have one instance ever //register our MVC types builder.AddDependencyDemandBuilder(new MvcTypesDemandBuilder(typeFinder)); // Register the IRoutableRequestContext builder.For <HttpRequestScopedCache>().KnownAs <AbstractScopedCache>().ScopedAs.Singleton(); builder.For <HttpRuntimeApplicationCache>().KnownAs <AbstractApplicationCache>().ScopedAs.Singleton(); builder.For <HttpRequestScopedFinalizer>().KnownAs <AbstractFinalizer>().ScopedAs.Singleton(); //builder.For<DefaultFrameworkContext>().KnownAs<IFrameworkContext>().ScopedAs.Singleton(); builder.For <RebelApplicationContext>().KnownAs <IRebelApplicationContext>().ScopedAs.Singleton(); builder.For <RoutableRequestContext>().KnownAs <IRoutableRequestContext>().ScopedAs.HttpRequest(); builder.For <DefaultBackOfficeRequestContext>().KnownAs <IBackOfficeRequestContext>().ScopedAs.HttpRequest(); // TODO: Ensure this isn't created manually anywhere but tests, only via a factory: builder.ForType<IRebelRenderModel, RebelRenderContext>().Register().ScopedPerHttpRequest(); builder.For <DefaultRenderModelFactory>().KnownAs <IRenderModelFactory>(). ScopedAs.Singleton(); // Register Hive provider //builder.AddDependencyDemandBuilder(new HiveDemandBuilder()); builder.AddDependencyDemandBuilder(new Hive.DemandBuilders.HiveDemandBuilder()); // Register Persistence provider loader //builder.AddDependencyDemandBuilder(new Framework.Persistence.DependencyManagement.DemandBuilders.LoadFromPersistenceConfig()); builder.AddDependencyDemandBuilder(new Hive.DemandBuilders.LoadFromPersistenceConfig()); // Register Cms bootstrapper // TODO: Split RebelContainerBuilder between Cms and Frontend variants / needs builder.For <CmsBootstrapper>().KnownAsSelf(); // Register Frontend bootstrapper builder.ForFactory( x => new RenderBootstrapper( x.Resolve <IRebelApplicationContext>(), x.Resolve <IRouteHandler>(RenderRouteHandler.SingletonServiceName), x.Resolve <IRenderModelFactory>()) ) .KnownAsSelf(); //register all component areas, loop through all found package folders //TODO: All other places querying for packages use the NuGet IO FileManager stuff, not the standard .Net IO classes var pluginFolder = new DirectoryInfo(_httpApp.Server.MapPath(_settings.PluginConfig.PluginsPath)); foreach (var package in pluginFolder.GetDirectories(PluginManager.PackagesFolderName) .SelectMany(x => x.GetDirectories() .Where(PluginManager.IsPackagePluginFolder))) { //register an area for this package builder.For <PackageAreaRegistration>() .KnownAsSelf() .WithNamedParam("packageFolder", package); } //register the RoutingEngine builder .For <DefaultRoutingEngine>() .KnownAs <IRoutingEngine>() .ScopedAs.HttpRequest(); //register the package context builder .ForFactory(x => new DefaultPackageContext(x.Resolve <RebelSettings>(), HostingEnvironment.MapPath)) //.For<DefaultPackageContext>() .KnownAs <IPackageContext>() .ScopedAs.Singleton(); //register the PropertyEditorFactory builder.For <PropertyEditorFactory>() .KnownAs <IPropertyEditorFactory>() .ScopedAs.Singleton(); //register the ParameterEditorFactory builder.For <ParameterEditorFactory>() .KnownAs <IParameterEditorFactory>() .ScopedAs.Singleton(); //register the SecurityService builder.ForFactory( x => new SecurityService( x.Resolve <IMembershipService <User> >(), x.Resolve <IMembershipService <Member> >(), x.Resolve <IPermissionsService>(), x.Resolve <IPublicAccessService>())) .KnownAs <ISecurityService>(); //register the MembershipService builder.ForFactory( x => { var frameworkContext = x.Resolve <IFrameworkContext>(); var hiveManager = x.Resolve <IHiveManager>(); MembershipProvider membershipProvider = Membership.Providers["UsersMembershipProvider"]; return(new MembershipService <User, UserProfile>( frameworkContext, hiveManager, "security://user-profiles", "security://user-groups", FixedHiveIds.UserProfileVirtualRoot, membershipProvider, _settings.MembershipProviders)); }) .KnownAs <IMembershipService <User> >() .ScopedAs.Singleton(); builder.ForFactory( x => new MembershipService <Member, MemberProfile>( x.Resolve <IFrameworkContext>(), x.Resolve <IHiveManager>(), "security://member-profiles", "security://member-groups", FixedHiveIds.MemberProfileVirtualRoot, Membership.Providers["MembersMembershipProvider"], _settings.MembershipProviders) ) .KnownAs <IMembershipService <Member> >() .ScopedAs.Singleton(); builder.ForFactory( x => new PermissionsService( x.Resolve <IHiveManager>(), x.Resolve <IEnumerable <Lazy <Permission, PermissionMetadata> > >(), x.Resolve <IMembershipService <User> >())) .KnownAs <IPermissionsService>() .ScopedAs.Singleton(); builder.ForFactory( x => new PublicAccessService( x.Resolve <IHiveManager>(), x.Resolve <IMembershipService <Member> >(), x.Resolve <IFrameworkContext>())) .KnownAs <IPublicAccessService>() .ScopedAs.Singleton(); //register the CmsAttributeTypeRegistry builder.For <CmsAttributeTypeRegistry>() .KnownAs <IAttributeTypeRegistry>() .ScopedAs.Singleton(); //component registration _componentRegistrar.RegisterTasks(builder, typeFinder); _componentRegistrar.RegisterTreeControllers(builder, typeFinder); _componentRegistrar.RegisterPropertyEditors(builder, typeFinder); _componentRegistrar.RegisterParameterEditors(builder, typeFinder); _componentRegistrar.RegisterEditorControllers(builder, typeFinder); _componentRegistrar.RegisterMenuItems(builder, typeFinder); _componentRegistrar.RegisterSurfaceControllers(builder, typeFinder); _componentRegistrar.RegisterDashboardFilters(builder, typeFinder); _componentRegistrar.RegisterDashboardMatchRules(builder, typeFinder); _componentRegistrar.RegisterPermissions(builder, typeFinder); _componentRegistrar.RegisterMacroEngines(builder, typeFinder); //register the registrations builder.For <ComponentRegistrations>().KnownAsSelf(); //register task manager builder.For <ApplicationTaskManager>().KnownAsSelf().ScopedAs.Singleton(); //register our model mappings and resolvers builder.AddDependencyDemandBuilder(new ModelMappingsDemandBuilder()); //TODO: More stuff should happen with the TextManager here (e.g. db access and whatnot) //The user may later override settings, most importantly the LocalizationConfig.CurrentTextManager delegate to implement different environments //The text manager is assumed to be set up by the framework var textManager = LocalizationConfig.TextManager; LocalizationWebConfig.ApplyDefaults <TWebApp>(textManager, overridesPath: "~/App_Data/Rebel/LocalizationEntries.xml"); LocalizationWebConfig.SetupMvcDefaults(setupMetadata: false); //The name of the assembly that contains common texts textManager.FallbackNamespaces.Add("Rebel.Cms.Web"); OnContainerBuildingComplete(new ContainerBuilderEventArgs(builder)); }
public override object ProvideValue(IServiceProvider serviceProvider) { var targetProvider = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget; if (targetProvider == null) { return(null); } var target = targetProvider.TargetObject as FrameworkElement; if (target == null) { return(null); } Type handlerType = null; var eventInfo = targetProvider.TargetProperty as EventInfo; if (eventInfo != null) { handlerType = eventInfo.EventHandlerType; } else { var method = targetProvider.TargetProperty as MethodInfo; handlerType = method.GetParameters()[1].ParameterType; } Action <object, object> invoke = null; if (string.IsNullOrEmpty(_bridge)) { invoke = (_, __) => target.DataContext.GetType().GetMethod(_path).Invoke(target.DataContext, new object[0]); } else { var items = _bridge.Split('.'); if (items.Length < 2) { return(null); } var bridgeType = TypeFinder.GetType(string.Join(".", items.Take(items.Length - 1))); if (bridgeType == null) { return(null); } var methodInfo = bridgeType.GetMethod(items[items.Length - 1]); var args = methodInfo.GetParameters(); if (args.Length != 3 && typeof(Delegate).IsAssignableFrom(args[2].ParameterType)) { return(null); } invoke = (o, e) => methodInfo.Invoke(null, new object[] { o, e, target.DataContext.GetType().GetMethod(_path).CreateDelegate(args[2].ParameterType, target.DataContext) }); } var arguments = handlerType.GetMethod("Invoke").GetParameters().Select(e => e.ParameterType).ToArray(); var conType = typeof(Listener <,>).MakeGenericType(arguments[0], arguments[1]); return(conType.GetMethod("Connect").Invoke(null, new object[] { handlerType, invoke })); }
public static void UseMoz(this IApplicationBuilder application, IWebHostEnvironment env) { var configuration = application.ApplicationServices.GetService(typeof(IConfiguration)) as IConfiguration; var options = (application.ApplicationServices.GetService(typeof(IOptions <AppConfig>)) as IOptions <AppConfig>)?.Value; if (options == null) { throw new ArgumentNullException(nameof(options)); } if (env.IsDevelopment()) { application.UseDeveloperExceptionPage(); } application.UseMiddleware <ErrorHandlingMiddleware>(); application.UseStatusCodePages(async context => { var registerType = options.StatusCodePageHandlerType; if (registerType != null && application.ApplicationServices.GetService(registerType) is IStatusCodePageHandler handler) { await handler.Process(context); } else { if (application.ApplicationServices.GetService(typeof(MozStatusCodePageHandler)) is IStatusCodePageHandler mozHandler) { await mozHandler.Process(context); } } }); application.UseMiddleware <JwtInHeaderMiddleware>(); //定时任务 if (DbFactory.CheckInstalled(options)) { var taskScheduleManager = application.ApplicationServices.GetService(typeof(ITaskScheduleManager)) as ITaskScheduleManager; taskScheduleManager?.Init(); } application.UseMozStaticFiles(); application.UseAuthentication(); application.UseSession(); application.UseRouting(); application.UseAuthorization(); //获取所有的 IAppStartup,执行各个模块的启动类 var startupConfigurations = TypeFinder.FindClassesOfType <IAppStartup>(); var instances = startupConfigurations .Select(startup => (IAppStartup)Activator.CreateInstance(startup.Type)) .OrderBy(startup => startup?.Order); foreach (var instance in instances) { instance.Configure(application, configuration, env, options); } application.UseEndpoints(endpoints => { endpoints.MapControllerRoute("area", "{area:exists}/{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); application.Run(context => { context.Response.StatusCode = 404; return(Task.CompletedTask); }); }
private void CreatePresetLayout() { EditorContent.Label("Create DynamicBone preset from existing GameObject tree."); EditorGUIUtility.labelWidth = 200; _gameObject = EditorContent.ObjectPicker<GameObject>("Root GameObject", _gameObject, true); if (ReferenceEquals(_gameObject, null)) return; var components = new List<Component>(); components.AddRange(_gameObject.GetComponentsInChildren(TypeFinder.GetType(DynamicBoneFullName))); components.AddRange(_gameObject.GetComponentsInChildren(TypeFinder.GetType(DynamicBoneColliderFullName))); components.AddRange(_gameObject.GetComponentsInChildren(TypeFinder.GetType(DynamicBonePlaneColliderFullName))); if (components.Count == 0) return; // differ { var added = components.Where(w => !_enabledComponents.ContainsKey(w.GetInstanceID())).ToList(); var removed = _enabledComponents.Where(w => ReferenceEquals(components.SingleOrDefault(v => v.GetInstanceID() == w.Key), null)).ToList(); foreach (var component in added) _enabledComponents.Add(component.GetInstanceID(), false); foreach (var instanceId in removed.Select(w => w.Key)) _enabledComponents.Remove(instanceId); } EditorContent.Space(); EditorContent.Label("Enabled Components:"); foreach (var component in components) { var instanceId = component.GetInstanceID(); _enabledComponents[instanceId] = EditorContent.Checkbox(component.ToString(), _enabledComponents[instanceId]); } if (_enabledComponents.Any(w => w.Value)) { EditorContent.Space(); EditorContent.Label("Naming Conventions:"); } foreach (var component in _enabledComponents.Where(w => w.Value).Select(w => components.Single(v => v.GetInstanceID() == w.Key))) { var convention = PropertyTransformer.TransformToStringPath(component); var instance = _configurations.SingleOrDefault(w => w.OriginalInstanceId == component.GetInstanceID()); if (ReferenceEquals(instance, null)) { instance = new DynamicBoneConfiguration(); instance.Name = instance.NamingConvention = convention; instance.Component = component; instance.OriginalInstanceId = component.GetInstanceID(); _configurations.Add(instance); } instance.NamingConvention = EditorContent.TextField(component.ToString(), instance.NamingConvention); } // cleanup instances foreach (var configuration in _enabledComponents.Where(w => !w.Value).Select(w => _configurations.SingleOrDefault(v => w.Key == v.OriginalInstanceId)).Where(w => !ReferenceEquals(w, null)).ToList()) _configurations.Remove(configuration); EditorContent.Space(); EditorContent.Label("DynamicBone Preset Manager convert hierarchy tree to the below name:"); EditorContent.Label("Avatar → Armature → Hips → ... to Avatar/Armature/Hips/..."); EditorContent.Label("If you want to preserve the tree structure, use `/` and `[^/]*?` in the naming convention."); using (EditorContent.DisabledGroup(_configurations.Count == 0)) _name = EditorContent.TextField("Preset Name", _name); using (EditorContent.DisabledGroup(string.IsNullOrEmpty(_name) || _configurations.Count == 0)) if (EditorContent.Button("Create DynamicBone Preset")) CreatePreset(); }
public static ObjectIdentifier CreateObjectIdentifier(long id, String assemblyQualifiedName, TypeFinder typeFinder) { CreateObjectIdentifierDelegate create; if (creationMethods.TryGetValue(assemblyQualifiedName, out create)) { return(create(id, assemblyQualifiedName, typeFinder)); } Type type = typeFinder.findType(assemblyQualifiedName); return(new ObjectIdentifier(id, null, type)); }
public IEnumerable <Type> FindClassesOfType <T>(Assembly assembly, bool onlyConcreteClasses = true) { return(TypeFinder.FindClassesOfType <T>(new List <Assembly> { assembly }, onlyConcreteClasses)); }
public void MatchTypeTest() { TypeFinder typeFinder = new TypeFinder (); typeFinder.findTypeFor ("var"); }
public TypeFinderTest() { var loggerFactory = new ServiceCollection().AddLogging().BuildServiceProvider().GetService <ILoggerFactory>(); _typeFinder = new TypeFinder(loggerFactory); }
public void TypeFinder_is_able_to_find_IEntityModelBuilder_from_dlls() { var consumers = TypeFinder.Find(typeof(IEntityModelBuilder)); Assert.NotEmpty(consumers); }
/// <summary> /// Register all controllers found in the specified Assembly /// </summary> /// <param name="containerBuilder"></param> /// <param name="assembly"></param> /// <param name="typeFinder"></param> /// <returns></returns> public static IContainerBuilder RegisterControllers(this IContainerBuilder containerBuilder, Assembly assembly, TypeFinder typeFinder) { return containerBuilder.RegisterControllers(new[] { assembly }, typeFinder); }
public void TypeFind_is_able_to_only_load_dlls_that_match_pattern() { Assert.False(TypeFinder.IsDllMatch("xunit.runner.visualstudio.dotnetcore.testadapter.dll")); Assert.True(TypeFinder.IsDllMatch("Fan.Blog.dll")); }
public void Setup() { _typeFinder = new TypeFinder(new MyAssemblyFinder()); _module = new AbpAutoMapperModule(_typeFinder); _module.PostInitialize(); }
public void Find_Class_Of_Type_With_Attribute() { var typesFound = TypeFinder.FindClassesOfTypeWithAttribute <TestEditor, MyTestAttribute>(_assemblies); Assert.AreEqual(2, typesFound.Count()); }
public void NewFinderTest() { var finder = new TypeFinder(null); }
private bool IsPluginAssembly(string assemblyPath) { using (Stream stream = File.OpenRead(assemblyPath)) using (var reader = new PEReader(stream)) { if (!reader.HasMetadata) { return(false); } if (_options.TypeFinderCriterias?.Any() != true) { // If there are no resolvers, assume that each DLL is a plugin return(true); } var runtimeDirectory = RuntimeEnvironment.GetRuntimeDirectory(); var runtimeAssemblies = Directory.GetFiles(runtimeDirectory, "*.dll"); var paths = new List <string>(runtimeAssemblies) { assemblyPath }; if (_options.PluginLoadContextOptions.AdditionalRuntimePaths?.Any() == true) { foreach (var additionalRuntimePath in _options.PluginLoadContextOptions.AdditionalRuntimePaths) { var dlls = Directory.GetFiles(additionalRuntimePath, "*.dll"); paths.AddRange(dlls); } } if (_options.PluginLoadContextOptions.UseHostApplicationAssemblies == UseHostApplicationAssembliesEnum.Always) { var hostApplicationPath = Environment.CurrentDirectory; var hostDlls = Directory.GetFiles(hostApplicationPath, "*.dll", SearchOption.AllDirectories); paths.AddRange(hostDlls); AddSharedFrameworkDlls(hostApplicationPath, runtimeDirectory, paths); } else if (_options.PluginLoadContextOptions.UseHostApplicationAssemblies == UseHostApplicationAssembliesEnum.Never) { var pluginPath = Path.GetDirectoryName(assemblyPath); var dllsInPluginPath = Directory.GetFiles(pluginPath, "*.dll", SearchOption.AllDirectories); paths.AddRange(dllsInPluginPath); } else if (_options.PluginLoadContextOptions.UseHostApplicationAssemblies == UseHostApplicationAssembliesEnum.Selected) { foreach (var hostApplicationAssembly in _options.PluginLoadContextOptions.HostApplicationAssemblies) { var assembly = Assembly.Load(hostApplicationAssembly); paths.Add(assembly.Location); } } paths = paths.Distinct().ToList(); var resolver = new PathAssemblyResolver(paths); // We use the metadata (readonly) versions of the assemblies before loading them using (var metadataContext = new MetadataLoadContext(resolver)) { var metadataPluginLoadContext = new MetadataTypeFindingContext(metadataContext); var readonlyAssembly = metadataContext.LoadFromAssemblyPath(assemblyPath); var typeFinder = new TypeFinder(); foreach (var finderCriteria in _options.TypeFinderCriterias) { var typesFound = typeFinder.Find(finderCriteria.Value, readonlyAssembly, metadataPluginLoadContext); if (typesFound?.Any() == true) { return(true); } } } } return(false); }
public void TestFixtureSetup() { typeFinder = new TypeFinder(new MyAssemblyFinder()); module = new AbpAutoMapperModule(typeFinder); module.PostInitialize(); }
public TypeFinderTest() { WhenCalling <IAssemblyLocator>(x => x.GetAssemblies()).Return(new[] { Assembly.GetExecutingAssembly() }); typeFinder = new TypeFinder <TEvent>(); }
public void Find_Classes_With_Attribute() { var typesFound = TypeFinder.FindClassesWithAttribute <RestExtensionAttribute>(_assemblies); Assert.AreEqual(1, typesFound.Count()); }
internal int FindOrAddAuto(Type type, bool demand, bool addWithContractOnly, bool addEvenIfAutoDisabled) { TypeFinder predicate = new TypeFinder(type); int key = types.IndexOf(predicate); MetaType metaType; if (key >= 0 && (metaType = ((MetaType)types[key])).Pending) { WaitOnLock(metaType); } if (key < 0) { // check for proxy types Type underlyingType = ResolveProxies(type); if (underlyingType != null) { predicate = new TypeFinder(underlyingType); key = types.IndexOf(predicate); type = underlyingType; // if new added, make it reflect the underlying type } } if (key < 0) { int opaqueToken = 0; try { TakeLock(ref opaqueToken); // try to recognise a few familiar patterns... if ((metaType = RecogniseCommonTypes(type)) == null) { // otherwise, check if it is a contract MetaType.AttributeFamily family = MetaType.GetContractFamily(type, null); if (family == MetaType.AttributeFamily.AutoTuple) addEvenIfAutoDisabled = true; // always add basic tuples, such as KeyValuePair bool shouldAdd = AutoAddMissingTypes || addEvenIfAutoDisabled; if (!shouldAdd || ( !type.IsEnum && addWithContractOnly && family == MetaType.AttributeFamily.None) ) { if (demand) ThrowUnexpectedType(type); return key; } metaType = Create(type); } metaType.Pending = true; bool weAdded = false; // double-checked int winner = types.IndexOf(predicate); if (winner < 0) { ThrowIfFrozen(); key = types.Add(metaType); weAdded = true; } else { key = winner; } if (weAdded) { metaType.ApplyDefaultBehaviour(); metaType.Pending = false; } } finally { ReleaseLock(opaqueToken); } } return key; }
public OutboundSectionReader(TypeFinder typeFinder, EndpointSectionReader endpointSectionReader) : base(typeFinder, endpointSectionReader) { _typeFinder = typeFinder; }