示例#1
0
        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);
        }
示例#2
0
        /// <summary>
        /// WebPages stores the version to be compiled against in AppSettings as &gt;add key="webpages:version" value="1.0" /&lt;.
        /// Changing values AppSettings does not cause recompilation therefore we could run into a state where we have files compiled against v1 but the application is
        /// currently v2.
        /// </summary>
        private static void InvalidateCompilationResultsIfVersionChanged(
            IBuildManager buildManager,
            IFileSystem fileSystem,
            string binDirectory,
            Version currentVersion
            )
        {
            Version previousVersion = WebPagesDeployment.GetPreviousRuntimeVersion(buildManager);

            // Persist the current version number in BuildManager's cached file
            WebPagesDeployment.PersistRuntimeVersion(buildManager, currentVersion);

            if (previousVersion == null)
            {
                // Do nothing.
            }
            else if (previousVersion != currentVersion)
            {
                // If the previous runtime version is different, perturb the bin directory so that it forces recompilation.
                WebPagesDeployment.ForceRecompile(fileSystem, binDirectory);
                var httpCompileException = new HttpCompileException(
                    ConfigurationResources.WebPagesVersionChanges
                    );
                // Indicator for tooling
                httpCompileException.Data[ToolingIndicatorKey] = true;
                throw httpCompileException;
            }
        }
示例#3
0
 /// <summary>
 /// 將 _cache filed 初始話
 /// 載入關於Controller類別 從Assemblies中
 /// </summary>
 /// <param name="buildManager">預設使用BuildManager</param>
 public void EnsureInitialized(IBuildManager buildManager)
 {
     if (_cache == null)
     {
         lock (_lockObj)
         {
             if (_cache == null)
             {
                 /***
                  * 獲得Controller類別順序如下
                  * 已IsControllerType(看後贅字是否是Controller)
                  * 1.從硬碟中找尋是否有快取的Controller類別
                  * 2.從組件中掃描出已Controller結尾的類別,並將資料序列話存在硬碟上
                  **/
                 List <Type> controllerTypes = TypeCacheUtil.GetFilteredTypesFromAssemblies(TypeCacheName, IsControllerType, 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);
             }
         }
     }
 }
 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);
     }
 }
        ///<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 static void CleanupFactory()
 {
     _backgroundScanner = null;
     _buildManager      = null;
     _taskProvider      = null;
     _projectStores.Clear();
 }
 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);
     }
 }
 public void EnsureInitialized(IBuildManager buildManager)
 {
     if (_cache == null)
     {
         lock (_lockObj)
         {
             if (_cache == null)
             {
                 List <Type> controllerTypes = TypeCacheUtil.GetFilteredTypesFromAssemblies(
                     TypeCacheName,
                     IsControllerType,
                     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 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);
		}
示例#10
0
        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);
        }
        protected BuildManager(IBuildManager buildManager)
        {
            if (buildManager == null)
                throw new ArgumentNullException("buildManager");

            _buildManager = buildManager;
        }
示例#12
0
    public ShopItemView(Transform content, Building scriptObj)
    {
        if (_prefab == null)
        {
            _prefab = Resources.Load <GameObject>("Prefabs/UI/ShopItem");
        }

        _uiManager       = GameClient.Get <IUIManager>();
        _settingsManager = GameClient.Get <ISettingsManager>();
        _buildManager    = GameClient.Get <IBuildManager>();

        transform  = MonoBehaviour.Instantiate(_prefab, content).transform;
        _scriptObj = scriptObj;

        _itemImage            = transform.Find("ItemImage").GetComponent <Image>();
        _itemName             = transform.Find("ItemName").GetComponent <Text>();
        _itemDescription      = transform.Find("DescriptionText").GetComponent <Text>();
        _itemButton           = transform.Find("ItemImage").GetComponent <Button>();
        _descriptionButton    = transform.Find("DescriptionButton").GetComponent <Button>();
        _descriptionOutButton = transform.Find("DescriptionText").GetComponent <Button>();

        _itemButton.onClick.AddListener(OnItemClickHandler);
        _descriptionButton.onClick.AddListener(DescriptionOnClickHandler);
        _descriptionOutButton.onClick.AddListener(DescriptionOutOnClickHandler);

        _itemImage.sprite     = scriptObj.Icon;
        _itemName.text        = scriptObj.BuildingName;
        _itemDescription.text = scriptObj.Description;
    }
示例#13
0
        public ControllerTypeResolver(
            IEnumerable <string> areaNamespacesToIgnore,
            RouteCollection routes,
            IControllerBuilder controllerBuilder,
            IBuildManager buildManager
            )
        {
            if (areaNamespacesToIgnore == null)
            {
                throw new ArgumentNullException("areaNamespacesToIgnore");
            }
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }
            if (controllerBuilder == null)
            {
                throw new ArgumentNullException("controllerBuilder");
            }
            if (buildManager == null)
            {
                throw new ArgumentNullException("buildManager");
            }

            this.areaNamespacesToIgnore = areaNamespacesToIgnore;
            this.routes            = routes;
            this.controllerBuilder = controllerBuilder;
            this.buildManager      = buildManager;

            Cache = new ThreadSafeDictionary <string, Type>();
        }
 public ReferencedExtensionLoader(IDependenciesFolder dependenciesFolder, IVirtualPathProvider virtualPathProvider, IBuildManager buildManager)
     : base(dependenciesFolder)
 {
     _virtualPathProvider = virtualPathProvider;
     _buildManager = buildManager;
     Logger = NullLogger.Instance;
 }
