コード例 #1
0
        public void EnsureOptions_ConfiguresDefaultCompilationOptions()
        {
            // Arrange
            var hostingEnvironment = Mock.Of <IHostingEnvironment>(h => h.EnvironmentName == "Development");
            var compiler           = new CSharpCompiler(ReferenceManager, hostingEnvironment);

            // Act & Assert
            var compilationOptions = compiler.CSharpCompilationOptions;

            Assert.False(compilationOptions.AllowUnsafe);
            Assert.Equal(ReportDiagnostic.Default, compilationOptions.GeneralDiagnosticOption);
            Assert.Equal(OptimizationLevel.Debug, compilationOptions.OptimizationLevel);
            Assert.Collection(compilationOptions.SpecificDiagnosticOptions.OrderBy(d => d.Key),
                              item =>
            {
                Assert.Equal("CS1701", item.Key);
                Assert.Equal(ReportDiagnostic.Suppress, item.Value);
            },
                              item =>
            {
                Assert.Equal("CS1702", item.Key);
                Assert.Equal(ReportDiagnostic.Suppress, item.Value);
            },
                              item =>
            {
                Assert.Equal("CS1705", item.Key);
                Assert.Equal(ReportDiagnostic.Suppress, item.Value);
            });
        }
コード例 #2
0
        public SharedRazorViewCompiler(
            IFileProvider fileProvider,
            RazorTemplateEngine templateEngine,
            CSharpCompiler csharpCompiler,
            Action <RoslynCompilationContext> compilationCallback,
            IList <CompiledViewDescriptor> precompiledViews,
            ILogger logger)
        {
            if (fileProvider == null)
            {
                throw new ArgumentNullException(nameof(fileProvider));
            }

            if (templateEngine == null)
            {
                throw new ArgumentNullException(nameof(templateEngine));
            }

            if (csharpCompiler == null)
            {
                throw new ArgumentNullException(nameof(csharpCompiler));
            }

            if (compilationCallback == null)
            {
                throw new ArgumentNullException(nameof(compilationCallback));
            }

            if (precompiledViews == null)
            {
                throw new ArgumentNullException(nameof(precompiledViews));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            _fileProvider        = fileProvider;
            _templateEngine      = templateEngine;
            _csharpCompiler      = csharpCompiler;
            _compilationCallback = compilationCallback;
            _logger = logger;

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

            _precompiledViewLookup = new Dictionary <string, Task <CompiledViewDescriptor> >(
                precompiledViews.Count,
                StringComparer.OrdinalIgnoreCase);

            foreach (var precompiledView in precompiledViews)
            {
                if (_precompiledViewLookup.TryGetValue(precompiledView.RelativePath, out var otherValue))
                {
                    throw new InvalidOperationException("A precompiled view with the same name already exists: " + otherValue.Result.RelativePath);
                }

                _precompiledViewLookup.Add(precompiledView.RelativePath, Task.FromResult(precompiledView));
            }
        }
コード例 #3
0
 /// <summary>
 /// Initalizes a new instance of the <see cref="DefaultRoslynCompilationService"/> class.
 /// </summary>
 /// <param name="compiler">The <see cref="CSharpCompiler"/>.</param>
 /// <param name="optionsAccessor">Accessor to <see cref="RazorViewEngineOptions"/>.</param>
 /// <param name="fileProviderAccessor">The <see cref="IRazorViewEngineFileProviderAccessor"/>.</param>
 /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
 public DefaultRoslynCompilationService(
     CSharpCompiler compiler,
     IRazorViewEngineFileProviderAccessor fileProviderAccessor,
     IOptions <RazorViewEngineOptions> optionsAccessor,
     ILoggerFactory loggerFactory)
 {
     _compiler            = compiler;
     _fileProvider        = fileProviderAccessor.FileProvider;
     _compilationCallback = optionsAccessor.Value.CompilationCallback;
     _logger = loggerFactory.CreateLogger <DefaultRoslynCompilationService>();
 }
コード例 #4
0
        public void GetCompilationOptions_ReturnsDefaultOptionsIfApplicationNameIsNullOrEmpty(string name)
        {
            // Arrange
            var hostingEnvironment = Mock.Of <IHostingEnvironment>(e => e.ApplicationName == name);
            var compiler           = new CSharpCompiler(ReferenceManager, hostingEnvironment);

            // Act
            var options = compiler.GetDependencyContextCompilationOptions();

            // Assert
            Assert.Same(DependencyContextCompilationOptions.Default, options);
        }
コード例 #5
0
        public void EnsureOptions_ConfiguresDefaultParseOptions()
        {
            // Arrange
            var hostingEnvironment = Mock.Of <IHostingEnvironment>(h => h.EnvironmentName == "Development");
            var compiler           = new CSharpCompiler(ReferenceManager, hostingEnvironment);

            // Act & Assert
            var parseOptions = compiler.ParseOptions;

            Assert.Equal(LanguageVersion.CSharp7, parseOptions.LanguageVersion);
            Assert.Equal(new[] { "DEBUG" }, parseOptions.PreprocessorSymbolNames);
        }
コード例 #6
0
        public void Constructor_SetsCompilationOptionsFromDependencyContext()
        {
            // Arrange
            var hostingEnvironment = new Mock <IHostingEnvironment>();

            hostingEnvironment.SetupGet(e => e.ApplicationName)
            .Returns(GetType().GetTypeInfo().Assembly.GetName().Name);
            var compiler = new CSharpCompiler(ReferenceManager, hostingEnvironment.Object);

            // Act & Assert
            var parseOptions = compiler.ParseOptions;

            Assert.Contains("SOME_TEST_DEFINE", parseOptions.PreprocessorSymbolNames);
        }
コード例 #7
0
        public void EnsureOptions_SetsPreprocessorSymbols(string environment, string expectedConfiguration)
        {
            // Arrange
            var options            = new RazorViewEngineOptions();
            var hostingEnvironment = new Mock <IHostingEnvironment>();

            hostingEnvironment.SetupGet(e => e.EnvironmentName)
            .Returns(environment);
            var compiler = new CSharpCompiler(ReferenceManager, hostingEnvironment.Object);

            // Act & Assert
            var parseOptions = compiler.ParseOptions;

            Assert.Equal(new[] { expectedConfiguration }, parseOptions.PreprocessorSymbolNames);
        }
コード例 #8
0
        public void GetCompilationOptions_ReturnsDefaultOptionsIfApplicationDoesNotHaveDependencyContext()
        {
            // Arrange
            var hostingEnvironment = new Mock <IHostingEnvironment>();

            hostingEnvironment.SetupGet(e => e.ApplicationName)
            .Returns(typeof(Controller).GetTypeInfo().Assembly.GetName().Name);
            var compiler = new CSharpCompiler(ReferenceManager, hostingEnvironment.Object);

            // Act
            var options = compiler.GetDependencyContextCompilationOptions();

            // Assert
            Assert.Same(DependencyContextCompilationOptions.Default, options);
        }
コード例 #9
0
        public RazorViewCompilerProvider(
            ApplicationPartManager applicationPartManager,
            RazorProjectEngine razorProjectEngine,
            IRazorViewEngineFileProviderAccessor fileProviderAccessor,
            CSharpCompiler csharpCompiler,
            IOptions <RazorViewEngineOptions> viewEngineOptionsAccessor,
            ILoggerFactory loggerFactory)
        {
            _applicationPartManager = applicationPartManager;
            _razorProjectEngine     = razorProjectEngine;
            _fileProviderAccessor   = fileProviderAccessor;
            _csharpCompiler         = csharpCompiler;
            _viewEngineOptions      = viewEngineOptionsAccessor.Value;

            _logger         = loggerFactory.CreateLogger <RazorViewCompiler>();
            _createCompiler = CreateCompiler;
        }
コード例 #10
0
        public void Constructor_SetsOptimizationLevelBasedOnEnvironment(
            string environment,
            OptimizationLevel expected)
        {
            // Arrange
            var options            = new RazorViewEngineOptions();
            var hostingEnvironment = new Mock <IHostingEnvironment>();

            hostingEnvironment.SetupGet(e => e.EnvironmentName)
            .Returns(environment);
            var compiler = new CSharpCompiler(ReferenceManager, hostingEnvironment.Object);

            // Act & Assert
            var compilationOptions = compiler.CSharpCompilationOptions;

            Assert.Equal(expected, compilationOptions.OptimizationLevel);
        }
コード例 #11
0
        private static DefaultRoslynCompilationService GetRoslynCompilationService(
            ApplicationPartManager partManager = null,
            RazorViewEngineOptions options     = null,
            IFileProvider fileProvider         = null)
        {
            partManager = partManager ?? GetApplicationPartManager();
            options     = options ?? GetOptions();
            var optionsAccessor  = GetAccessor(options);
            var referenceManager = new RazorReferenceManager(partManager, optionsAccessor);
            var compiler         = new CSharpCompiler(referenceManager, optionsAccessor);

            return(new DefaultRoslynCompilationService(
                       compiler,
                       GetFileProviderAccessor(fileProvider),
                       optionsAccessor,
                       NullLoggerFactory.Instance));
        }
コード例 #12
0
 public TestRazorViewCompiler(
     TestFileProvider fileProvider,
     RazorProjectEngine projectEngine,
     CSharpCompiler csharpCompiler,
     Action <RoslynCompilationContext> compilationCallback,
     IList <CompiledViewDescriptor> precompiledViews,
     Func <string, CompiledViewDescriptor> compile = null) :
     base(fileProvider, projectEngine, csharpCompiler, compilationCallback, precompiledViews, new MemoryCache(new MemoryCacheOptions()), NullLogger.Instance)
 {
     Compile = compile;
     if (Compile == null)
     {
         Compile = path => new CompiledViewDescriptor
         {
             RelativePath  = path,
             ViewAttribute = new RazorViewAttribute(path, typeof(object)),
         };
     }
 }
コード例 #13
0
        private static TestRazorViewCompiler GetViewCompiler(
            TestFileProvider fileProvider = null,
            Action <RoslynCompilationContext> compilationCallback = null,
#pragma warning disable CS0618 // Type or member is obsolete
            RazorReferenceManager referenceManager = null,
#pragma warning restore CS0618 // Type or member is obsolete
            IList <CompiledViewDescriptor> precompiledViews = null,
            CSharpCompiler csharpCompiler = null)
        {
            fileProvider = fileProvider ?? new TestFileProvider();
            var accessor = Mock.Of <IRazorViewEngineFileProviderAccessor>(a => a.FileProvider == fileProvider);

            compilationCallback = compilationCallback ?? (_ => { });
            var options = Options.Create(new RazorViewEngineOptions());

            if (referenceManager == null)
            {
                referenceManager = CreateReferenceManager(options);
            }

            precompiledViews = precompiledViews ?? Array.Empty <CompiledViewDescriptor>();

            var hostingEnvironment = Mock.Of <IHostingEnvironment>(e => e.ContentRootPath == "BasePath");
            var fileSystem         = new FileProviderRazorProjectFileSystem(accessor, hostingEnvironment);
            var projectEngine      = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder =>
            {
                RazorExtensions.Register(builder);
            });

            csharpCompiler = csharpCompiler ?? new CSharpCompiler(referenceManager, hostingEnvironment);

            var viewCompiler = new TestRazorViewCompiler(
                fileProvider,
                projectEngine,
                csharpCompiler,
                compilationCallback,
                precompiledViews);

            return(viewCompiler);
        }
