Beispiel #1
0
        public IDirectoryContents GetDirectoryContents(string subpath)
        {
            if (subpath == null)
            {
                return(NotFoundDirectoryContents.Singleton);
            }

            var folder = _contentRoot + NormalizePath(subpath);

            var entries = new List <IFileInfo>();

            if (folder == "")
            {
                entries.Add(new EmbeddedDirectoryInfo(Application.ModulesPath));
            }
            else if (folder == Application.ModulesPath)
            {
                entries.AddRange(_environment.GetApplication().ModuleNames
                                 .Select(n => new EmbeddedDirectoryInfo(n)));
            }
            else if (folder.StartsWith(Application.ModulesRoot, StringComparison.Ordinal))
            {
                var path  = folder.Substring(Application.ModulesRoot.Length);
                var index = path.IndexOf('/');

                var name       = index == -1 ? path : path.Substring(0, index);
                var assetPaths = _environment.GetModule(name).AssetPaths;

                var folders = new HashSet <string>(StringComparer.Ordinal);

                foreach (var assetPath in assetPaths.Where(a => a.StartsWith(folder, StringComparison.Ordinal)))
                {
                    path  = assetPath.Substring(folder.Length + 1);
                    index = path.IndexOf('/');

                    if (index == -1)
                    {
                        entries.Add(GetFileInfo(assetPath));
                    }
                    else
                    {
                        folders.Add(path.Substring(0, index));
                    }
                }

                entries.AddRange(folders.Select(f => new EmbeddedDirectoryInfo(f)));
            }

            return(new EmbeddedDirectoryContents(entries));
        }
        public IFileInfo GetFileInfo(string subpath)
        {
            if (subpath == null)
            {
                return(new NotFoundFileInfo(subpath));
            }

            var path = NormalizePath(subpath);

            var index = path.IndexOf('/');

            if (index != -1)
            {
                var module = path.Substring(0, index);

                if (_environment.GetApplication().NamedModules.Count(e => e.Name.Equals(module, StringComparison.Ordinal)) > 0)
                {
                    var fileSubPath = Module.WebRoot + path.Substring(index + 1);

                    if (module != _environment.GetApplication().Name)
                    {
                        return(_environment.GetModule(module).GetFileInfo(fileSubPath));
                    }

                    fileSubPath = _environment.GetApplication().Root + fileSubPath;
                    return(new PhysicalFileInfo(new FileInfo(fileSubPath)));
                }
            }

            return(new NotFoundFileInfo(subpath));
        }
        public ModuleProjectLiquidFileProvider(IHostingEnvironment environment)
        {
            if (_paths != null)
            {
                return;
            }

            lock (_synLock)
            {
                if (_paths == null)
                {
                    if (_paths == null)
                    {
                        var assets      = new List <Asset>();
                        var application = environment.GetApplication();

                        foreach (var name in application.ModuleNames)
                        {
                            var module = environment.GetModule(name);

                            if (module.Assembly == null || Path.GetDirectoryName(module.Assembly.Location)
                                != Path.GetDirectoryName(application.Assembly.Location))
                            {
                                continue;
                            }

                            assets.AddRange(module.Assets.Where(a => a.ModuleAssetPath
                                                                .EndsWith(".liquid", StringComparison.Ordinal)));
                        }

                        _paths = assets.ToDictionary(a => a.ModuleAssetPath, a => a.ProjectAssetPath);
                    }
                }
            }
        }
        public ModuleProjectStaticFileProvider(IHostingEnvironment environment)
        {
            if (_paths != null)
            {
                return;
            }

            lock (_synLock)
            {
                if (_paths == null)
                {
                    var application = environment.GetApplication();

                    var paths = new Dictionary <string, string>();

                    foreach (var name in application.ModuleNames)
                    {
                        var module = environment.GetModule(name);

                        if (module.Assembly == null || Path.GetDirectoryName(module.Assembly.Location)
                            != Path.GetDirectoryName(application.Assembly.Location))
                        {
                            continue;
                        }

                        var contentRoot = Application.ModulesRoot + name + '/' + Module.WebRoot;

                        var assets = module.Assets.Where(a => a.ModuleAssetPath
                                                         .StartsWith(contentRoot, StringComparison.Ordinal)).ToArray();

                        foreach (var asset in assets)
                        {
                            var requestPath = name + asset.ModuleAssetPath.Substring(contentRoot.Length - 1);
                            paths[requestPath] = asset.ProjectAssetPath;
                        }
                    }

                    _paths = paths;
                }
            }
        }
        public ModuleProjectContentFileProvider(IHostingEnvironment environment, string contentPath)
        {
            _contentRoot = NormalizePath(contentPath) + "/";

            if (_paths != null)
            {
                return;
            }

            lock (_synLock)
            {
                if (_paths == null)
                {
                    var assets      = new List <Asset>();
                    var application = environment.GetApplication();

                    foreach (var name in application.ModuleNames)
                    {
                        var module = environment.GetModule(name);

                        if (module.Assembly == null || Path.GetDirectoryName(module.Assembly.Location)
                            != Path.GetDirectoryName(application.Assembly.Location))
                        {
                            continue;
                        }

                        var contentRoot = Application.ModulesRoot + name + '/' + Module.ContentRoot;

                        assets.AddRange(module.Assets.Where(a => a.ModuleAssetPath
                                                            .StartsWith(contentRoot, StringComparison.Ordinal)));
                    }

                    _paths = assets.ToDictionary(a => a.ModuleAssetPath, a => a.ProjectAssetPath);
                }
            }
        }
