public ExtensionEntry Load(ExtensionDescriptor descriptor)
        {
            if (!ExtensionsSearchPaths.Contains(descriptor.Location))
            {
                return null;
            }

            var directory = _fileSystem.GetDirectoryInfo(descriptor.Location);

            using (_loaderContainer.AddLoader(_extensionAssemblyLoader.WithPath(directory.FullName)))
            {
                try
                {
                    var assembly = Assembly.Load(new AssemblyName(descriptor.Id));

                    if (_logger.IsEnabled(LogLevel.Information))
                    {
                        _logger.LogInformation("Loaded referenced extension \"{0}\": assembly name=\"{1}\"", descriptor.Name, assembly.FullName);
                    }
                    return new ExtensionEntry
                    {
                        Descriptor = descriptor,
                        Assembly = assembly,
                        ExportedTypes = assembly.ExportedTypes
                    };
                }
                catch (System.Exception ex)
                {
                    _logger.LogError(string.Format("Error trying to load extension {0}", descriptor.Id), ex);
                    throw;
                }
            }
        }
Esempio n. 2
0
        public ExtensionEntry Load(ExtensionDescriptor descriptor)
        {
            if (!ExtensionsSearchPaths.Contains(descriptor.Location))
            {
                return null;
            }

            try
            {
                var assembly = _extensionLibraryService.LoadDynamicExtension(descriptor);
            
                if (assembly == null)
                {
                    return null;
                }

                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("Loaded referenced dynamic extension \"{0}\": assembly name=\"{1}\"", descriptor.Name, assembly.FullName);
                }

                return new ExtensionEntry
                {
                    Descriptor = descriptor,
                    Assembly = assembly,
                    ExportedTypes = assembly.ExportedTypes
                };
            }
            catch
            {
                return null;
            }
       }
        public override ExtensionProbeEntry Probe(ExtensionDescriptor descriptor) {
            if (Disabled)
                return null;

            if (descriptor.Location == "~/Themes") {
                string projectPath = _virtualPathProvider.Combine(descriptor.Location, descriptor.Id,
                                           descriptor.Id + ".csproj");

                // ignore themes including a .csproj in this loader
                if ( _virtualPathProvider.FileExists(projectPath) ) {
                    return null;
                }

                var assemblyPath = _virtualPathProvider.Combine(descriptor.Location, descriptor.Id, "bin",
                                                descriptor.Id + ".dll");

                // ignore themes with /bin in this loader
                if ( _virtualPathProvider.FileExists(assemblyPath) )
                    return null;

                return new ExtensionProbeEntry {
                    Descriptor = descriptor,
                    Loader = this,
                    VirtualPath = "~/Theme/" + descriptor.Id,
                    VirtualPathDependencies = Enumerable.Empty<string>(),
                };
            }
            return null;
        }
Esempio n. 4
0
        public async Task<ExtensionDescriptor> GetThemeAsync()
        {
            // For performance reason, processes the current theme only once per scope (request).
            // This can't be cached as each request gets a different value.
            if (_theme == null)
            {
                var allThemeResults = await Task.WhenAll(_themeSelectors.Select(async x => await x.GetThemeAsync().ConfigureAwait(false))).ConfigureAwait(false);

                var requestTheme = allThemeResults
                    .Where(x => x != null)
                    .OrderByDescending(x => x.Priority)
                    .ToList();

                if (requestTheme.Count == 0)
                {
                    return null;
                }

                // Try to load the theme to ensure it's present
                foreach (var theme in requestTheme)
                {
                    var t = _extensionManager.GetExtension(theme.ThemeName);
                    if (t != null)
                    {
                        return _theme = t;
                    }
                }

                // No valid theme. Don't save the result right now.
                return null;
            }

            return _theme;
        }
        public IEnumerable<ExtensionDescriptor> AvailableExtensions()
        {
            return _extensionsByName.
                Select(extensionByName =>
                    {
                        var extensionDescriptor = new ExtensionDescriptor
                        {
                            Location = string.Empty,
                            Id = extensionByName.Key,
                            ExtensionType = DefaultExtensionTypes.Module,
                            Path = extensionByName.Key
                        };

                        var features = extensionByName.Value.Features.Select(feature =>
                            new FeatureDescriptor
                            {
                                Extension = extensionDescriptor,
                                Id = feature
                            });

                        extensionDescriptor.Features = features;

                        return extensionDescriptor;
                    });
        }