コード例 #14
0
        public RazorViewCompiler(
            IFileProvider fileProvider,
            RazorProjectEngine projectEngine,
            CSharpCompiler csharpCompiler,
            Action <RoslynCompilationContext> compilationCallback,
            IList <CompiledViewDescriptor> precompiledViews,
            IMemoryCache cache,
            ILogger logger)
        {
            if (fileProvider == null)
            {
                throw new ArgumentNullException(nameof(fileProvider));
            }

            if (projectEngine == null)
            {
                throw new ArgumentNullException(nameof(projectEngine));
            }

            if (csharpCompiler == null)
            {
                throw new ArgumentNullException(nameof(csharpCompiler));
            }

            if (compilationCallback == null)
            {
                throw new ArgumentNullException(nameof(compilationCallback));
            }

            if (precompiledViews == null)
            {
                throw new ArgumentNullException(nameof(precompiledViews));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            _fileProvider        = fileProvider;
            _projectEngine       = projectEngine;
            _csharpCompiler      = csharpCompiler;
            _compilationCallback = compilationCallback;
            _logger = logger;


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

            // 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.
            _cache = cache;

            // 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, CompiledViewDescriptor>(
                precompiledViews.Count,
                StringComparer.OrdinalIgnoreCase);

            foreach (var precompiledView in precompiledViews)
            {
                logger.ViewCompilerLocatedCompiledView(precompiledView.RelativePath);

                if (!_precompiledViews.ContainsKey(precompiledView.RelativePath))
                {
                    // View ordering has precedence semantics, a view with a higher precedence was
                    // already added to the list.
                    _precompiledViews.Add(precompiledView.RelativePath, precompiledView);
                }
            }

            if (_precompiledViews.Count == 0)
            {
                logger.ViewCompilerNoCompiledViewsFound();
            }
        }