Beispiel #6
0
        public void Apply(PageRouteModel model)
        {
            var pageName = model.ViewEnginePath.Trim('/');
            var tokenizer = new StringTokenizer(pageName, new[] { '/' });
            int count = tokenizer.Count(), pathIndex = 0;

            for (var i = 0; i < count; i++)
            {
                var segment = tokenizer.ElementAt(i);

                if ("Pages" == segment)
                {
                    if (i < 2 || i == count - 1)
                    {
                        return;
                    }

                    foreach (var selector in model.Selectors)
                    {
                        selector.AttributeRouteModel.SuppressLinkGeneration = true;
                    }

                    var module = tokenizer.ElementAt(i - 1).Value;

                    var template = pageName.Substring(pathIndex - (module.Length + 1));

                    model.Selectors.Add(new SelectorModel
                    {
                        AttributeRouteModel = new AttributeRouteModel
                        {
                            Template = template,
                            Name     = template.Replace('/', '.')
                        }
                    });

                    var name = _hostingEnvironment.GetModule(module).ModuleInfo.Name;

                    if (!String.IsNullOrWhiteSpace(name))
                    {
                        module = name;
                    }

                    if (module != Application.ModuleName)
                    {
                        template = module + pageName.Substring(pathIndex + "Pages".Length);
                    }
                    else
                    {
                        template = pageName.Substring(pathIndex + "Pages".Length + 1);
                    }


                    model.Selectors.Add(new SelectorModel
                    {
                        AttributeRouteModel = new AttributeRouteModel
                        {
                            Template = template,
                            Name     = template.Replace('/', '.')
                        }
                    });

                    break;
                }

                pathIndex += segment.Length + 1;
            }
        }
