public void UpdateGuestProjectManager_ProjectChanged_ConfigurationChange()
        {
            // Arrange
            var oldHandle = new ProjectSnapshotHandleProxy(
                new Uri("vsls:/path/project.csproj"),
                RazorConfiguration.Default,
                "project",
                projectWorkspaceState: null);
            var newConfiguration = RazorConfiguration.Create(RazorLanguageVersion.Version_1_0, "Custom-1.0", Enumerable.Empty <RazorExtension>());
            var newHandle        = new ProjectSnapshotHandleProxy(
                oldHandle.FilePath,
                newConfiguration,
                oldHandle.RootNamespace,
                oldHandle.ProjectWorkspaceState);
            var synchronizationService = new ProjectSnapshotSynchronizationService(
                JoinableTaskFactory,
                SessionContext,
                Mock.Of <IProjectSnapshotManagerProxy>(),
                ProjectSnapshotManager);
            var hostProject = new HostProject("/guest/path/project.csproj", RazorConfiguration.Default, "project");

            ProjectSnapshotManager.ProjectAdded(hostProject);
            ProjectSnapshotManager.ProjectConfigurationChanged(hostProject);
            var args = new ProjectChangeEventProxyArgs(oldHandle, newHandle, ProjectProxyChangeKind.ProjectChanged);

            // Act
            synchronizationService.UpdateGuestProjectManager(args);

            // Assert
            var project = Assert.Single(ProjectSnapshotManager.Projects);

            Assert.Equal("/guest/path/project.csproj", project.FilePath);
            Assert.Same(newConfiguration, project.Configuration);
            Assert.Empty(project.TagHelpers);
        }
        public override RazorProjectEngine Create(RazorConfiguration configuration, RazorProjectFileSystem fileSystem, Action <RazorProjectEngineBuilder> configure)
        {
            if (fileSystem is null)
            {
                throw new ArgumentNullException(nameof(fileSystem));
            }

            // When we're running in the editor, the editor provides a configure delegate that will include
            // the editor settings and tag helpers.
            //
            // This service is only used in process in Visual Studio, and any other callers should provide these
            // things also.
            configure ??= ((b) => { });

            // The default configuration currently matches the newest MVC configuration.
            //
            // We typically want this because the language adds features over time - we don't want to a bunch of errors
            // to show up when a document is first opened, and then go away when the configuration loads, we'd prefer the opposite.
            configuration ??= s_defaultConfiguration;

            // If there's no factory to handle the configuration then fall back to a very basic configuration.
            //
            // This will stop a crash from happening in this case (misconfigured project), but will still make
            // it obvious to the user that something is wrong.
            var factory = SelectFactory(configuration) ?? _fallback;

            return(factory.Create(configuration, fileSystem, configure));
        }
 public override RazorProjectEngine Create(RazorConfiguration configuration, RazorProjectFileSystem fileSystem, Action <RazorProjectEngineBuilder> configure)
 {
     return(RazorProjectEngine.Create(configuration, fileSystem, b =>
     {
         RazorExtensions.Register(b);
     }));
 }
Beispiel #4
0
        private RazorProjectEngine CreateProjectEngine(RazorConfiguration configuration, MetadataReference[] references, Action <RazorProjectEngineBuilder>?configure)
        {
            return(RazorProjectEngine.Create(configuration, FileSystem, b =>
            {
                b.Phases.Insert(0, new ConfigureCodeRenderingPhase(LineEnding));

                configure?.Invoke(b);

                // Allow the test to do custom things with tag helpers, but do the default thing most of the time.
                if (!b.Features.OfType <ITagHelperFeature>().Any())
                {
                    b.Features.Add(new CompilationTagHelperFeature());
                    b.Features.Add(new DefaultMetadataReferenceFeature()
                    {
                        References = references,
                    });
                }

                b.Features.Add(new DefaultTypeNameFeature());
                b.SetCSharpLanguageVersion(CSharpParseOptions.LanguageVersion);

                // Decorate each import feature so we can normalize line endings.
                foreach (var feature in b.Features.OfType <IImportProjectFeature>().ToArray())
                {
                    b.Features.Remove(feature);
                    b.Features.Add(new NormalizedDefaultImportFeature(feature, LineEnding));
                }
            }));
        }
