public TestRazorTemplateCompiler(
     RazorSourceGenerator sourceGenerator,
     RoslynCompilationService roslynCompilationService,
     RazorLightProject razorLightProject,
     RazorLightOptions razorLightOptions) : base(sourceGenerator, roslynCompilationService, razorLightProject, razorLightOptions)
 {
 }
        public virtual RazorLightEngine Build()
        {
            var options = new RazorLightOptions();

            if (namespaces != null)
            {
                options.Namespaces = namespaces;
            }

            if (dynamicTemplates != null)
            {
                options.DynamicTemplates = dynamicTemplates;
            }

            if (metadataReferences != null)
            {
                options.AdditionalMetadataReferences = metadataReferences;
            }

            if (prerenderCallbacks != null)
            {
                options.PreRenderCallbacks = prerenderCallbacks;
            }

            var sourceGenerator          = new RazorSourceGenerator(DefaultRazorEngine.Instance, project, options.Namespaces);
            var metadataReferenceManager = new DefaultMetadataReferenceManager(options.AdditionalMetadataReferences);

            var assembly = operatingAssembly ?? Assembly.GetEntryAssembly();

            var compiler = new RoslynCompilationService(metadataReferenceManager, assembly);
            var templateFactoryProvider = new TemplateFactoryProvider(sourceGenerator, compiler, options);

            return(new RazorLightEngine(options, templateFactoryProvider, cachingProvider));
        }
        public RazorTemplateCompiler(
            RazorSourceGenerator sourceGenerator,
            RoslynCompilationService roslynCompilationService,
            RazorLightProject razorLightProject,
            RazorLightOptions razorLightOptions)
        {
            _razorSourceGenerator = sourceGenerator ?? throw new ArgumentNullException(nameof(sourceGenerator));
            _compiler             = roslynCompilationService ?? throw new ArgumentNullException(nameof(roslynCompilationService));
            _razorProject         = razorLightProject ?? throw new ArgumentNullException(nameof(razorLightProject));
            _razorLightOptions    = razorLightOptions ?? throw new ArgumentNullException(nameof(razorLightOptions));

            // This is our L0 cache, and is a durable store. Views migrate into the cache as they are requested
            // from either the set of known precompiled views, or by being compiled.
            var cacheOptions = Options.Create(new MemoryCacheOptions());

            _cache = new MemoryCache(cacheOptions);

            _normalizedKeysCache = new ConcurrentDictionary <string, string>(StringComparer.Ordinal);

            // We need to validate that the all of the precompiled views are unique by path (case-insensitive).
            // We do this because there's no good way to canonicalize paths on windows, and it will create
            // problems when deploying to linux. Rather than deal with these issues, we just don't support
            // views that differ only by case.
            _precompiledViews = new Dictionary <string, CompiledTemplateDescriptor>(
                5,                 //Change capacity when precompiled views are arrived
                StringComparer.OrdinalIgnoreCase);
        }
 public RazorTemplateCompiler(
     RazorSourceGenerator sourceGenerator,
     ICompilationService compilationService,
     RazorLightProject razorLightProject,
     IOptions <RazorLightOptions> options) : this(sourceGenerator, compilationService, razorLightProject, options.Value)
 {
 }
Exemple #5
0
        public void GenerateCode_ByKey_Throws_OnEmpty_Project()
        {
            var generator = new RazorSourceGenerator(DefaultRazorEngine.Instance, project: null);

            Func <Task> action = () => generator.GenerateCodeAsync("key");

            Assert.ThrowsAsync <InvalidOperationException>(action);
        }
Exemple #6
0
        public void Namespaces_NotNull_If_Not_Specified()
        {
            var generator = new RazorSourceGenerator(
                DefaultRazorEngine.Instance,
                new EmbeddedRazorProject(typeof(Root)),
                namespaces: null);

            Assert.NotNull(generator.Namespaces);
        }
Exemple #7
0
        public void Ensure_Engine_And_Project_Not_Null()
        {
            var generator = new RazorSourceGenerator(
                RazorEngine.Create(),
                new EmbeddedRazorProject(typeof(RazorSourceGeneratorTest)));

            Assert.NotNull(generator.ProjectEngine);
            Assert.NotNull(generator.Project);
        }
 public TemplateFactoryProvider(
     RazorSourceGenerator generator,
     RoslynCompilationService compiler,
     RazorLightOptions razorOptions)
 {
     sourceGenerator  = generator ?? throw new ArgumentNullException(nameof(generator));
     templateCompiler = compiler ?? throw new ArgumentNullException(nameof(compiler));
     options          = razorOptions ?? throw new ArgumentNullException(nameof(razorOptions));
 }
        public async Task CreateCodeDocumentAsync_Throws_On_Null_ProjectItem()
        {
            var generator = new RazorSourceGenerator(DefaultRazorEngine.Instance, project: null);

            Func <Task> action = () => generator.CreateCodeDocumentAsync(null);

            var exception = await Assert.ThrowsAsync <ArgumentNullException>(action);

            Assert.Equal("projectItem", exception.ParamName);
        }