Beispiel #7
0
        public IDirectoryContents GetDirectoryContents(string subpath)
        {
            if (subpath == null)
            {
                return(NotFoundDirectoryContents.Singleton);
            }

            var folder = NormalizePath(subpath);

            var entries = new List <IFileInfo>();

            if (folder == "")
            {
                entries.Add(new EmbeddedDirectoryInfo(Application.ModulesPath));
            }
            else if (folder == Application.ModulesPath)
            {
                entries.AddRange(Application.ModuleNames
                                 .Select(n => new EmbeddedDirectoryInfo(n)));
            }
            else if (folder == Application.ModulePath)
            {
                return(new PhysicalDirectoryContents(Application.Path));
            }
            else if (folder.StartsWith(Application.ModuleRoot, StringComparison.Ordinal))
            {
                var tokenizer = new StringTokenizer(folder, new char[] { '/' });
                if (tokenizer.Any(s => s == "Pages" || s == "Views"))
                {
                    var folderSubPath = folder.Substring(Application.ModuleRoot.Length);
                    return(new PhysicalDirectoryContents(Application.Root + folderSubPath));
                }
            }
            else if (folder.StartsWith(Application.ModulesRoot, StringComparison.Ordinal))
            {
                var path        = folder.Substring(Application.ModulesRoot.Length);
                var index       = path.IndexOf('/');
                var name        = index == -1 ? path : path.Substring(0, index);
                var assetPaths  = _environment.GetModule(name).AssetPaths;
                var folders     = new HashSet <string>(StringComparer.Ordinal);
                var folderSlash = folder + '/';

                foreach (var assetPath in assetPaths.Where(a => a.StartsWith(folderSlash, StringComparison.Ordinal)))
                {
                    var folderPath = assetPath.Substring(folderSlash.Length);
                    var pathIndex  = folderPath.IndexOf('/');
                    var isFilePath = pathIndex == -1;

                    if (isFilePath)
                    {
                        entries.Add(GetFileInfo(assetPath));
                    }
                    else
                    {
                        folders.Add(folderPath.Substring(0, pathIndex));
                    }
                }

                entries.AddRange(folders.Select(f => new EmbeddedDirectoryInfo(f)));
            }

            return(new EmbeddedDirectoryContents(entries));
        }
        private IViewCompiler CreateCompiler()
        {
            var feature = new ViewsFeature();

            var featureProviders = _applicationPartManager.FeatureProviders
                                   .OfType <IApplicationFeatureProvider <ViewsFeature> >()
                                   .ToList();

            featureProviders.AddRange(_viewsFeatureProviders);

            var assemblyParts =
                new AssemblyPart[]
            {
                new AssemblyPart(Assembly.Load(new AssemblyName(_hostingEnvironment.ApplicationName)))
            };

            foreach (var provider in featureProviders)
            {
                provider.PopulateFeature(assemblyParts, feature);
            }

            var application = _hostingEnvironment.GetApplication();

            foreach (var descriptor in feature.ViewDescriptors)
            {
                if (descriptor.RelativePath.StartsWith(Application.ModulesRoot) ||
                    !(descriptor.ViewAttribute?.ViewType.Name.StartsWith("Pages_") ?? false))
                {
                    continue;
                }

                descriptor.RelativePath = '/' + application.ModulePath + descriptor.RelativePath;
            }

            if (!_hostingEnvironment.IsDevelopment())
            {
                var moduleNames   = _hostingEnvironment.GetApplication().ModuleNames;
                var moduleFeature = new ViewsFeature();

                foreach (var name in moduleNames)
                {
                    var module = _hostingEnvironment.GetModule(name);

                    if (module.Name == application.Name)
                    {
                        continue;
                    }

                    var precompiledAssemblyPath = Path.Combine(Path.GetDirectoryName(module.Assembly.Location),
                                                               module.Assembly.GetName().Name + ".Views.dll");

                    if (File.Exists(precompiledAssemblyPath))
                    {
                        try
                        {
                            var assembly = Assembly.LoadFile(precompiledAssemblyPath);

                            foreach (var provider in featureProviders)
                            {
                                provider.PopulateFeature(new ApplicationPart[] { new CompiledRazorAssemblyPart(assembly) }, moduleFeature);
                            }

                            foreach (var descriptor in moduleFeature.ViewDescriptors)
                            {
                                descriptor.RelativePath = '/' + module.SubPath + descriptor.RelativePath;
                                feature.ViewDescriptors.Add(descriptor);
                            }

                            moduleFeature.ViewDescriptors.Clear();
                        }
                        catch (FileLoadException)
                        {
                            // Don't throw if assembly cannot be loaded. This can happen if the file is not a managed assembly.
                        }
                    }
                }
            }

            return(new SharedRazorViewCompiler(
                       _fileProviderAccessor.FileProvider,
                       _razorProjectEngine,
                       _csharpCompiler,
                       _viewEngineOptions.CompilationCallback,
                       feature.ViewDescriptors,
                       _logger));
        }