Beispiel #5
0
        public void Equals_ReturnsTrue_IfRazorConfigurationAreDifferentInstancesButEqualValues()
        {
            // Arrange
            var options1 = new RazorSourceGenerationOptions
            {
                CSharpLanguageVersion = LanguageVersion.Latest,
                Configuration         = RazorConfiguration.Create(RazorLanguageVersion.Parse("6.0"), "Default", Enumerable.Empty <RazorExtension>(), useConsolidatedMvcViews: true),
                GenerateMetadataSourceChecksumAttributes = true,
                RootNamespace = "Asp",
                SupportLocalizedComponentNames = true,
                SuppressRazorSourceGenerator   = true,
            };

            var options2 = new RazorSourceGenerationOptions
            {
                Configuration         = RazorConfiguration.Create(RazorLanguageVersion.Parse("6.0"), "Default", Enumerable.Empty <RazorExtension>(), useConsolidatedMvcViews: true),
                CSharpLanguageVersion = LanguageVersion.Latest,
                GenerateMetadataSourceChecksumAttributes = true,
                RootNamespace = "Asp",
                SupportLocalizedComponentNames = true,
                SuppressRazorSourceGenerator   = true,
            };

            // Act
            var equals = options1.Equals(options2);

            // Assert
            Assert.True(equals);
        }
        protected override Task <int> ExecuteCoreAsync()
        {
            if (!Parent.Checker.Check(ExtensionFilePaths.Values))
            {
                Error.WriteLine($"Extenions could not be loaded. See output for details.");
                return(Task.FromResult(ExitCodeFailure));
            }

            // Loading all of the extensions should succeed as the dependency checker will have already
            // loaded them.
            var extensions = new RazorExtension[ExtensionNames.Values.Count];

            for (var i = 0; i < ExtensionNames.Values.Count; i++)
            {
                extensions[i] = new AssemblyExtension(ExtensionNames.Values[i], Parent.Loader.LoadFromPath(ExtensionFilePaths.Values[i]));
            }

            var version       = RazorLanguageVersion.Parse(Version.Value());
            var configuration = RazorConfiguration.Create(version, Configuration.Value(), extensions);

            var result = ExecuteCore(
                configuration: configuration,
                projectDirectory: ProjectDirectory.Value(),
                outputFilePath: TagHelperManifest.Value(),
                assemblies: Assemblies.Values.ToArray());

            return(Task.FromResult(result));
        }
Beispiel #7
0
        // intentionally private - we don't want individual tests messing with the project engine
        private RazorProjectEngine CreateProjectEngine(RazorConfiguration configuration, MetadataReference[] references)
        {
            return(RazorProjectEngine.Create(configuration, FileSystem, b =>
            {
                b.SetRootNamespace(DefaultRootNamespace);

                // Turn off checksums, we're testing code generation.
                b.Features.Add(new SuppressChecksum());

                b.Features.Add(new TestImportProjectFeature(ImportItems));

                if (LineEnding != null)
                {
                    b.Phases.Insert(0, new ForceLineEndingPhase(LineEnding));
                }

                b.Features.Add(new CompilationTagHelperFeature());
                b.Features.Add(new DefaultMetadataReferenceFeature()
                {
                    References = references,
                });

                b.SetCSharpLanguageVersion(CSharpParseOptions.LanguageVersion);

                CompilerFeatures.Register(b);
            }));
        }
 public MSBuildProjectManagerTest()
 {
     CustomConfiguration = RazorConfiguration.Create(
         RazorLanguageVersion.Experimental,
         "Custom",
         Enumerable.Empty <RazorExtension>());
 }