Exemple #10
0
        public async Task GenerateCode_ByKey_Throws_OnEmpty_Project()
        {
            var generator = new RazorSourceGenerator(DefaultRazorEngine.Instance, project: null);

            Func <Task> action = () => generator.GenerateCodeAsync("key");

            var exception = await Assert.ThrowsAsync <InvalidOperationException>(action);

            Assert.Equal("Can not resolve a content for the template \"key\" as there is no project set. You can only render a template by passing it's content directly via string using corresponding function overload", exception.Message);
        }
Exemple #11
0
        private TemplateFactoryProvider GetProvider()
        {
            var sourceGenerator    = new RazorSourceGenerator(DefaultRazorEngine.Instance, project);
            var metadataReferences = new DefaultMetadataReferenceManager();
            var compiler           = new RoslynCompilationService(metadataReferences, Assembly.GetEntryAssembly());

            var provider = new TemplateFactoryProvider(sourceGenerator, compiler, new RazorLightOptions());

            return(provider);
        }
            public static TestRazorTemplateCompiler Create(RazorLightOptions options = null, RazorLightProject project = null)
            {
                var razorOptions    = options ?? new RazorLightOptions();
                var metatadaManager = new DefaultMetadataReferenceManager();
                var assembly        = Assembly.GetCallingAssembly();
                var razorProject    = project ?? new EmbeddedRazorProject(assembly);
                var compilerService = new RoslynCompilationService(metatadaManager, assembly);
                var generator       = new RazorSourceGenerator(DefaultRazorEngine.Instance, razorProject);

                return(new TestRazorTemplateCompiler(generator, compilerService, razorProject, razorOptions));
            }
Exemple #13
0
        public async Task GetImports_Returns_EmptyCollection_On_Empty_Project_WhenResolving_Content_ByKey()
        {
            //Assign
            var generator = new RazorSourceGenerator(RazorEngine.Create(), new EmbeddedRazorProject(typeof(Root)));

            //Act
            var projectItem = new TextSourceRazorProjectItem("key", "some content");
            var result      = await generator.GetImportsAsync(projectItem);

            Assert.NotNull(result);
            Assert.Empty(result);
        }
Exemple #14
0
        public async Task Return_Empty_Imports_ForTextSource_ProjectItem()
        {
            //Assign
            var generator = new RazorSourceGenerator(RazorEngine.Create(), new EmbeddedRazorProject(typeof(Root)));

            //Act
            var projectItem = new TextSourceRazorProjectItem("key", "some content");
            IEnumerable <RazorSourceDocument> result = await generator.GetImportsAsync(projectItem);

            //Assert
            Assert.NotNull(result);
            Assert.Empty(result);
        }
Exemple #15
0
        public void Ensure_Namespaces_Are_Passed()
        {
            var namespaces = new HashSet <string>
            {
                "System.Diagnostics",
                "System.CodeDom"
            };

            var generator = new RazorSourceGenerator(RazorEngine.Create(), new EmbeddedRazorProject(typeof(Root)), namespaces);

            Assert.NotNull(generator.Namespaces);
            Assert.Equal(generator.Namespaces, namespaces);
        }
Exemple #16
0
        /// <summary>
        ///Creates RazorLightEngine with a custom RazorLightProject
        /// </summary>
        /// <param name="project">The project</param>
        /// <returns>Instance of RazorLightEngine</returns>
        public virtual RazorLightEngine Create(RazorLightProject project, RazorLightOptions options = null)
        {
            var razorOptions = options ?? new RazorLightOptions();

            var sourceGenerator = new RazorSourceGenerator(DefaultRazorEngine.Instance, project, razorOptions.Namespaces);

            var metadataReferenceManager = new DefaultMetadataReferenceManager(razorOptions.AdditionalMetadataReferences);
            var compiler = new RoslynCompilationService(metadataReferenceManager, Assembly.GetEntryAssembly());
            var templateFactoryProvider = new TemplateFactoryProvider(sourceGenerator, compiler, razorOptions);

            ICachingProvider cacheProvider = new MemoryCachingProvider();

            return(new RazorLightEngine(razorOptions, templateFactoryProvider, cacheProvider));
        }