示例#15
0
 internal static void RegisterAllPlugins(RouteCollection routes, IBuildManager buildManager, object state)
 {
     foreach (Type type in TypeCacheUtil.GetFilteredTypesFromAssemblies(TypeCacheName, new Predicate <Type>(PluginBase.IsPluginType), buildManager))
     {
         ((PluginBase)Activator.CreateInstance(type)).CreateContextAndRegister(routes, state);
     }
 }
        /// <summary>
        /// Reads the types from cache.
        /// </summary>
        /// <param name="buildManager">The build manager.</param>
        /// <param name="cacheName">Name of the cache.</param>
        /// <param name="predicate">The predicate.</param>
        /// <param name="serializer">The serializer.</param>
        /// <returns></returns>
        public static IEnumerable <Type> ReadTypesFromCache(IBuildManager buildManager, string cacheName, Predicate <Type> predicate, ITypeCacheSerializer serializer)
        {
            Func <Type, bool> func = type => (TypeIsPublicClass(type) && predicate(type));

            try
            {
                using (var s = buildManager.ReadCachedFile(cacheName))
                    if (s != null)
                    {
                        using (var r = new StreamReader(s))
                        {
                            var source = serializer.DeserializeTypes(r);
                            if (source != null)
                            {
                                if (source.All(func))
                                {
                                    return(source);
                                }
                            }
                        }
                    }
            }
            catch { }
            return(null);
        }
        internal static Version GetPreviousRuntimeVersion(IBuildManager buildManagerFileSystem)
        {
            string fileName = GetCachedFileName();

            try
            {
                Stream stream = buildManagerFileSystem.ReadCachedFile(fileName);
                if (stream == null)
                {
                    return(null);
                }

                using (StreamReader reader = new StreamReader(stream))
                {
                    string  text = reader.ReadLine();
                    Version version;
                    if (Version.TryParse(text, out version))
                    {
                        return(version);
                    }
                }
            }
            catch
            {
            }
            return(null);
        }
示例#18
0
        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
                {
                    typesInAsm = assembly.GetTypes();
                }
                catch (ReflectionTypeLoadException ex)
                {
                    typesInAsm = ex.Types;
                }
                typesSoFar = typesSoFar.Concat(typesInAsm);
            }
            return(typesSoFar.Where(type => TypeIsPublicClass(type) && predicate(type)));
        }
 public ReferencedExtensionLoader(IDependenciesFolder dependenciesFolder, IVirtualPathProvider virtualPathProvider, IBuildManager buildManager)
     : base(dependenciesFolder)
 {
     _virtualPathProvider = virtualPathProvider;
     _buildManager        = buildManager;
     Logger = NullLogger.Instance;
 }
        /// <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;
        }
示例#21
0
        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));
        }
示例#22
0
 public WrenchProject(SourceSettings ss, IGraphState graph,
                      ActionLog log)
 {
     this.ss      = ss;
     this.log     = log;
     this.graph   = graph;
     this.manager = WrenchOperations.MakeManager(this);
 }
示例#23
0
        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);
		}
 public static IBuildManager GetBuildManager()
 {
     if (_buildManager == null)
     {
         _buildManager = new BuildManager(_serviceProvider);
     }
     return _buildManager;
 }
 public static IBuildManager GetBuildManager()
 {
     if (_buildManager == null)
     {
         _buildManager = new BuildManager(_serviceProvider);
     }
     return(_buildManager);
 }
        protected ThemeableBuildManagerViewEngine(IBuildManager buildManager) {
            
            if (buildManager == null) {
                throw new ArgumentNullException("buildManager");
            }

            BuildManager = buildManager;
        }
 public AssemblyProbingServiceImpl(IAssemblyLoader assemblyLoader,
                                   IFileSystem fileSystem,
                                   IBuildManager buildManager)
 {
     AssemblyLoader = assemblyLoader;
     FileSystem     = fileSystem;
     BuildManager   = buildManager;
 }
 public AspNetPresenterTypeResolver(
     IBuildManager buildManager,
     IEnumerable <string> defaultNamespaces,
     IEnumerable <string> viewSuffixes,
     IEnumerable <string> presenterNameTemplates)
     : base(buildManager, defaultNamespaces, viewSuffixes, presenterNameTemplates)
 {
 }