Beispiel #9
0
        // Internal for testing
        internal static bool TryGetConfiguration(
            IImmutableDictionary <string, IProjectRuleSnapshot> state,
            out RazorConfiguration configuration)
        {
            if (!TryGetDefaultConfiguration(state, out var defaultConfiguration))
            {
                configuration = null;
                return(false);
            }

            if (!TryGetLanguageVersion(state, out var languageVersion))
            {
                configuration = null;
                return(false);
            }

            if (!TryGetConfigurationItem(defaultConfiguration, state, out var configurationItem))
            {
                configuration = null;
                return(false);
            }

            var extensionNames = GetExtensionNames(configurationItem);

            if (!TryGetExtensions(extensionNames, state, out var extensions))
            {
                configuration = null;
                return(false);
            }

            configuration = new ProjectSystemRazorConfiguration(languageVersion, configurationItem.Key, extensions);
            return(true);
        }
        // Internal for testing
        internal static bool TryGetConfiguration(
            IMSBuildEvaluatedPropertyCollection projectProperties,
            IEnumerable <IMSBuildItemEvaluated> projectItems,
            out RazorConfiguration configuration)
        {
            if (!TryGetDefaultConfiguration(projectProperties, out var defaultConfiguration))
            {
                configuration = null;
                return(false);
            }

            if (!TryGetLanguageVersion(projectProperties, out var languageVersion))
            {
                configuration = null;
                return(false);
            }

            if (!TryGetConfigurationItem(defaultConfiguration, projectItems, out var configurationItem))
            {
                configuration = null;
                return(false);
            }

            var extensionNames = GetExtensionNames(configurationItem);
            var extensions     = GetExtensions(extensionNames, projectItems);

            configuration = new ProjectSystemRazorConfiguration(languageVersion, configurationItem.Include, extensions);
            return(true);
        }
Beispiel #11
0
        public async Task ProjectWorkspaceStateChange_WithProjectWorkspaceState_CSharpLanguageVersionChange_DoesNotCacheOutput()
        {
            // Arrange
            var csharp8ValidConfiguration = RazorConfiguration.Create(RazorLanguageVersion.Version_3_0, HostProject.Configuration.ConfigurationName, HostProject.Configuration.Extensions);
            var hostProject            = new HostProject(TestProjectData.SomeProject.FilePath, csharp8ValidConfiguration, TestProjectData.SomeProject.RootNamespace);
            var originalWorkspaceState = new ProjectWorkspaceState(SomeTagHelpers, LanguageVersion.CSharp7);
            var original =
                ProjectState.Create(Workspace.Services, hostProject, originalWorkspaceState)
                .WithAddedHostDocument(HostDocument, () => Task.FromResult(TextAndVersion.Create(SourceText.From("@DateTime.Now"), VersionStamp.Default)));
            var changedWorkspaceState = new ProjectWorkspaceState(SomeTagHelpers, LanguageVersion.CSharp8);

            var(originalOutput, originalInputVersion, originalCSharpOutputVersion, originalHtmlOutputVersion) = await GetOutputAsync(original, HostDocument);

            // Act
            var state = original.WithProjectWorkspaceState(changedWorkspaceState);

            // Assert
            var(actualOutput, actualInputVersion, actualCSharpOutputVersion, actualHtmlOutputVersion) = await GetOutputAsync(state, HostDocument);

            Assert.NotSame(originalOutput, actualOutput);
            Assert.NotEqual(originalInputVersion, actualInputVersion);
            Assert.NotEqual(originalCSharpOutputVersion, actualCSharpOutputVersion);
            Assert.Equal(originalHtmlOutputVersion, actualHtmlOutputVersion);
            Assert.Equal(state.ProjectWorkspaceStateVersion, actualInputVersion);
        }
        static BlazorExtensionInitializer()
        {
            // RazorConfiguration is changing between 15.7 and preview2 builds of Razor, this is a reflection-based
            // workaround.
            DeclarationConfiguration = Create("BlazorDeclaration-0.1");
            DefaultConfiguration     = Create("Blazor-0.1");

            RazorConfiguration Create(string configurationName)
            {
                var args = new object[] { RazorLanguageVersion.Version_2_1, configurationName, Array.Empty <RazorExtension>(), };

                MethodInfo      method;
                ConstructorInfo constructor;

                if ((method = typeof(RazorConfiguration).GetMethod("Create", BindingFlags.Public | BindingFlags.Static)) != null)
                {
                    return((RazorConfiguration)method.Invoke(null, args));
                }
                else if ((constructor = typeof(RazorConfiguration).GetConstructors().FirstOrDefault()) != null)
                {
                    return((RazorConfiguration)constructor.Invoke(args));
                }
                else
                {
                    throw new InvalidOperationException("Can't create a configuration. This is bad.");
                }
            }
        }
            public SerializedProjectSnapshot(string filePath, RazorConfiguration configuration)
            {
                FilePath      = filePath;
                Configuration = configuration;

                Version = VersionStamp.Default;
            }
