private static IEnumerable<Type> FilterTypesInAssemblies(IBuildManager buildManager, Predicate<Type> predicate) { // Go through all assemblies referenced by the application and search for types matching a predicate IEnumerable<Type> typesSoFar = Type.EmptyTypes; ICollection assemblies = buildManager.GetReferencedAssemblies(); foreach (Assembly assembly in assemblies) { Type[] typesInAsm; try { try { typesInAsm = assembly.GetExportedTypes(); } catch (NotImplementedException) { typesInAsm = assembly.GetTypes(); } } catch (ReflectionTypeLoadException ex) { typesInAsm = ex.Types; } typesSoFar = typesSoFar.Concat(typesInAsm); } return typesSoFar.Where(type => TypeIsPublicClass(type) && predicate(type)); }
internal static void RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, object state) { List<Type> areaRegistrationTypes = TypeHelpers.FilterTypesInAssemblies(buildManager, IsAreaRegistrationType); foreach (Type areaRegistrationType in areaRegistrationTypes) { AreaRegistration registration = (AreaRegistration)Activator.CreateInstance(areaRegistrationType); registration.CreateContextAndRegister(routes, state); } }
protected BuildManager(IBuildManager buildManager) { if (buildManager == null) throw new ArgumentNullException("buildManager"); _buildManager = buildManager; }
/// <summary> /// 获取当前项目中满足指定条件的类型集合 /// 首先从缓存文件中查询,若无缓存则遍历所有引用的程序集,并最后保存到缓存文件中 /// </summary> /// <param name="cacheName">缓存文件名</param> /// <param name="predicate">类型匹配的规则(一个委托)</param> /// <param name="buildManager">操作类型缓存的组件</param> /// <returns>匹配的类型集合</returns> public static List<Type> GetFilteredTypesFromAssemblies(string cacheName, Predicate<Type> predicate, IBuildManager buildManager) { //类型缓存序列化器 TypeCacheSerializer serializer = new TypeCacheSerializer(); //首先从本地磁盘读取缓存路由的缓存文件,获取缓存的区域路由的类型集合 // first, try reading from the cache on disk List<Type> matchingTypes = ReadTypesFromCache(cacheName, predicate, buildManager, serializer); if (matchingTypes != null) { return matchingTypes; } //如果没有读取到路由的缓存信息,则枚举每一个程序集寻找匹配的类型 //即寻找继承了AreaRegistration的类,并且包含无参构造函数 // if reading from the cache failed, enumerate over every assembly looking for a matching type matchingTypes = FilterTypesInAssemblies(buildManager, predicate).ToList(); // 将类型信息保存到XML文件中作为缓存 // C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\985b57d0\89016edd\UserCache\MVC-AreaRegistrationTypeCache.xml // finally, save the cache back to disk SaveTypesToCache(cacheName, matchingTypes, buildManager, serializer); return matchingTypes; }
internal static void RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, object state) { List<Type> areaRegistrationTypes = TypeCacheUtil.GetFilteredTypesFromAssemblies(_typeCacheName, IsAreaRegistrationType, buildManager); foreach (Type areaRegistrationType in areaRegistrationTypes) { AreaRegistration registration = (AreaRegistration)Activator.CreateInstance(areaRegistrationType); registration.CreateContextAndRegister(routes, state); } }
public ValidateEnvironmentService(IDeployRequestManager deployRequestManager, IBuildManager buildManager, IProjectManager projectManager, IDeploymentValidator validator) { _deployRequestManager = DIHelper.VerifyParameter(deployRequestManager); _buildManager = DIHelper.VerifyParameter(buildManager); _projectManager = DIHelper.VerifyParameter(projectManager); _validator = DIHelper.VerifyParameter(validator); }
///<summary> /// Creates a new instance of the ConventionBasedPresenterDiscoveryStrategy class. ///</summary> ///<param name="buildManager">The IBuildManager implementation to use.</param> public ConventionBasedPresenterDiscoveryStrategy(IBuildManager buildManager) { if (buildManager == null) throw new ArgumentNullException("buildManager"); this.buildManager = buildManager; }
public ReferencedExtensionLoader(IDependenciesFolder dependenciesFolder, IVirtualPathProvider virtualPathProvider, IBuildManager buildManager) : base(dependenciesFolder) { _virtualPathProvider = virtualPathProvider; _buildManager = buildManager; Logger = NullLogger.Instance; }
public WrenchProject (SourceSettings ss, IGraphState graph, ActionLog log) { this.ss = ss; this.log = log; this.graph = graph; this.manager = WrenchOperations.MakeManager (this); }
public static IBuildManager GetBuildManager() { if (_buildManager == null) { _buildManager = new BuildManager(_serviceProvider); } return _buildManager; }
public BuildPurger(ISystemSettings systemSettings, IBuildManager buildManager, Logger logger, IDIFactory diFactory, IBuildPurgeRuleManager buildPurgeRuleManager) { _systemSettings = DIHelper.VerifyParameter(systemSettings); _buildManager = DIHelper.VerifyParameter(buildManager); _logger = DIHelper.VerifyParameter(logger); _diFactory = DIHelper.VerifyParameter(diFactory); _buildPurgeRuleManager = DIHelper.VerifyParameter(buildPurgeRuleManager); }
protected ThemeableBuildManagerViewEngine(IBuildManager buildManager) { if (buildManager == null) { throw new ArgumentNullException("buildManager"); } BuildManager = buildManager; }
// Adds Parameter for unit tests internal static bool StartCore(IFileSystem fileSystem, string appDomainAppPath, string binDirectory, NameValueCollection appSettings, IEnumerable<AssemblyName> loadedAssemblies, IBuildManager buildManager, Action<Version> loadWebPages, Action registerForChangeNotification, Func<string, AssemblyName> getAssemblyNameThunk = null) { if (WebPagesDeployment.IsExplicitlyDisabled(appSettings)) { // If WebPages is explicitly disabled, exit. Debug.WriteLine("WebPages Bootstrapper v{0}: not loading WebPages since it is disabled", AssemblyUtils.ThisAssemblyName.Version); return false; } Version maxWebPagesVersion = AssemblyUtils.GetMaxWebPagesVersion(loadedAssemblies); Debug.Assert(maxWebPagesVersion != null, "Function must return some max value."); if (AssemblyUtils.ThisAssemblyName.Version != maxWebPagesVersion) { // Always let the highest version determine what needs to be done. This would make future proofing simpler. Debug.WriteLine("WebPages Bootstrapper v{0}: Higher version v{1} is available.", AssemblyUtils.ThisAssemblyName.Version, maxWebPagesVersion); return false; } var webPagesEnabled = WebPagesDeployment.IsEnabled(fileSystem, appDomainAppPath, appSettings); Version binVersion = AssemblyUtils.GetVersionFromBin(binDirectory, fileSystem, getAssemblyNameThunk); Version version = WebPagesDeployment.GetVersionInternal(appSettings, binVersion, defaultVersion: maxWebPagesVersion); // Asserts to ensure unit tests are set up correctly. So essentially, we're unit testing the unit tests. Debug.Assert(version != null, "GetVersion always returns a version"); Debug.Assert(binVersion == null || binVersion <= maxWebPagesVersion, "binVersion cannot be higher than max version"); if ((binVersion != null) && (binVersion != version)) { // Determine if there's a version conflict. A conflict could occur if there's a version specified in the bin which is different from the version specified in the // config that is different. throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, ConfigurationResources.WebPagesVersionConflict, version, binVersion)); } else if (binVersion != null) { // The rest of the code is only meant to be executed if we are executing from the GAC. // If a version is bin deployed, we don't need to do anything special to bootstrap. return false; } else if (!webPagesEnabled) { Debug.WriteLine("WebPages Bootstrapper v{0}: WebPages not enabled, registering for change notifications", AssemblyUtils.ThisAssemblyName.Version); // Register for change notifications under the application root registerForChangeNotification(); return false; } else if (!AssemblyUtils.IsVersionAvailable(loadedAssemblies, version)) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, ConfigurationResources.WebPagesVersionNotFound, version, AssemblyUtils.ThisAssemblyName.Version)); } Debug.WriteLine("WebPages Bootstrapper v{0}: loading version {1}, loading WebPages", AssemblyUtils.ThisAssemblyName.Version, version); // If the version the application was compiled earlier was different, invalidate compilation results by adding a file to the bin. InvalidateCompilationResultsIfVersionChanged(buildManager, fileSystem, binDirectory, version); loadWebPages(version); return true; }
/// <summary> /// Initializes a new instance of the <see cref="BuildManagerTypeCache"/> class. /// </summary> /// <param name="buildManager">The build manager.</param> /// <param name="serializer">The serializer.</param> public BuildManagerTypeCache(IBuildManager buildManager, ITypeCacheSerializer serializer) { if (buildManager == null) throw new ArgumentNullException("buildManager"); if (serializer == null) throw new ArgumentNullException("serializer"); BuildManager = buildManager; Serializer = serializer; }
public WebFormRoutingHandler(string virtualPath, bool validateAccessRights, IBuildManager buildManager) : base() { Precondition.Defined(virtualPath, () => Error.ArgumentNull("virtualPath")); _virtualPath = virtualPath; _validateAccessRights = validateAccessRights; _buildManager = buildManager; }
protected BuildManagerCompiledView(string viewPath, IBuildManager buildManager, IViewActivator activator) { Precondition.Defined(viewPath, () => Error.ArgumentNull("viewPath")); Precondition.Require(buildManager, () => Error.ArgumentNull("buildManager")); Precondition.Require(activator, () => Error.ArgumentNull("activator")); _viewPath = viewPath; _buildManager = buildManager; _activator = activator; }
public HttpControllerTypeCache(HttpConfiguration configuration) { if (configuration == null) { throw Error.ArgumentNull("configuration"); } _configuration = configuration; _buildManager = _configuration.ServiceResolver.GetBuildManager(); _cache = InitializeCache(); }
//读取全部是从缓存文件中读,若为空先写入缓存,再读取。(基本上所有的涉及缓存的操作都是这么个套路) public static IEnumerable<Type> GetFilteredTypesFromAssemblies(string cacheName,IBuildManager buildManager,Predicate<Type> predict) { TypeCacheSerializer serializer = new TypeCacheSerializer(); IEnumerable<Type> matchingTypes = ReadTypesFromCache(cacheName,predict,buildManager,serializer); if (matchingTypes!=null) { return matchingTypes; } matchingTypes = FilterTypesInAssemblies(buildManager,predict); SaveTypesToCache(cacheName,matchingTypes,buildManager,serializer); return matchingTypes; }
//时时刻刻能感受到,是我要怎么写代码,而不是我只能如何写代码,而是我真正驾驭着代码。 private static IEnumerable<Type> FilterTypesInAssemblies(IBuildManager buildManager,Predicate<Type> predict) { //遍历所有的引用的assembly去找到匹配predict的Type IEnumerable<Type> typesSoFar = Type.EmptyTypes; ICollection assemblies = buildManager.GetReferencedAssemblies(); foreach (Assembly assembly in assemblies) { Type[] typesInAsm = assembly.GetTypes(); typesSoFar = typesSoFar.Concat(typesInAsm); //这么写有什么必要吗??? } return typesSoFar.Where(type=>predict(type)); }
internal static void SaveTypesToCache(string cacheName, IList<Type> matchingTypes, IBuildManager buildManager, TypeCacheSerializer serializer) { try { Stream stream = buildManager.CreateCachedFile(cacheName); if (stream != null) { using (StreamWriter writer = new StreamWriter(stream)) { serializer.SerializeTypes(matchingTypes, writer); } } } catch { } }
public DefaultRazorCompilationEvents( IDependenciesFolder dependenciesFolder, IExtensionDependenciesManager extensionDependenciesManager, IBuildManager buildManager, IEnumerable<IExtensionLoader> loaders, IAssemblyLoader assemblyLoader) { _dependenciesFolder = dependenciesFolder; _extensionDependenciesManager = extensionDependenciesManager; _buildManager = buildManager; _loaders = loaders; _assemblyLoader = assemblyLoader; Logger = NullLogger.Instance; }
private static Dictionary<string, Type> BuildTypeCache(IBuildManager buildManager) { Dictionary<string, Type> cache = new Dictionary<string, Type>( StringComparer.OrdinalIgnoreCase); foreach (Type type in DiscoverControllerTypes(buildManager)) { if (cache.ContainsKey(type.Name)) throw Error.DuplicateControllerName(type.Name); cache.Add(type.Name, type); } return cache; }
/// <summary> /// 注册区域路由 /// </summary> /// <param name="routes">全局路由表</param> /// <param name="buildManager">管理 ASP.NET 应用程序编译的组件,用于获取类型缓存</param> /// <param name="state"></param> internal static void RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, object state) { // 获取所有区域类型 // 1、尝试从缓存文件中获取 // 2、所无缓存则遍历引用的所有程序集查找匹配的类型并写入缓存文件 List<Type> areaRegistrationTypes = TypeCacheUtil.GetFilteredTypesFromAssemblies(TypeCacheName, IsAreaRegistrationType, buildManager); // 遍历所有区域类型 分别创建对象的实例,将其路由规则注册到路由表中 foreach (Type areaRegistrationType in areaRegistrationTypes) { AreaRegistration registration = (AreaRegistration)Activator.CreateInstance(areaRegistrationType); registration.CreateContextAndRegister(routes, state); } }
internal static PresenterDiscoveryResult GetBinding(IView viewInstance, IBuildManager buildManager, IEnumerable<string> viewInstanceSuffixes, IEnumerable<string> presenterTypeFullNameFormats) { var viewType = viewInstance.GetType(); var searchResult = viewTypeToPresenterTypeCache.GetOrCreateValue(viewType.TypeHandle, () => PerformSearch(viewInstance, viewInstanceSuffixes, presenterTypeFullNameFormats, buildManager)); return new PresenterDiscoveryResult( new[] {viewInstance}, searchResult.Message, searchResult.PresenterType == null ? new PresenterBinding[0] : new [] { new PresenterBinding(searchResult.PresenterType, viewType, BindingMode.Default, new[] { viewInstance }) } ); }
public void EnsureInitialized(IBuildManager buildManager) { if (_cache == null) { lock (_lockObj) { if (_cache == null) { List<Type> controllerTypes = GetAllControllerTypes(buildManager); var groupedByName = controllerTypes.GroupBy( t => t.Name.Substring(0, t.Name.Length - "Controller".Length), StringComparer.OrdinalIgnoreCase); _cache = groupedByName.ToDictionary( g => g.Key, g => g.ToLookup(t => t.Namespace ?? String.Empty, StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase); } } } }
public ControllerTypeResolverFactory( IEnumerable<string> areaNamespacesToIgnore, IControllerBuilder controllerBuilder, IBuildManager buildManager ) { if (areaNamespacesToIgnore == null) throw new ArgumentNullException("areaNamespacesToIgnore"); if (controllerBuilder == null) throw new ArgumentNullException("controllerBuilder"); if (buildManager == null) throw new ArgumentNullException("buildManager"); this.areaNamespacesToIgnore = areaNamespacesToIgnore; this.controllerBuilder = controllerBuilder; this.buildManager = buildManager; }
private static List<Type> GetAllControllerTypes(IBuildManager buildManager) { // Go through all assemblies referenced by the application and search for // controllers and controller factories. List<Type> controllerTypes = new List<Type>(); ICollection assemblies = buildManager.GetReferencedAssemblies(); foreach (Assembly assembly in assemblies) { Type[] typesInAsm; try { typesInAsm = assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { typesInAsm = ex.Types; } controllerTypes.AddRange(typesInAsm.Where(IsControllerType)); } return controllerTypes; }
public static List<Type> GetFilteredTypesFromAssemblies(string cacheName, Predicate<Type> predicate, IBuildManager buildManager) { TypeCacheSerializer serializer = new TypeCacheSerializer(); // first, try reading from the cache on disk List<Type> matchingTypes = ReadTypesFromCache(cacheName, predicate, buildManager, serializer); if (matchingTypes != null) { return matchingTypes; } // if reading from the cache failed, enumerate over every assembly looking for a matching type matchingTypes = FilterTypesInAssemblies(buildManager, predicate).ToList(); // finally, save the cache back to disk SaveTypesToCache(cacheName, matchingTypes, buildManager, serializer); return matchingTypes; }
internal static List<Type> ReadTypesFromCache(string cacheName, Predicate<Type> predicate, IBuildManager buildManager, TypeCacheSerializer serializer) { try { Stream stream = buildManager.ReadCachedFile(cacheName); if (stream != null) { using (StreamReader reader = new StreamReader(stream)) { List<Type> deserializedTypes = serializer.DeserializeTypes(reader); if (deserializedTypes != null && deserializedTypes.All(type => TypeIsPublicClass(type) && predicate(type))) { // If all read types still match the predicate, success! return deserializedTypes; } } } } catch { } return null; }
private static IEnumerable<Type> DiscoverControllerTypes(IBuildManager buildManager) { List<Type> types = new List<Type>(); foreach (Assembly assembly in buildManager.GetReferencedAssemblies()) { Type[] typesInAsm; try { typesInAsm = assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { typesInAsm = ex.Types; } types.AddRange(typesInAsm.Where(IsController)); } return types; }