Esempio n. 6
0
        public IEnumerable<string> GetZones(ExtensionDescriptor theme) {
            if(theme == null) {
                return Enumerable.Empty<string>();
            }

            IEnumerable<string> zones = new List<string>();

            // get the zones for this theme
            if (theme.Zones != null)
                zones = theme.Zones.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(x => x.Trim())
                    .Distinct()
                    .ToList();

            // if this theme has no zones defined then walk the BaseTheme chain until we hit a theme which defines zones
            while (zones.Count() == 0 && theme != null && !string.IsNullOrWhiteSpace(theme.BaseTheme)) {
                string baseTheme = theme.BaseTheme;
                theme = _extensionManager.GetExtension(baseTheme);
                if (theme != null && theme.Zones != null)
                    zones = theme.Zones.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(x => x.Trim())
                        .Distinct()
                        .ToList();
            }

            return zones;
        }
        private IViewEngine DeepEngines(ExtensionDescriptor theme) {
            return _configuredEnginesCache.BindDeepEngines(theme.Id, () => {
                // The order for searching for views is:
                // 1. Current "theme"
                // 2. Base themes of the current theme (in "base" order)
                // 3. Active features from modules in dependency order

                var engines = Enumerable.Empty<IViewEngine>();
                // 1. current theme
                engines = engines.Concat(CreateThemeViewEngines(theme));

                // 2. Base themes of the current theme (in "base" order)
                engines = GetBaseThemes(theme).Aggregate(engines, (current, baseTheme) => current.Concat(CreateThemeViewEngines(baseTheme)));

                // 3. Active features from modules in dependency order
                var enabledModules = _extensionManager.EnabledFeatures(_shellDescriptor)
                    .Reverse()  // reverse from (C <= B <= A) to (A => B => C)
                    .Where(fd => DefaultExtensionTypes.IsModule(fd.Extension.ExtensionType));

                var allLocations = enabledModules.Concat(enabledModules)
                    .Select(fd => fd.Extension.Location + "/" + fd.Extension.Id)
                    .Distinct(StringComparer.OrdinalIgnoreCase)
                    .ToList();

                var moduleParams = new CreateModulesViewEngineParams { VirtualPaths = allLocations };
                engines = engines.Concat(_viewEngineProviders.Select(vep => vep.CreateModulesViewEngine(moduleParams)));

                return new ViewEngineCollectionWrapper(engines);
            });
        }
Esempio n. 8
0
 public ExtensionEntry Load(ExtensionDescriptor descriptor) {
     var dependency = _dependenciesFolder.GetDescriptor(descriptor.Id);
     if (dependency != null && dependency.LoaderName == this.Name) {
         return LoadWorker(descriptor);
     }
     return null;
 }
Esempio n. 9
0
        public Stream BuildPackage(ExtensionDescriptor extensionDescriptor) {
            var context = new CreateContext();
            BeginPackage(context);
            try {
                EstablishPaths(context, _webSiteFolder, extensionDescriptor.Location, extensionDescriptor.Id, extensionDescriptor.ExtensionType);
                SetCoreProperties(context, extensionDescriptor);

                string projectFile = extensionDescriptor.Id + ".csproj";
                if (LoadProject(context, projectFile)) {
                    EmbedVirtualFile(context, projectFile, MediaTypeNames.Text.Xml);
                    EmbedProjectFiles(context, "Compile", "Content", "None", "EmbeddedResource");
                    EmbedReferenceFiles(context);
                } else if (DefaultExtensionTypes.IsTheme(extensionDescriptor.ExtensionType)) {
                    // this is a simple theme with no csproj
                    EmbedThemeFiles(context);
                }
            }
            finally {
                EndPackage(context);
            }

            if (context.Stream.CanSeek) {
                context.Stream.Seek(0, SeekOrigin.Begin);
            }

            return context.Stream;
        }