コード例 #15
0
ファイル: RazorViewCompiler.cs プロジェクト: jo-ninja/Mvc
        public RazorViewCompiler(
            IFileProvider fileProvider,
            RazorProjectEngine projectEngine,
            CSharpCompiler csharpCompiler,
            Action <RoslynCompilationContext> compilationCallback,
            IList <CompiledViewDescriptor> precompiledViews,
            ILogger logger)
        {
            if (fileProvider == null)
            {
                throw new ArgumentNullException(nameof(fileProvider));
            }

            if (projectEngine == null)
            {
                throw new ArgumentNullException(nameof(projectEngine));
            }

            if (csharpCompiler == null)
            {
                throw new ArgumentNullException(nameof(csharpCompiler));
            }

            if (compilationCallback == null)
            {
                throw new ArgumentNullException(nameof(compilationCallback));
            }

            if (precompiledViews == null)
            {
                throw new ArgumentNullException(nameof(precompiledViews));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            _fileProvider        = fileProvider;
            _projectEngine       = projectEngine;
            _csharpCompiler      = csharpCompiler;
            _compilationCallback = compilationCallback;
            _logger = logger;

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

            // 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.
            _cache = new MemoryCache(new MemoryCacheOptions());

            // We need to validate that the all of the precompiled views are unique by path (case-insenstive).
            // 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, CompiledViewDescriptor>(
                precompiledViews.Count,
                StringComparer.OrdinalIgnoreCase);

            foreach (var precompiledView in precompiledViews)
            {
                if (_precompiledViews.TryGetValue(precompiledView.RelativePath, out var otherValue))
                {
                    var message = string.Join(
                        Environment.NewLine,
                        Resources.RazorViewCompiler_ViewPathsDifferOnlyInCase,
                        otherValue.RelativePath,
                        precompiledView.RelativePath);
                    throw new InvalidOperationException(message);
                }

                _precompiledViews.Add(precompiledView.RelativePath, precompiledView);
            }
        }