示例#29
0
 public BootstrapperTestDouble(
     Mock <ContainerAdapter> adapter,
     IBuildManager buildManager,
     IBootstrapperTasksRegistry bootstrapperTasksRegistry,
     IPerRequestTasksRegistry perRequestTasksRegistry) : base(buildManager, bootstrapperTasksRegistry, perRequestTasksRegistry)
 {
     this.adapter = adapter;
 }
示例#30
0
	public WrenchProject (SourceSettings ss, IGraphState graph, 
			      ActionLog log) 
	{
	    this.ss = ss;
	    this.log = log;
	    this.graph = graph;
	    this.manager = WrenchOperations.MakeManager (this);
	}
示例#31
0
        // 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);
        }
示例#32
0
        ///<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;
        }
示例#33
0
        private static void RegisterSpamDetectors(IBuildManager buildManager, IUnityContainer container)
        {
            Type spamDetectorInterfaceType = typeof(ISpamDetector);

            foreach (Type spamDetectorType in buildManager.ConcreteTypes.Where(spamDetectorInterfaceType.IsAssignableFrom))
            {
                container.RegisterType(spamDetectorInterfaceType, spamDetectorType, spamDetectorType.FullName, perRequest());
            }
        }
 /// <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;
 }
        // 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;
        }
 public ExtensionHarvester(ICacheManager cacheManager, IWebSiteFolder webSiteFolder, ICriticalErrorProvider criticalErrorProvider, IBuildManager buildManager)
 {
     this.cacheManager          = cacheManager;
     this.webSiteFolder         = webSiteFolder;
     this.criticalErrorProvider = criticalErrorProvider;
     this.buildManager          = buildManager;
     Logger = NullLogger.Instance;
     T      = NullLocalizer.Instance;
 }
示例#37
0
        protected ThemeableBuildManagerViewEngine(IBuildManager buildManager)
        {
            if (buildManager == null)
            {
                throw new ArgumentNullException("buildManager");
            }

            BuildManager = buildManager;
        }
示例#38
0
        private static void RegisterBackgroundServices(IBuildManager buildManager, IUnityContainer container)
        {
            Type backgroundServiceInterfaceType = typeof(IBackgroundService);

            foreach (Type backgroundServiceType in buildManager.ConcreteTypes.Where(backgroundServiceInterfaceType.IsAssignableFrom))
            {
                container.RegisterType(backgroundServiceInterfaceType, backgroundServiceType, backgroundServiceType.FullName, singleton());
            }
        }
示例#39
0
        public WebFormRoutingHandler(string virtualPath,
                                     bool validateAccessRights, IBuildManager buildManager)
            : base()
        {
            Precondition.Defined(virtualPath, () => Error.ArgumentNull("virtualPath"));

            _virtualPath          = virtualPath;
            _validateAccessRights = validateAccessRights;
            _buildManager         = buildManager;
        }
示例#40
0
        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 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 BuildManagerWrapper()
 {
     if (IsUsingWebServer())
     {
         _innerBuildManager = new IISBuildManager();
     }
     else
     {
         _innerBuildManager = new NonHostedBuildManager();
     }
 }
示例#44
0
        public HttpControllerTypeCache(HttpConfiguration configuration)
        {
            if (configuration == null)
            {
                throw Error.ArgumentNull("configuration");
            }

            _configuration = configuration;
            _buildManager  = _configuration.ServiceResolver.GetBuildManager();
            _cache         = InitializeCache();
        }
        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 DynamicExtensionLoaderAccessor(
     IBuildManager buildManager,
     IVirtualPathProvider virtualPathProvider,
     IVirtualPathMonitor virtualPathMonitor,
     IHostEnvironment hostEnvironment,
     IAssemblyProbingFolder assemblyProbingFolder,
     IDependenciesFolder dependenciesFolder,
     IProjectFileParser projectFileParser)
     : base(buildManager, virtualPathProvider, virtualPathMonitor, hostEnvironment, assemblyProbingFolder, dependenciesFolder, projectFileParser)
 {
 }
示例#48
0
 //时时刻刻能感受到,是我要怎么写代码,而不是我只能如何写代码,而是我真正驾驭着代码。
 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));
 }
示例#49
0
 //读取全部是从缓存文件中读,若为空先写入缓存,再读取。(基本上所有的涉及缓存的操作都是这么个套路)
 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;
 }
示例#50
0
 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 {
     }
 }
        /// <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);
            }
        }
示例#52
0
 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;
		}
        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 }) }
            );
        }
示例#55
0
 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;
        }
示例#57
0
        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;
        }
示例#58
0
 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;
 }
示例#59
0
        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;
 }