Esempio n. 10
0
        public override ExtensionProbeEntry Probe(ExtensionDescriptor descriptor) {
            if (Disabled)
                return null;

            // Temporary - theme without own project should be under ~/themes
            if (descriptor.Location.StartsWith("~/Themes",StringComparison.InvariantCultureIgnoreCase)) {
                string projectPath = _virtualPathProvider.Combine(descriptor.Location, descriptor.Id,
                                           descriptor.Id + ".csproj");

                // ignore themes including a .csproj in this loader
                if ( _virtualPathProvider.FileExists(projectPath) ) {
                    return null;
                }

                var assemblyPath = _virtualPathProvider.Combine(descriptor.Location, descriptor.Id, "bin",
                                                descriptor.Id + ".dll");

                // ignore themes with /bin in this loader
                if ( _virtualPathProvider.FileExists(assemblyPath) )
                    return null;

                return new ExtensionProbeEntry {
                    Descriptor = descriptor,
                    Loader = this,
                    VirtualPath = descriptor.VirtualPath,
                    VirtualPathDependencies = Enumerable.Empty<string>(),
                };
            }
            return null;
        }
Esempio n. 11
0
        public ExtensionEntry Load(ExtensionDescriptor descriptor)
        {
            if (!descriptor.Location.StartsWith("Core"))
            {
                return null;
            }

            var directory = _fileSystem.GetDirectoryInfo("Core");

            using (_loaderContainer.AddLoader(_extensionAssemblyLoader.WithPath(directory.FullName)))
            {
                var assembly = Assembly.Load(new AssemblyName(CoreAssemblyName));

                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("Loaded referenced extension \"{0}\": assembly name=\"{1}\"", descriptor.Name, assembly.FullName);
                }
                return new ExtensionEntry
                {
                    Descriptor = descriptor,
                    Assembly = assembly,
                    ExportedTypes = assembly.ExportedTypes.Where(x => IsTypeFromModule(x, descriptor))
                };
            }
        }
Esempio n. 12
0
        private IEnumerable<string> ExtractLayoutNames(ExtensionDescriptor theme)
        {
            var views = Directory.EnumerateFiles(HttpContext.Current.Server.MapPath(
                        string.Format("{0}/{1}/Views/", theme.Location, theme.Name.Replace(" ", ""))), "*.cshtml").Select(template =>
                        {
                            var f = new FileInfo(template);

                            if (f.Name.StartsWith("Layout-"))
                            {
                                string fname = f.Name.Replace("Layout-", "")
                                               .Replace("-", " ")
                                               .Replace(f.Extension, "");

                                if (fname.Length > 0)
                                    return fname;
                            }
                            return null;
                        }).Where(n => n != null);

            // Traverse base themes
            if (!String.IsNullOrWhiteSpace(theme.BaseTheme))
            {
                var baseTheme = _extensionManager.GetExtension(theme.BaseTheme);
                // Concat not Union since Distinct is enforce in service anyway
                views = views.Concat(ExtractLayoutNames(baseTheme));
            }
            return views;
        }