コード例 #16
0
ファイル: RazorViewCompiler.cs プロジェクト: Nishadks1/Mvc-1
        public RazorViewCompiler(
            IFileProvider fileProvider,
            RazorTemplateEngine templateEngine,
            CSharpCompiler csharpCompiler,
            Action <RoslynCompilationContext> compilationCallback,
            IList <CompiledViewDescriptor> precompiledViews,
            ILogger logger)
        {
            if (fileProvider == null)
            {
                throw new ArgumentNullException(nameof(fileProvider));
            }

            if (templateEngine == null)
            {
                throw new ArgumentNullException(nameof(templateEngine));
            }

            if (csharpCompiler == null)
            {
                throw new ArgumentNullException(nameof(csharpCompiler));
            }

            if (compilationCallback == null)
            {
                throw new ArgumentNullException(nameof(compilationCallback));
            }

            if (precompiledViews == null)
            {
                throw new ArgumentNullException(nameof(precompiledViews));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            _fileProvider        = fileProvider;
            _templateEngine      = templateEngine;
            _csharpCompiler      = csharpCompiler;
            _compilationCallback = compilationCallback;
            _logger = logger;

            _normalizedPathLookup = new ConcurrentDictionary <string, string>(StringComparer.Ordinal);
            _cache = new MemoryCache(new MemoryCacheOptions());

            _precompiledViewLookup = new Dictionary <string, Task <CompiledViewDescriptor> >(
                precompiledViews.Count,
                StringComparer.OrdinalIgnoreCase);

            foreach (var precompiledView in precompiledViews)
            {
                if (_precompiledViewLookup.TryGetValue(precompiledView.RelativePath, out var otherValue))
                {
                    var message = string.Join(
                        Environment.NewLine,
                        Resources.RazorViewCompiler_ViewPathsDifferOnlyInCase,
                        otherValue.Result.RelativePath,
                        precompiledView.RelativePath);
                    throw new InvalidOperationException(message);
                }

                _precompiledViewLookup.Add(precompiledView.RelativePath, Task.FromResult(precompiledView));
            }
        }