Exemple #17
0
        public void DefaultImports_Created_On_Constructor()
        {
            var generator = new RazorSourceGenerator(
                RazorEngine.Create(),
                new EmbeddedRazorProject(typeof(RazorSourceGeneratorTest)));

            var defaultImports = generator.GetDefaultImportLines().ToList();

            Assert.NotEmpty(defaultImports);

            Assert.Contains(defaultImports, i => i == "@using System");
            Assert.Contains(defaultImports, i => i == "@using System.Threading.Tasks");
            Assert.Contains(defaultImports, i => i == "@using System.Collections.Generic");
            Assert.Contains(defaultImports, i => i == "@using System.Linq");
        }
        public async Task CreateCodeDocumentAsync_Throws_On_ProjectItem_Not_Exists()
        {
            var generator = new RazorSourceGenerator(DefaultRazorEngine.Instance, project: null);

            string templateKey = "Assets.Embedded.IDoNotExist.cshtml";

            var projectItem = new EmbeddedRazorProjectItem(typeof(Root), templateKey);

            Assert.False(projectItem.Exists);

            Func <Task> action = () => generator.CreateCodeDocumentAsync(projectItem);

            var exception = await Assert.ThrowsAsync <InvalidOperationException>(action);

            Assert.Equal($"{ nameof(RazorLightProjectItem)} of type {projectItem.GetType().FullName} with key {projectItem.Key} does not exist.", exception.Message);
        }
        public void Ensure_Throws_OnNull_Constructor_Dependencies()
        {
            var options         = new RazorLightOptions();
            var metadataManager = new DefaultMetadataReferenceManager();
            var assembly        = Assembly.GetCallingAssembly();
            var project         = new EmbeddedRazorProject(assembly);
            var compilerService = new RoslynCompilationService(metadataManager, assembly);
            var generator       = new RazorSourceGenerator(DefaultRazorEngine.Instance, project);

            Action p1 = new Action(() => { new RazorTemplateCompiler(null, compilerService, project, options); });
            Action p2 = new Action(() => { new RazorTemplateCompiler(generator, null, project, options); });
            Action p3 = new Action(() => { new RazorTemplateCompiler(generator, compilerService, null, options); });
            Action p4 = new Action(() => { new RazorTemplateCompiler(generator, compilerService, project, null); });

            Assert.Throws <ArgumentNullException>(p1);
            Assert.Throws <ArgumentNullException>(p2);
            Assert.Throws <ArgumentNullException>(p3);
            Assert.Throws <ArgumentNullException>(p4);
        }
Exemple #20
0
        public void Allow_Null_Project()
        {
            var generator = new RazorSourceGenerator(DefaultRazorEngine.Instance, project: null);

            Assert.NotNull(generator);
        }
Exemple #21
0
        public virtual RazorLightEngine Build()
        {
            options = options ?? new RazorLightOptions();
            project = project ?? new NoRazorProject();

            if (namespaces != null)
            {
                if (namespaces.Count > 0 && options.Namespaces.Count > 0)
                {
                    ThrowIfHasBeenSetExplicitly(nameof(namespaces));
                }

                options.Namespaces = namespaces;
            }

            if (dynamicTemplates != null)
            {
                if (dynamicTemplates.Count > 0 && options.DynamicTemplates.Count > 0)
                {
                    ThrowIfHasBeenSetExplicitly(nameof(dynamicTemplates));
                }

                options.DynamicTemplates = dynamicTemplates;
            }

            if (metadataReferences != null)
            {
                if (metadataReferences.Count > 0 && options.AdditionalMetadataReferences.Count > 0)
                {
                    ThrowIfHasBeenSetExplicitly(nameof(metadataReferences));
                }

                options.AdditionalMetadataReferences = metadataReferences;
            }

            if (excludedAssemblies != null)
            {
                if (excludedAssemblies.Count > 0 && options.ExcludedAssemblies.Count > 0)
                {
                    ThrowIfHasBeenSetExplicitly(nameof(excludedAssemblies));
                }

                options.ExcludedAssemblies = excludedAssemblies;
            }

            if (prerenderCallbacks != null)
            {
                if (prerenderCallbacks.Count > 0 && options.PreRenderCallbacks.Count > 0)
                {
                    ThrowIfHasBeenSetExplicitly(nameof(prerenderCallbacks));
                }

                options.PreRenderCallbacks = prerenderCallbacks;
            }

            if (cachingProvider != null)
            {
                if (options.CachingProvider != null)
                {
                    ThrowIfHasBeenSetExplicitly(nameof(cachingProvider));
                }

                options.CachingProvider = cachingProvider;
            }

            if (disableEncoding.HasValue)
            {
                if (options.DisableEncoding != null)
                {
                    ThrowIfHasBeenSetExplicitly(nameof(disableEncoding));
                }

                options.DisableEncoding = options.DisableEncoding ?? disableEncoding ?? false;
            }
            else
            {
                if (!options.DisableEncoding.HasValue)
                {
                    options.DisableEncoding = false;
                }
            }

            if (enableDebugMode.HasValue && options.EnableDebugMode.HasValue)
            {
                ThrowIfHasBeenSetExplicitly(nameof(enableDebugMode));
            }
            else
            {
                options.EnableDebugMode = options.EnableDebugMode ?? enableDebugMode ?? false;
            }

            var metadataReferenceManager = new DefaultMetadataReferenceManager(options.AdditionalMetadataReferences, options.ExcludedAssemblies);
            var assembly = operatingAssembly ?? Assembly.GetEntryAssembly();
            var compiler = new RoslynCompilationService(metadataReferenceManager, assembly);

            var sourceGenerator         = new RazorSourceGenerator(DefaultRazorEngine.Instance, project, options.Namespaces);
            var templateCompiler        = new RazorTemplateCompiler(sourceGenerator, compiler, project, options);
            var templateFactoryProvider = new TemplateFactoryProvider();

            var engineHandler = new EngineHandler(options, templateCompiler, templateFactoryProvider, cachingProvider);

            return(new RazorLightEngine(engineHandler));
        }