Esempio n. 13
0
        public ExtensionEntry Load(ExtensionDescriptor descriptor)
        {
            if (!ExtensionsSearchPaths.Contains(descriptor.Location)) {
                return null;
            }

            var plocation = _hostEnvironment.MapPath(descriptor.Location);

            using (_loaderContainer.AddLoader(_extensionAssemblyLoader.WithPath(plocation))) {
                try {
                    var assembly = Assembly.Load(new AssemblyName(descriptor.Id));

                    _logger.LogInformation("Loaded referenced extension \"{0}\": assembly name=\"{1}\"", descriptor.Name, assembly.FullName);

                    return new ExtensionEntry {
                        Descriptor = descriptor,
                        Assembly = assembly,
                        ExportedTypes = assembly.ExportedTypes
                    };
                }
                catch (System.Exception ex) {
                    _logger.LogError(string.Format("Error trying to load extension {0}", descriptor.Id), ex);
                    throw;
                }
            }
        }
Esempio n. 14
0
        public ExtensionEntry Load(ExtensionDescriptor descriptor)
        {
            //var probingFolder = _fileSystem.GetDirectoryInfo("bin");
            //if (!probingFolder.Exists)
            //{
            //    probingFolder.Create();
            //}

            //var location = Path.Combine(_fileSystem.RootPath, descriptor.Location, descriptor.Id);

            //Process.Start("dotnet", $"build \"{location}\" --output \"{probingFolder}\" --framework netstandard1.5").WaitForExit();

            //var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(probingFolder.FullName, descriptor.Id) + ".dll");

            //if (assembly == null)
            //{
            //    return null;
            //}

            //return new ExtensionEntry
            //{
            //    Descriptor = descriptor,
            //    Assembly = assembly,
            //    ExportedTypes = assembly.ExportedTypes
            //};

            return null;
        }
Esempio n. 15
0
        protected override void Resolve(ILifetimeScope container) {
            _compositionStrategy = container.Resolve<CompositionStrategy>();
            _compositionStrategy.Logger = container.Resolve<ILogger>();

            var alphaExtension = new ExtensionDescriptor {
                Id = "Alpha",
                Name = "Alpha",
                ExtensionType = "Module"
            };

            var alphaFeatureDescriptor = new FeatureDescriptor {
                Id = "Alpha",
                Name = "Alpha",
                Extension = alphaExtension
            };

            var betaFeatureDescriptor = new FeatureDescriptor {
                Id = "Beta",
                Name = "Beta",
                Extension = alphaExtension,
                Dependencies = new List<string> {
                    "Alpha"
                }
            };

            alphaExtension.Features = new List<FeatureDescriptor> {
                alphaFeatureDescriptor,
                betaFeatureDescriptor
            };

            _availableExtensions = new[] {
                alphaExtension
            };

            _installedFeatures = new List<Feature> {
                new Feature {
                    Descriptor = alphaFeatureDescriptor,
                    ExportedTypes = new List<Type> {
                        typeof(AlphaDependency)
                    }
                },
                new Feature {
                    Descriptor = betaFeatureDescriptor,
                    ExportedTypes = new List<Type> {
                        typeof(BetaDependency)
                    }
                }
            };

            _loggerMock.Setup(x => x.IsEnabled(It.IsAny<LogLevel>())).Returns(true);

            _extensionManager.Setup(x => x.AvailableExtensions()).Returns(() => _availableExtensions);

            _extensionManager.Setup(x => x.AvailableFeatures()).Returns(() =>
                _extensionManager.Object.AvailableExtensions()
                .SelectMany(ext => ext.Features)
                .ToReadOnlyCollection());

            _extensionManager.Setup(x => x.LoadFeatures(It.IsAny<IEnumerable<FeatureDescriptor>>())).Returns(() => _installedFeatures);
        }
Esempio n. 16
0
 public override void ExtensionActivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension)
 {
     if (_reloadWorkaround.AppDomainRestartNeeded)
     {
         Logger.Information("ExtensionActivated: Module \"{0}\" has changed, forcing AppDomain restart", extension.Id);
         ctx.RestartAppDomain = _reloadWorkaround.AppDomainRestartNeeded;
     }
 }