Beispiel #9
0
        private void EnsureInitialized()
        {
            if (_isInitialized)
            {
                return;
            }

            lock (InitializationSyncLock)
            {
                if (_isInitialized)
                {
                    return;
                }

                var moduleNames      = _hostingEnvironment.GetApplication().ModuleNames;
                var loadedExtensions = new ConcurrentDictionary <string, ExtensionEntry>();

                // Load all extensions in parallel
                Parallel.ForEach(moduleNames, new ParallelOptions {
                    MaxDegreeOfParallelism = 8
                }, (name) =>
                {
                    var module = _hostingEnvironment.GetModule(name);

                    if (!module.ModuleInfo.Exists)
                    {
                        return;
                    }

                    var manifestConfiguration = _manifestOptions
                                                .ManifestConfigurations
                                                .FirstOrDefault(mc =>
                    {
                        return(module.ModuleInfo.Type.Equals(mc.Type, StringComparison.OrdinalIgnoreCase));
                    });

                    if (manifestConfiguration == null)
                    {
                        return;
                    }

                    var manifestInfo = new ManifestInfo(module.ModuleInfo);

                    var extensionInfo = new ExtensionInfo(module.SubPath, manifestInfo, (mi, ei) => {
                        return(_featuresProvider.GetFeatures(ei, mi));
                    });

                    var entry = new ExtensionEntry
                    {
                        ExtensionInfo = extensionInfo,
                        Assembly      = module.Assembly,
                        ExportedTypes = module.Assembly.ExportedTypes
                    };

                    loadedExtensions.TryAdd(module.Name, entry);
                });

                var loadedFeatures = new Dictionary <string, FeatureEntry>();

                // Get all valid types from any extension
                var allTypesByExtension = loadedExtensions.SelectMany(extension =>
                                                                      extension.Value.ExportedTypes.Where(IsComponentType)
                                                                      .Select(type => new
                {
                    ExtensionEntry = extension.Value,
                    Type           = type
                })).ToArray();

                var typesByFeature = allTypesByExtension
                                     .GroupBy(typeByExtension => GetSourceFeatureNameForType(
                                                  typeByExtension.Type,
                                                  typeByExtension.ExtensionEntry.ExtensionInfo.Id))
                                     .ToDictionary(
                    group => group.Key,
                    group => group.Select(typesByExtension => typesByExtension.Type).ToArray());

                foreach (var loadedExtension in loadedExtensions)
                {
                    var extension = loadedExtension.Value;

                    foreach (var feature in extension.ExtensionInfo.Features)
                    {
                        // Features can have no types
                        if (typesByFeature.TryGetValue(feature.Id, out var featureTypes))
                        {
                            foreach (var type in featureTypes)
                            {
                                _typeFeatureProvider.TryAdd(type, feature);
                            }
                        }
                        else
                        {
                            featureTypes = Array.Empty <Type>();
                        }

                        loadedFeatures.Add(feature.Id, new CompiledFeatureEntry(feature, featureTypes));
                    }
                }
                ;

                // Feature infos and entries are ordered by priority and dependencies.
                _featureInfos = Order(loadedFeatures.Values.Select(f => f.FeatureInfo));
                _features     = _featureInfos.ToDictionary(f => f.Id, f => loadedFeatures[f.Id]);

                // Extensions are also ordered according to the weight of their first features.
                _extensionsInfos = _featureInfos.Where(f => f.Id == f.Extension.Features.First().Id)
                                   .Select(f => f.Extension);

                _extensions = _extensionsInfos.ToDictionary(e => e.Id, e => loadedExtensions[e.Id]);

                _isInitialized = true;
            }
        }