Beispiel #14
0
            public SerializedProjectSnapshot(string filePath, RazorConfiguration configuration, string rootNamespace)
            {
                FilePath      = filePath;
                Configuration = configuration;
                RootNamespace = rootNamespace;

                Version = VersionStamp.Default;
            }
Beispiel #15
0
 public CodeGenerationIntegrationTest()
     : base(generateBaselines: null)
 {
     Configuration = RazorConfiguration.Create(
         RazorLanguageVersion.Version_2_0,
         "MVC-2.1",
         new[] { new AssemblyExtension("MVC-2.1", typeof(ExtensionInitializer).Assembly) });
 }
 public RazorProjectEngine Create(RazorConfiguration configuration, RazorProjectFileSystem fileSystem, Action <RazorProjectEngineBuilder> configure)
 {
     return(RazorProjectEngine.Create(configuration, fileSystem, builder =>
     {
         var csharpLoweringIndex = builder.Phases.IndexOf(builder.Phases.OfType <IRazorCSharpLoweringPhase>().Single());
         builder.Phases[csharpLoweringIndex] = new UnsupportedCSharpLoweringPhase();
     }));
 }
 public CodeGenerationIntegrationTest()
     : base(generateBaselines: null, projectDirectoryHint: "Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X")
 {
     Configuration = RazorConfiguration.Create(
         RazorLanguageVersion.Version_2_0,
         "MVC-2.1",
         new[] { new AssemblyExtension("MVC-2.1", typeof(ExtensionInitializer).Assembly) });
 }
 public override RazorProjectEngine Create(RazorConfiguration configuration, RazorProjectFileSystem fileSystem, Action <RazorProjectEngineBuilder> configure)
 {
     return(Engine ?? RazorProjectEngine.Create(configuration, fileSystem, b =>
     {
         configure(b);
         Configure(b);
     }));
 }
Beispiel #19
0
        public RazorProjectEngine Create(RazorConfiguration configuration, RazorProjectFileSystem fileSystem, Action <RazorProjectEngineBuilder> configure)
        {
            return(RazorProjectEngine.Create(configuration, fileSystem, b =>
            {
                CompilerFeatures.Register(b);

                configure?.Invoke(b);
            }));
        }