Esempio n. 17
0
        public Assembly LoadAmbientExtension(ExtensionDescriptor descriptor)
        {
            if (IsAmbientExtension(descriptor))
            {
                return Assembly.Load(new AssemblyName(descriptor.Id));
            }

            return null;
        }
 public ExtensionEntry Load(ExtensionDescriptor descriptor)
 {
     //var assembly = Assembly.Load(descriptor.Name);
     //return new ModuleEntry {
     //    Descriptor = descriptor,
     //    Assembly = assembly,
     //    ExportedTypes = assembly.GetExportedTypes()
     //};
     return null;
 }
        public static IOrchardFileSystem GetExtensionFileProvider(
            this IOrchardFileSystem parentFileSystem,
            ExtensionDescriptor extensionDescriptor,
            ILogger logger)
        {
            var subPath = parentFileSystem.Combine(extensionDescriptor.Location, extensionDescriptor.Id);

            return parentFileSystem
                .GetSubPathFileProvider(subPath, logger);
        }
Esempio n. 20
0
        private static void SetCoreProperties(CreateContext context, ExtensionDescriptor extensionDescriptor) {
            context.Builder.Id = BuildPackageId(extensionDescriptor.Id, extensionDescriptor.ExtensionType);
            context.Builder.Version = new Version(extensionDescriptor.Version);
            context.Builder.Title = extensionDescriptor.Name ?? extensionDescriptor.Id;
            context.Builder.Description = extensionDescriptor.Description;
            context.Builder.Authors.Add(extensionDescriptor.Author);

            if(Uri.IsWellFormedUriString(extensionDescriptor.WebSite, UriKind.Absolute)) {
                context.Builder.ProjectUrl = new Uri(extensionDescriptor.WebSite);
            }
        }
        public ExtensionEntry Load(ExtensionDescriptor descriptor)
        {
            if (ExtensionsSearchPaths == null || descriptor == null || !ExtensionsSearchPaths.Contains(descriptor.Location))
            {
                return null;
            }

            var directory = _fileSystem.GetDirectoryInfo(descriptor.Location);

            return null;
        }
        public ExtensionEntry Load(ExtensionDescriptor descriptor)
        {
            var assembly = Assembly.Load(new AssemblyName(descriptor.Id));

            return new ExtensionEntry
            {
                Descriptor = descriptor,
                Assembly = assembly,
                ExportedTypes = assembly.ExportedTypes
            };
        }
        protected override ExtensionEntry LoadWorker(ExtensionDescriptor descriptor) {
            if (Disabled)
                return null;

            Logger.Information("Loaded no-code theme \"{0}\"", descriptor.Name);

            return new ExtensionEntry {
                Descriptor = descriptor,
                Assembly = GetType().Assembly,
                ExportedTypes = new Type[0]
            };
        }
        public ExtensionEntry Load(ExtensionDescriptor descriptor)
        {
            if (descriptor.Location == "~/Areas") {

                var assembly = Assembly.Load("Orchard.Web");
                return new ExtensionEntry {
                                              Descriptor = descriptor,
                                              Assembly = assembly,
                                              ExportedTypes = assembly.GetExportedTypes().Where(x => IsTypeFromModule(x, descriptor))
                                          };
            }
            return null;
        }
        public override void ExtensionDeactivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) {
            if (_assemblyProbingFolder.AssemblyExists(extension.Id)) {
                ctx.DeleteActions.Add(
                    () => {
                        Logger.Information("ExtensionDeactivated: Deleting assembly \"{0}\" from probing directory", extension.Id);
                        _assemblyProbingFolder.DeleteAssembly(extension.Id);
                    });

                // We need to restart the appDomain if the assembly is loaded
                if (_hostEnvironment.IsAssemblyLoaded(extension.Id)) {
                    Logger.Information("ExtensionDeactivated: Module \"{0}\" is deactivated and its assembly is loaded, forcing AppDomain restart", extension.Id);
                    ctx.RestartAppDomain = true;
                }
            }
        }