Beispiel #10
0
        private void EnsureInitialized()
        {
            if (_isInitialized)
            {
                return;
            }

            lock (InitializationSyncLock)
            {
                if (_isInitialized)
                {
                    return;
                }

                var moduleNames   = _hostingEnvironment.GetApplication().NamedModules;
                var loadedPlugins = new ConcurrentDictionary <string, PluginEntry>();

                Parallel.ForEach(moduleNames, new ParallelOptions {
                    MaxDegreeOfParallelism = 8
                }, (name) =>
                {
                    var module = _hostingEnvironment.GetModule(name.Name);

                    if (!module.ModuleInfo.Exists)
                    {
                        return;
                    }
                    var manifestInfo = new ManifestInfo(module.ModuleInfo);

                    var pluginInfo = new PluginInfo(module.SubPath, manifestInfo, (mi, ei) =>
                    {
                        return(_featuresProvider.GetFeatures(ei, mi));
                    });

                    var entry = new PluginEntry
                    {
                        PluginInfo    = pluginInfo,
                        Assembly      = module.Assembly,
                        ExportedTypes = module.Assembly.ExportedTypes
                    };

                    loadedPlugins.TryAdd(module.Name, entry);
                });

                var loadedFeatures = new Dictionary <string, FeatureEntry>();

                var allTypesByExtension = loadedPlugins.SelectMany(extension =>
                                                                   extension.Value.ExportedTypes.Where(IsComponentType)
                                                                   .Select(type => new
                {
                    PluginEntry = extension.Value,
                    Type        = type
                })).ToArray();

                var typesByFeature = allTypesByExtension
                                     .GroupBy(typeByExtension => GetSourceFeatureNameForType(
                                                  typeByExtension.Type,
                                                  typeByExtension.PluginEntry.PluginInfo.Id))
                                     .ToDictionary(
                    group => group.Key,
                    group => group.Select(typesByExtension => typesByExtension.Type).ToArray());

                foreach (var loadedExtension in loadedPlugins)
                {
                    var plugin = loadedExtension.Value;

                    foreach (var feature in plugin.PluginInfo.Features)
                    {
                        if (typesByFeature.TryGetValue(feature.Id, out var featureTypes))
                        {
                            foreach (var type in featureTypes)
                            {
                                _typeFeatureProvider.TryAdd(type, feature);
                            }
                        }
                        else
                        {
                            featureTypes = Array.Empty <Type>();
                        }

                        loadedFeatures.Add(feature.Id, new CompiledFeatureEntry(feature, featureTypes));
                    }
                }
                ;

                _featureInfos = Order(loadedFeatures.Values.Select(f => f.FeatureInfo));
                _features     = _featureInfos.ToDictionary(f => f.Id, f => loadedFeatures[f.Id]);

                _pluginInfos = _featureInfos.Where(f => f.Id == f.Plugin.Features.First().Id)
                               .Select(f => f.Plugin);

                _plugins = _pluginInfos.ToDictionary(e => e.Id, e => loadedPlugins[e.Id]);

                _isInitialized = true;
            }
        }
Beispiel #11
0
        private IViewCompiler CreateCompiler()
        {
            var feature = new ViewsFeature();

            var featureProviders = _applicationPartManager.FeatureProviders
                                   .OfType <IApplicationFeatureProvider <ViewsFeature> >()
                                   .ToList();

            featureProviders.AddRange(_viewsFeatureProviders);

            var assemblyParts =
                new AssemblyPart[]
            {
                new AssemblyPart(Assembly.Load(new AssemblyName(_hostingEnvironment.ApplicationName)))
            };

            foreach (var provider in featureProviders)
            {
                provider.PopulateFeature(assemblyParts, feature);
            }

            if (!_hostingEnvironment.IsDevelopment())
            {
                var moduleNames   = _hostingEnvironment.GetApplication().NamedModules;
                var moduleFeature = new ViewsFeature();

                foreach (var name in moduleNames)
                {
                    var module = _hostingEnvironment.GetModule(name.Name);

                    var precompiledAssemblyPath = Path.Combine(Path.GetDirectoryName(module.Assembly.Location),
                                                               module.Assembly.GetName().Name + ".Views.dll");

                    if (File.Exists(precompiledAssemblyPath))
                    {
                        try
                        {
                            var assembly = Assembly.LoadFile(precompiledAssemblyPath);

                            foreach (var provider in featureProviders)
                            {
                                provider.PopulateFeature(new ApplicationPart[] { new CompiledRazorAssemblyPart(assembly) }, moduleFeature);
                            }

                            foreach (var descriptor in moduleFeature.ViewDescriptors)
                            {
                                descriptor.RelativePath = '/' + module.SubPath + descriptor.RelativePath;
                                feature.ViewDescriptors.Add(descriptor);
                            }

                            moduleFeature.ViewDescriptors.Clear();
                        }
                        catch (FileLoadException)
                        {
                        }
                    }
                }
            }

            return(new SharedRazorViewCompiler(
                       _fileProviderAccessor.FileProvider,
                       _razorProjectEngine,
                       _csharpCompiler,
                       // _viewEngineOptions.CompilationCallback,
                       feature.ViewDescriptors,
                       _logger));
        }