Beispiel #20
0
        public override void UpdateProject(
            string filePath,
            RazorConfiguration configuration,
            string rootNamespace,
            ProjectWorkspaceState projectWorkspaceState,
            IReadOnlyList <DocumentSnapshotHandle> documents)
        {
            _foregroundDispatcher.AssertForegroundThread();

            var normalizedPath = _filePathNormalizer.Normalize(filePath);
            var project        = (DefaultProjectSnapshot)_projectSnapshotManagerAccessor.Instance.GetLoadedProject(normalizedPath);

            if (project == null)
            {
                // Never tracked the project to begin with, noop.
                _logger.LogInformation($"Failed to update untracked project '{filePath}'.");
                return;
            }

            UpdateProjectDocuments(documents, project.FilePath);

            if (!projectWorkspaceState.Equals(ProjectWorkspaceState.Default))
            {
                _logger.LogInformation($"Updating project '{filePath}' TagHelpers ({projectWorkspaceState.TagHelpers.Count}) and C# Language Version ({projectWorkspaceState.CSharpLanguageVersion}).");
            }

            _projectSnapshotManagerAccessor.Instance.ProjectWorkspaceStateChanged(project.FilePath, projectWorkspaceState);

            var currentHostProject   = project.HostProject;
            var currentConfiguration = currentHostProject.Configuration;

            if (currentConfiguration.ConfigurationName == configuration?.ConfigurationName &&
                currentHostProject.RootNamespace == rootNamespace)
            {
                _logger.LogTrace($"Updating project '{filePath}'. The project is already using configuration '{configuration.ConfigurationName}' and root namespace '{rootNamespace}'.");
                return;
            }

            if (configuration == null)
            {
                configuration = RazorDefaults.Configuration;
                _logger.LogInformation($"Updating project '{filePath}' to use Razor's default configuration ('{configuration.ConfigurationName}')'.");
            }
            else if (currentConfiguration.ConfigurationName != configuration.ConfigurationName)
            {
                _logger.LogInformation($"Updating project '{filePath}' to Razor configuration '{configuration.ConfigurationName}' with language version '{configuration.LanguageVersion}'.");
            }

            if (currentHostProject.RootNamespace != rootNamespace)
            {
                _logger.LogInformation($"Updating project '{filePath}''s root namespace to '{rootNamespace}'.");
            }

            var hostProject = new HostProject(project.FilePath, configuration, rootNamespace);

            _projectSnapshotManagerAccessor.Instance.ProjectConfigurationChanged(hostProject);
        }
Beispiel #21
0
        private IProjectEngineFactory CreateFactory(RazorConfiguration configuration, string factoryTypeName)
        {
            if (factoryTypeName == null)
            {
                return(null);
            }

            return((IProjectEngineFactory)Activator.CreateInstance(Type.GetType(factoryTypeName, throwOnError: true)));
        }
            public SerializedProjectSnapshot(string filePath, RazorConfiguration configuration, Project workspaceProject)
            {
                FilePath         = filePath;
                Configuration    = configuration;
                WorkspaceProject = workspaceProject;

                IsInitialized = true;
                Version       = VersionStamp.Default;
            }
    public DefaultRazorCodeGenerationOptionsBuilder(RazorConfiguration configuration, string fileKind)
    {
        if (configuration == null)
        {
            throw new ArgumentNullException(nameof(configuration));
        }

        Configuration = configuration;
        FileKind      = fileKind;
    }