Esempio n. 26
0
        public override ExtensionProbeEntry Probe(ExtensionDescriptor descriptor) {
            if (Disabled)
                return null;

            if (descriptor.Location == "~/Core") {
                return new ExtensionProbeEntry {
                    Descriptor = descriptor,
                    Loader = this,
                    Priority = 100, // Higher priority because assemblies in ~/bin always take precedence
                    VirtualPath = "~/Core/" + descriptor.Id,
                    VirtualPathDependencies = Enumerable.Empty<string>(),
                };
            }
            return null;
        }
        protected override ExtensionEntry LoadWorker(ExtensionDescriptor descriptor) {
            if (Disabled)
                return null;

            var assembly = _buildManager.GetReferencedAssembly(descriptor.Id);
            if (assembly == null)
                return null;

            Logger.Information("Loaded referenced extension \"{0}\": assembly name=\"{1}\"", descriptor.Name, assembly.FullName);

            return new ExtensionEntry {
                Descriptor = descriptor,
                Assembly = assembly,
                ExportedTypes = assembly.GetExportedTypes()
            };
        }
        public override void Monitor(ExtensionDescriptor descriptor, Action<IVolatileToken> monitor) {
            if (Disabled)
                return;

            // Monitor .csproj and all .cs files
            string projectPath = GetProjectPath(descriptor);
            if (projectPath != null) {
                foreach (var path in GetDependencies(projectPath)) {
                    Logger.Debug("Monitoring virtual path \"{0}\"", path);

                    var token = _virtualPathMonitor.WhenPathChanges(path);
                    monitor(token);
                    _reloadWorkaround.Monitor(token);
                }
            }
        }
Esempio n. 29
0
        private IEnumerable<Recipe> HarvestRecipes(ExtensionDescriptor extension) {
            var recipes = new List<Recipe>();
            
            var recipeLocation = Path.Combine(extension.Location, extension.Id, "Recipes");
            var recipeFiles = _webSiteFolder.ListFiles(recipeLocation, true);

            recipeFiles.Where(r => r.EndsWith(".recipe.xml", StringComparison.OrdinalIgnoreCase)).ToList().ForEach(r => {
                try {
                    recipes.Add(_recipeParser.ParseRecipe(_webSiteFolder.ReadFile(r)));
                }
                catch (Exception ex) {
                    Logger.Error(ex, "Error while parsing recipe file '{0}'.", r);
                }
            });
            
            return recipes;
        }
Esempio n. 30
-1
        private async Task<IEnumerable<RecipeDescriptor>> HarvestRecipesAsync(ExtensionDescriptor extension)
        {
            var recipeLocation = _fileSystem.Combine(extension.Location, extension.Id, "Recipes");

            var recipeOptions = _recipeOptions.Value;

            List<RecipeDescriptor> recipeDescriptors = new List<RecipeDescriptor>();

            foreach(var recipeFileExtension in recipeOptions.RecipeFileExtensions)
            {
                var fileMatcher = new Matcher(System.StringComparison.OrdinalIgnoreCase);
                fileMatcher.AddInclude(recipeFileExtension.Key);

                var recipeFiles = _fileSystem.ListFiles(recipeLocation, fileMatcher);

                recipeDescriptors.AddRange(await recipeFiles.InvokeAsync(recipeFile => {
                    var recipeParser = _recipeParsers.First(x => x.GetType() == recipeFileExtension.Value);
                    using (var stream = recipeFile.CreateReadStream()) {
                        var recipe = recipeParser.ParseRecipe(stream);
                        recipe.Location = recipeFile.PhysicalPath.Replace(_fileSystem.RootPath, "").TrimStart(System.IO.Path.DirectorySeparatorChar);
                        return Task.FromResult(recipe);
                    }
                }, Logger));
            }

            return recipeDescriptors;
        }