Beispiel #24
0
    protected RazorProjectEngine CreateProjectEngine(Action <RazorProjectEngineBuilder> configure)
    {
        var configuration = RazorConfiguration.Create(Version, "test", Array.Empty <RazorExtension>());

        return(RazorProjectEngine.Create(configuration, RazorProjectFileSystem.Empty, b =>
        {
            ConfigureProjectEngine(b);
            configure?.Invoke(b);
        }));
    }
        public static RazorSourceGenerationContext Create(GeneratorExecutionContext context)
        {
            var globalOptions = context.AnalyzerConfigOptions.GlobalOptions;

            if (!globalOptions.TryGetValue("build_property.RootNamespace", out var rootNamespace))
            {
                rootNamespace = "ASP";
            }

            globalOptions.TryGetValue("build_property.DesignTimeBuild", out var designTimeBuild);
            if (!globalOptions.TryGetValue("build_property._RazorReferenceAssemblyTagHelpersOutputPath", out var refsTagHelperOutputCachePath))
            {
                throw new InvalidOperationException("_RazorReferenceAssemblyTagHelpersOutputPath is not specified.");
            }

            if (!globalOptions.TryGetValue("build_property.RazorLangVersion", out var razorLanguageVersionString) ||
                !RazorLanguageVersion.TryParse(razorLanguageVersionString, out var razorLanguageVersion))
            {
                context.ReportDiagnostic(Diagnostic.Create(
                                             RazorDiagnostics.InvalidRazorLangVersionDescriptor,
                                             Location.None,
                                             razorLanguageVersionString));

                return(null);
            }

            if (!globalOptions.TryGetValue("build_property.RazorConfiguration", out var configurationName))
            {
                configurationName = "default";
            }

            globalOptions.TryGetValue("build_property._RazorSourceGeneratorDebug", out var waitForDebugger);
            globalOptions.TryGetValue("build_property._RazorSourceGeneratorWriteGeneratedOutput", out var writeOutput);
            globalOptions.TryGetValue("build_property._RazorSourceGeneratorLog", out var enableLogging);

            var razorConfiguration = RazorConfiguration.Create(razorLanguageVersion, configurationName, Enumerable.Empty <RazorExtension>());

            var(razorFiles, cshtmlFiles) = GetRazorInputs(context);
            var fileSystem = GetVirtualFileSystem(razorFiles, cshtmlFiles);

            return(new RazorSourceGenerationContext
            {
                RootNamespace = rootNamespace,
                Configuration = razorConfiguration,
                FileSystem = fileSystem,
                RazorFiles = razorFiles,
                CshtmlFiles = cshtmlFiles,
                DesignTimeBuild = designTimeBuild == "true",
                RefsTagHelperOutputCachePath = refsTagHelperOutputCachePath,
                WaitForDebugger = waitForDebugger == "true",
                WriteGeneratedContent = writeOutput == "true",
                EnableLogging = enableLogging == "true"
            });
        }
 public MSBuildProjectManagerTest()
 {
     var projectInstanceEvaluator = new Mock<ProjectInstanceEvaluator>();
     projectInstanceEvaluator.Setup(instance => instance.Evaluate(It.IsAny<ProjectInstance>()))
         .Returns<ProjectInstance>(pi => pi);
     ProjectInstanceEvaluator = projectInstanceEvaluator.Object;
     CustomConfiguration = RazorConfiguration.Create(
         RazorLanguageVersion.Experimental,
         "Custom",
         Enumerable.Empty<RazorExtension>());
 }
        public RazorProjectEngine Create(RazorConfiguration configuration, RazorProjectFileSystem fileSystem, Action <RazorProjectEngineBuilder> configure)
        {
            return(RazorProjectEngine.Create(configuration, fileSystem, b =>
            {
                configure?.Invoke(b);
                new BlazorExtensionInitializer().Initialize(b);

                var classifier = b.Features.OfType <ComponentDocumentClassifierPass>().Single();
                classifier.MangleClassNames = true;
            }));
        }
Beispiel #28
0
            public SerializedProjectSnapshot(string filePath, RazorConfiguration configuration, Project workspaceProject)
            {
                FilePath         = filePath;
                Configuration    = configuration;
                HostProject      = new HostProject(filePath, configuration);
                WorkspaceProject = workspaceProject;
                TagHelpers       = Array.Empty <TagHelperDescriptor>();

                IsInitialized = true;
                Version       = VersionStamp.Default;
            }
Beispiel #29
0
        private RazorEngine CreateEngine()
        {
            var configuration = RazorConfiguration.Create(RazorLanguageVersion.Version_1_1, "test", Array.Empty <RazorExtension>());

            return(RazorProjectEngine.Create(configuration, RazorProjectFileSystem.Empty, b =>
            {
                // Notice we're not registering the InjectDirective.Pass here so we can run it on demand.
                b.AddDirective(InjectDirective.Directive);
                b.AddDirective(ModelDirective.Directive);
            }).Engine);
        }
Beispiel #30
0
    public DefaultRazorParserOptionsBuilder(RazorConfiguration configuration, string fileKind)
    {
        if (configuration == null)
        {
            throw new ArgumentNullException(nameof(configuration));
        }

        Configuration   = configuration;
        LanguageVersion = configuration.LanguageVersion;
        FileKind        = fileKind;
    }