Ejemplo n.º 1
0
        public OOPTagHelperResolverTest()
        {
            HostProject_For_2_0 = new HostProject("Test.csproj", FallbackRazorConfiguration.MVC_2_0);
            HostProject_For_NonSerializableConfiguration = new HostProject(
                "Test.csproj",
                new ProjectSystemRazorConfiguration(RazorLanguageVersion.Version_2_1, "Blazor-0.1", Array.Empty <RazorExtension>()));

            CustomFactories = new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>[]
            {
                new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>(
                    () => new LegacyProjectEngineFactory_2_0(),
                    typeof(LegacyProjectEngineFactory_2_0).GetCustomAttribute <ExportCustomProjectEngineFactoryAttribute>()),

                // We don't really use this factory, we just use it to ensure that the call is going to go out of process.
                new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>(
                    () => new LegacyProjectEngineFactory_2_1(),
                    new ExportCustomProjectEngineFactoryAttribute("Blazor-0.1")
                {
                    SupportsSerialization = false,
                }),
            };

            FallbackFactory = new FallbackProjectEngineFactory();

            Workspace = new AdhocWorkspace();

            var info = ProjectInfo.Create(ProjectId.CreateNewId("Test"), VersionStamp.Default, "Test", "Test", LanguageNames.CSharp, filePath: "Test.csproj");

            WorkspaceProject = Workspace.CurrentSolution.AddProject(info).GetProject(info.Id);

            ErrorReporter  = new DefaultErrorReporter();
            ProjectManager = new TestProjectSnapshotManager(Workspace);
            EngineFactory  = new DefaultProjectSnapshotProjectEngineFactory(FallbackFactory, CustomFactories);
        }
        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 void UpdateGuestProjectManager_ProjectChanged_ProjectWorkspaceStateChange()
        {
            // Arrange
            var oldHandle = new ProjectSnapshotHandleProxy(
                new Uri("vsls:/path/project.csproj"),
                RazorConfiguration.Default,
                "project",
                ProjectWorkspaceState.Default);
            var newProjectWorkspaceState = ProjectWorkspaceStateWithTagHelpers;
            var newHandle = new ProjectSnapshotHandleProxy(
                oldHandle.FilePath,
                oldHandle.Configuration,
                oldHandle.RootNamespace,
                newProjectWorkspaceState);
            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.ProjectWorkspaceStateChanged(hostProject.FilePath, oldHandle.ProjectWorkspaceState);
            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(RazorConfiguration.Default, project.Configuration);
            Assert.Same(newProjectWorkspaceState.TagHelpers, project.TagHelpers);
        }
        public DefaultProjectResolver(
            ForegroundDispatcher foregroundDispatcher,
            FilePathNormalizer filePathNormalizer,
            RazorConfigurationResolver configurationResolver,
            ProjectSnapshotManagerAccessor projectSnapshotManagerAccessor)
        {
            if (foregroundDispatcher == null)
            {
                throw new ArgumentNullException(nameof(foregroundDispatcher));
            }

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

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

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

            _foregroundDispatcher           = foregroundDispatcher;
            _filePathNormalizer             = filePathNormalizer;
            _projectSnapshotManagerAccessor = projectSnapshotManagerAccessor;

            var miscellaneousProjectPath = Path.Combine(TempDirectory.Instance.DirectoryPath, "__MISC_RAZOR_PROJECT__");

            _miscellaneousHostProject = new HostProject(miscellaneousProjectPath, configurationResolver.Default);
        }
        public ProjectSnapshotManagerBenchmarkBase()
        {
            var current = new DirectoryInfo(AppContext.BaseDirectory);

            while (current != null && !File.Exists(Path.Combine(current.FullName, "Razor.sln")))
            {
                current = current.Parent;
            }

            var root        = current;
            var projectRoot = Path.Combine(root.FullName, "test", "testapps", "LargeProject");

            HostProject = new HostProject(Path.Combine(projectRoot, "LargeProject.csproj"), FallbackRazorConfiguration.MVC_2_1);

            TextLoaders = new TextLoader[4];
            for (var i = 0; i < 4; i++)
            {
                var filePath = Path.Combine(projectRoot, "Views", "Home", $"View00{i % 4}.cshtml");
                var text     = SourceText.From(filePath, encoding: null);
                TextLoaders[i] = TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create()));
            }

            Documents = new HostDocument[100];
            for (var i = 0; i < Documents.Length; i++)
            {
                var filePath = Path.Combine(projectRoot, "Views", "Home", $"View00{i % 4}.cshtml");
                Documents[i] = new HostDocument(filePath, $"/Views/Home/View00{i}.cshtml", FileKinds.Legacy);
            }

            var tagHelpers = Path.Combine(root.FullName, "benchmarks", "Microsoft.AspNetCore.Razor.Performance", "taghelpers.json");

            TagHelperResolver = new StaticTagHelperResolver(ReadTagHelpers(tagHelpers));
        }
        public void UpdateProject_KnownDocuments()
        {
            // Arrange
            var projectManager = TestProjectSnapshotManager.Create(Dispatcher);
            var hostProject    = new HostProject("/path/to/project.csproj", RazorConfiguration.Default, "TestRootNamespace");

            projectManager.ProjectAdded(hostProject);
            var document = new HostDocument("/path/to/file.cshtml", "file.cshtml", FileKinds.Legacy);

            projectManager.DocumentAdded(hostProject, document, Mock.Of <TextLoader>());
            var projectService = CreateProjectService(Mock.Of <ProjectResolver>(), projectManager);
            var newDocument    = new DocumentSnapshotHandle(document.FilePath, document.TargetPath, document.FileKind);

            projectManager.AllowNotifyListeners = true;
            projectManager.Changed += (sender, args) =>
            {
                if (args.Kind == ProjectChangeKind.DocumentRemoved ||
                    args.Kind == ProjectChangeKind.DocumentChanged ||
                    args.Kind == ProjectChangeKind.DocumentAdded)
                {
                    throw new XunitException("Should have nooped");
                }
            };

            // Act & Assert
            projectService.UpdateProject(hostProject.FilePath, hostProject.Configuration, hostProject.RootNamespace, ProjectWorkspaceState.Default, new[] { newDocument });
        }
        protected override async Task OnProjectChangedAsync()
        {
            ForegroundDispatcher.AssertBackgroundThread();

            await ExecuteWithLockAsync(async() =>
            {
                var referencedAssemblies = await DotNetProject.GetReferencedAssemblies(ConfigurationSelector.Default);
                var mvcReference         = referencedAssemblies.FirstOrDefault(IsMvcAssembly);

                if (mvcReference == null)
                {
                    // Ok we can't find an MVC version. Let's assume this project isn't using Razor then.
                    await UpdateHostProjectUnsafeAsync(null).ConfigureAwait(false);
                    return;
                }

                var version = GetAssemblyVersion(mvcReference.FilePath);
                if (version == null)
                {
                    // Ok we can't find an MVC version. Let's assume this project isn't using Razor then.
                    await UpdateHostProjectUnsafeAsync(null).ConfigureAwait(false);
                    return;
                }

                var configuration = FallbackRazorConfiguration.SelectConfiguration(version);
                var hostProject   = new HostProject(DotNetProject.FileName.FullPath, configuration, rootNamespace: null);
                await UpdateHostProjectUnsafeAsync(hostProject).ConfigureAwait(false);
            });
        }
        private void UpdateDocuments(HostProject hostProject, IEnumerable <IMSBuildItemEvaluated> projectItems)
        {
            var projectDirectory  = Path.GetDirectoryName(hostProject.FilePath);
            var documentFilePaths = GetRazorDocuments(projectDirectory, projectItems);

            var oldFiles     = _currentRazorFilePaths;
            var newFiles     = documentFilePaths.ToImmutableHashSet();
            var addedFiles   = newFiles.Except(oldFiles);
            var removedFiles = oldFiles.Except(newFiles);

            _currentRazorFilePaths = documentFilePaths;

            _ = ProjectSnapshotManagerDispatcher.RunOnDispatcherThreadAsync(() =>
            {
                foreach (var document in removedFiles)
                {
                    RemoveDocument(hostProject, document);
                }

                foreach (var document in addedFiles)
                {
                    var relativeFilePath = document.Substring(projectDirectory.Length + 1);
                    AddDocument(hostProject, document, relativeFilePath);
                }
            },
                                                                            CancellationToken.None);
        }
Ejemplo n.º 9
0
        public DefaultVisualStudioDocumentTrackerTest()
        {
            RazorCoreContentType = Mock.Of <IContentType>(c => c.IsOfType(RazorLanguage.ContentType) == true);
            TextBuffer           = Mock.Of <ITextBuffer>(b => b.ContentType == RazorCoreContentType);

            FilePath    = TestProjectData.SomeProjectFile1.FilePath;
            ProjectPath = TestProjectData.SomeProject.FilePath;

            ImportDocumentManager   = Mock.Of <ImportDocumentManager>();
            WorkspaceEditorSettings = new DefaultWorkspaceEditorSettings(Mock.Of <ForegroundDispatcher>(), Mock.Of <EditorSettingsManager>());

            SomeTagHelpers = new List <TagHelperDescriptor>()
            {
                TagHelperDescriptorBuilder.Create("test", "test").Build(),
            };

            ProjectManager = new TestProjectSnapshotManager(Dispatcher, Workspace)
            {
                AllowNotifyListeners = true
            };

            HostProject        = new HostProject(ProjectPath, FallbackRazorConfiguration.MVC_2_1);
            UpdatedHostProject = new HostProject(ProjectPath, FallbackRazorConfiguration.MVC_2_0);
            OtherHostProject   = new HostProject(TestProjectData.AnotherProject.FilePath, FallbackRazorConfiguration.MVC_2_0);

            DocumentTracker = new DefaultVisualStudioDocumentTracker(
                Dispatcher,
                FilePath,
                ProjectPath,
                ProjectManager,
                WorkspaceEditorSettings,
                Workspace,
                TextBuffer,
                ImportDocumentManager);
        }
        protected override async Task OnProjectChangedAsync()
        {
            await ExecuteWithLockAsync(async() =>
            {
                var projectProperties = DotNetProject.MSBuildProject.EvaluatedProperties;
                var projectItems      = DotNetProject.MSBuildProject.EvaluatedItems;

                if (TryGetIntermediateOutputPath(projectProperties, out var intermediatePath))
                {
                    var projectConfigurationFile = Path.Combine(intermediatePath, _languageServerFeatureOptions.ProjectConfigurationFileName);
                    ProjectConfigurationFilePathStore.Set(DotNetProject.FileName.FullPath, projectConfigurationFile);
                }

                if (TryGetConfiguration(projectProperties, projectItems, out var configuration))
                {
                    TryGetRootNamespace(projectProperties, out var rootNamespace);
                    var hostProject = new HostProject(DotNetProject.FileName.FullPath, configuration, rootNamespace);
                    await UpdateHostProjectUnsafeAsync(hostProject).ConfigureAwait(false);
                    UpdateDocuments(hostProject, projectItems);
                }
                else
                {
                    // Ok we can't find a configuration. Let's assume this project isn't using Razor then.
                    await UpdateHostProjectUnsafeAsync(null).ConfigureAwait(false);
                }
            });
        }
Ejemplo n.º 11
0
        private void AttachToDocument(uint docCookie, string moniker)
        {
            _foregroundThreadAffinitization.AssertIsForeground();

            var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
            var textBuffer   = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);

            if (_fileTrackingMetadataAsSourceService.TryAddDocumentToWorkspace(moniker, textBuffer))
            {
                // We already added it, so we will keep it excluded from the misc files workspace
                return;
            }

            // This should always succeed since we only got here if we already confirmed the moniker is acceptable
            var languageInformation = TryGetLanguageInformation(moniker);

            Contract.ThrowIfNull(languageInformation);
            var parseOptions = languageInformation.ParseOptions;

            if (Path.GetExtension(moniker) == languageInformation.ScriptExtension)
            {
                parseOptions = parseOptions.WithKind(SourceCodeKind.Script);
            }

            // First, create the project
            var hostProject = new HostProject(this, CurrentSolution.Id, languageInformation.LanguageName, parseOptions, _metadataReferences);

            // Now try to find the document. We accept any text buffer, since we've already verified it's an appropriate file in ShouldIncludeFile.
            var document = _documentProvider.TryGetDocumentForFile(
                hostProject,
                moniker,
                parseOptions.Kind,
                getFolderNames: _ => SpecializedCollections.EmptyReadOnlyList <string>(),
                canUseTextBuffer: _ => true);

            // If the buffer has not yet been initialized, we won't get a document.
            if (document == null)
            {
                return;
            }

            // Since we have a document, we can do the rest of the project setup.
            _hostProjects.Add(hostProject.Id, hostProject);
            OnProjectAdded(hostProject.CreateProjectInfoForCurrentState());

            OnDocumentAdded(document.GetInitialState());
            hostProject.Document = document;

            // Notify the document provider, so it knows the document is now open and a part of
            // the project
            _documentProvider.NotifyDocumentRegisteredToProjectAndStartToRaiseEvents(document);

            Contract.ThrowIfFalse(document.IsOpen);

            var buffer = document.GetOpenTextBuffer();

            OnDocumentOpened(document.Id, document.GetOpenTextContainer());

            _docCookiesToHostProject.Add(docCookie, hostProject);
        }
Ejemplo n.º 12
0
        // Adapted from DocumentExcerptServiceTestBase's InitializeDocument.
        // Adds the text to a ProjectSnapshot, generates code, and updates the workspace.
        private Document InitializeDocument(SourceText sourceText)
        {
            var baseDirectory = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "c:\\users\\example\\src" : "/home/example";
            var hostProject   = new HostProject(
                Path.Combine(baseDirectory, "SomeProject", "SomeProject.csproj"), RazorConfiguration.Default, "SomeProject");
            var hostDocument = new HostDocument(
                Path.Combine(baseDirectory, "SomeProject", "File1.cshtml"), "File1.cshtml", FileKinds.Legacy);

            var project = new DefaultProjectSnapshot(
                ProjectState.Create(Workspace.Services, hostProject)
                .WithAddedHostDocument(hostDocument, () => Task.FromResult(TextAndVersion.Create(sourceText, VersionStamp.Create()))));

            var documentSnapshot = project.GetDocument(hostDocument.FilePath);

            var solution = Workspace.CurrentSolution.AddProject(ProjectInfo.Create(
                                                                    ProjectId.CreateNewId(Path.GetFileNameWithoutExtension(hostDocument.FilePath)),
                                                                    VersionStamp.Create(),
                                                                    Path.GetFileNameWithoutExtension(hostDocument.FilePath),
                                                                    Path.GetFileNameWithoutExtension(hostDocument.FilePath),
                                                                    LanguageNames.CSharp,
                                                                    hostDocument.FilePath));

            solution = solution.AddDocument(
                DocumentId.CreateNewId(solution.ProjectIds.Single(), hostDocument.FilePath),
                hostDocument.FilePath,
                new GeneratedDocumentTextLoader(documentSnapshot, hostDocument.FilePath));

            var document = solution.Projects.Single().Documents.Single();

            return(document);
        }
Ejemplo n.º 13
0
        private void AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(uint docCookie, string moniker)
        {
            var languageInformation = TryGetLanguageInformation(moniker);

            if (languageInformation != null &&
                !_filesInProjects.Any(d => StringComparer.OrdinalIgnoreCase.Equals(d.Moniker, moniker)) &&
                !_docCookiesToHostProject.ContainsKey(docCookie))
            {
                // See if we should push to this to the metadata-to-source workspace instead.
                if (_runningDocumentTable.IsDocumentInitialized(docCookie))
                {
                    var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
                    var textBuffer   = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);

                    if (_fileTrackingMetadataAsSourceService.TryAddDocumentToWorkspace(moniker, textBuffer))
                    {
                        // We already added it, so we will keep it excluded from the misc files workspace
                        return;
                    }
                }

                var parseOptions = languageInformation.ParseOptions;

                if (Path.GetExtension(moniker) == languageInformation.ScriptExtension)
                {
                    parseOptions = parseOptions.WithKind(SourceCodeKind.Script);
                }

                // First, create the project
                var hostProject = new HostProject(this, CurrentSolution.Id, languageInformation.LanguageName, parseOptions, _metadataReferences);

                // Now try to find the document. We accept any text buffer, since we've already verified it's an appropriate file in ShouldIncludeFile.
                var document = _documentProvider.TryGetDocumentForFile(hostProject, (uint)VSConstants.VSITEMID.Nil, moniker, parseOptions.Kind, t => true);

                // If the buffer has not yet been initialized, we won't get a document.
                if (document == null)
                {
                    return;
                }

                // Since we have a document, we can do the rest of the project setup.
                _hostProjects.Add(hostProject.Id, hostProject);
                OnProjectAdded(hostProject.CreateProjectInfoForCurrentState());

                OnDocumentAdded(document.GetInitialState());
                hostProject.Document = document;

                // Notify the document provider, so it knows the document is now open and a part of
                // the project
                _documentProvider.NotifyDocumentRegisteredToProject(document);

                Contract.ThrowIfFalse(document.IsOpen);

                var buffer = document.GetOpenTextBuffer();
                OnDocumentOpened(document.Id, document.GetOpenTextContainer());

                _docCookiesToHostProject.Add(docCookie, hostProject);
            }
        }
Ejemplo n.º 14
0
 protected void RemoveDocument(HostProject hostProject, string filePath)
 {
     if (_currentDocuments.TryGetValue(filePath, out var hostDocument))
     {
         _projectSnapshotManager.DocumentRemoved(hostProject, hostDocument);
         _currentDocuments.Remove(filePath);
     }
 }
Ejemplo n.º 15
0
 public DefaultWorkspaceSemanticTokensRefreshTriggerTest()
 {
     ProjectManager = TestProjectSnapshotManager.Create(LegacyDispatcher);
     ProjectManager.AllowNotifyListeners = true;
     HostProject = new HostProject("/path/to/project.csproj", RazorConfiguration.Default, "TestRootNamespace");
     ProjectManager.ProjectAdded(HostProject);
     HostDocument = new HostDocument("/path/to/file.razor", "file.razor");
     ProjectManager.DocumentAdded(HostProject, HostDocument, new EmptyTextLoader(HostDocument.FilePath));
 }
Ejemplo n.º 16
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);
        }
        public DefaultProjectSnapshotProjectEngineFactoryTest()
        {
            Project project = null;

            Workspace = TestWorkspace.Create(workspace =>
            {
                var info = ProjectInfo.Create(ProjectId.CreateNewId("Test"), VersionStamp.Default, "Test", "Test", LanguageNames.CSharp, filePath: "/TestPath/SomePath/Test.csproj");
                project  = workspace.CurrentSolution.AddProject(info).GetProject(info.Id);
            });

            WorkspaceProject = project;

            HostProject_For_1_0 = new HostProject("/TestPath/SomePath/Test.csproj", FallbackRazorConfiguration.MVC_1_0);
            HostProject_For_1_1 = new HostProject("/TestPath/SomePath/Test.csproj", FallbackRazorConfiguration.MVC_1_1);
            HostProject_For_2_0 = new HostProject("/TestPath/SomePath/Test.csproj", FallbackRazorConfiguration.MVC_2_0);

            HostProject_For_2_1 = new HostProject(
                "/TestPath/SomePath/Test.csproj",
                new ProjectSystemRazorConfiguration(RazorLanguageVersion.Version_2_1, "MVC-2.1", Array.Empty <RazorExtension>()));

            HostProject_For_3_0 = new HostProject(
                "/TestPath/SomePath/Test.csproj",
                new ProjectSystemRazorConfiguration(RazorLanguageVersion.Version_3_0, "MVC-3.0", Array.Empty <RazorExtension>()));

            HostProject_For_UnknownConfiguration = new HostProject(
                "/TestPath/SomePath/Test.csproj",
                new ProjectSystemRazorConfiguration(RazorLanguageVersion.Version_2_1, "Blazor-0.1", Array.Empty <RazorExtension>()));

            Snapshot_For_1_0 = new DefaultProjectSnapshot(ProjectState.Create(Workspace.Services, HostProject_For_1_0, WorkspaceProject));
            Snapshot_For_1_1 = new DefaultProjectSnapshot(ProjectState.Create(Workspace.Services, HostProject_For_1_1, WorkspaceProject));
            Snapshot_For_2_0 = new DefaultProjectSnapshot(ProjectState.Create(Workspace.Services, HostProject_For_2_0, WorkspaceProject));
            Snapshot_For_2_1 = new DefaultProjectSnapshot(ProjectState.Create(Workspace.Services, HostProject_For_2_1, WorkspaceProject));
            Snapshot_For_3_0 = new DefaultProjectSnapshot(ProjectState.Create(Workspace.Services, HostProject_For_3_0, WorkspaceProject));
            Snapshot_For_UnknownConfiguration = new DefaultProjectSnapshot(ProjectState.Create(Workspace.Services, HostProject_For_UnknownConfiguration, WorkspaceProject));

            CustomFactories = new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>[]
            {
                new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>(
                    () => new LegacyProjectEngineFactory_1_0(),
                    typeof(LegacyProjectEngineFactory_1_0).GetCustomAttribute <ExportCustomProjectEngineFactoryAttribute>()),
                new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>(
                    () => new LegacyProjectEngineFactory_1_1(),
                    typeof(LegacyProjectEngineFactory_1_1).GetCustomAttribute <ExportCustomProjectEngineFactoryAttribute>()),
                new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>(
                    () => new LegacyProjectEngineFactory_2_0(),
                    typeof(LegacyProjectEngineFactory_2_0).GetCustomAttribute <ExportCustomProjectEngineFactoryAttribute>()),
                new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>(
                    () => new LegacyProjectEngineFactory_2_1(),
                    typeof(LegacyProjectEngineFactory_2_1).GetCustomAttribute <ExportCustomProjectEngineFactoryAttribute>()),
                new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>(
                    () => new LegacyProjectEngineFactory_3_0(),
                    typeof(LegacyProjectEngineFactory_3_0).GetCustomAttribute <ExportCustomProjectEngineFactoryAttribute>()),
            };

            FallbackFactory = new FallbackProjectEngineFactory();
        }
 public DefaultGeneratedDocumentPublisherTest()
 {
     Server         = new TestServer();
     ProjectManager = TestProjectSnapshotManager.Create(Dispatcher);
     ProjectManager.AllowNotifyListeners = true;
     HostProject = new HostProject("/path/to/project.csproj", RazorConfiguration.Default, "TestRootNamespace");
     ProjectManager.ProjectAdded(HostProject);
     HostDocument = new HostDocument("/path/to/file.razor", "file.razor");
     ProjectManager.DocumentAdded(HostProject, HostDocument, new EmptyTextLoader(HostDocument.FilePath));
 }
Ejemplo n.º 19
0
        public BackgroundDocumentGeneratorTest()
        {
            Documents = new HostDocument[]
            {
                new HostDocument("c:/Test1/Index.cshtml", "Index.cshtml"),
                new HostDocument("c:/Test1/Components/Counter.cshtml", "Components/Counter.cshtml"),
            };

            HostProject1 = new HostProject("c:/Test1/Test1.csproj", RazorConfiguration.Default, "TestRootNamespace");
            HostProject2 = new HostProject("c:/Test2/Test2.csproj", RazorConfiguration.Default, "TestRootNamespace");
        }
Ejemplo n.º 20
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;
            }
        public override void AddProject(string filePath)
        {
            _foregroundDispatcher.AssertForegroundThread();

            var normalizedPath = _filePathNormalizer.Normalize(filePath);
            var hostProject = new HostProject(normalizedPath, RazorDefaults.Configuration, RazorDefaults.RootNamespace);
            _projectSnapshotManagerAccessor.Instance.ProjectAdded(hostProject);
            _logger.LogInformation($"Added project '{filePath}' to project system.");

            TryMigrateMiscellaneousDocumentsToProject();
        }
        public DocumentOutputReferenceCapturerTest()
        {
            ProjectManager = TestProjectSnapshotManager.Create(Dispatcher);
            ProjectManager.AllowNotifyListeners = true;

            HostProject = new HostProject("C:/path/to/project.csproj", RazorConfiguration.Default, "TestNamespace");
            ProjectManager.ProjectAdded(HostProject);
            HostDocument = new HostDocument("C:/path/to/file.razor", "file.razor");
            ProjectManager.DocumentAdded(HostProject, HostDocument, new EmptyTextLoader(HostDocument.FilePath));

            DocumentOutputReferenceCapturer = new DocumentOutputReferenceCapturer();
            DocumentOutputReferenceCapturer.Initialize(ProjectManager);
        }
        public ProjectBuildChangeTriggerTest()
        {
            SomeProject      = new HostProject("c:\\SomeProject\\SomeProject.csproj", FallbackRazorConfiguration.MVC_1_0, "SomeProject");
            SomeOtherProject = new HostProject("c:\\SomeOtherProject\\SomeOtherProject.csproj", FallbackRazorConfiguration.MVC_2_0, "SomeOtherProject");

            Workspace = TestWorkspace.Create(w => SomeWorkspaceProject = w.AddProject(ProjectInfo.Create(
                                                                                          ProjectId.CreateNewId(),
                                                                                          VersionStamp.Create(),
                                                                                          "SomeProject",
                                                                                          "SomeProject",
                                                                                          LanguageNames.CSharp,
                                                                                          filePath: SomeProject.FilePath)));
        }
        public VsSolutionUpdatesProjectSnapshotChangeTriggerTest()
        {
            SomeProject      = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_1_0, TestProjectData.SomeProject.RootNamespace);
            SomeOtherProject = new HostProject(TestProjectData.AnotherProject.FilePath, FallbackRazorConfiguration.MVC_2_0, TestProjectData.AnotherProject.RootNamespace);

            Workspace = TestWorkspace.Create(w => SomeWorkspaceProject = w.AddProject(ProjectInfo.Create(
                                                                                          ProjectId.CreateNewId(),
                                                                                          VersionStamp.Create(),
                                                                                          "SomeProject",
                                                                                          "SomeProject",
                                                                                          LanguageNames.CSharp,
                                                                                          filePath: SomeProject.FilePath)));
        }
        public async Task ProjectRemoved_UnSetPublishFilePath_NoopsAsync()
        {
            // Arrange
            var snapshotManager = CreateProjectSnapshotManager(allowNotifyListeners: true);
            var publisher       = new TestDefaultRazorProjectChangePublisher(JoinableTaskContext, RazorLogger);

            publisher.Initialize(snapshotManager);
            var hostProject = new HostProject("/path/to/project.csproj", RazorConfiguration.Default, "TestRootNamespace");

            await RunOnForegroundAsync(() => snapshotManager.ProjectAdded(hostProject)).ConfigureAwait(false);

            // Act & Assert
            await RunOnForegroundAsync(() => snapshotManager.ProjectRemoved(hostProject)).ConfigureAwait(false);
        }
        public DefaultProjectSnapshotProjectEngineFactoryTest()
        {
            Workspace = TestWorkspace.Create();

            ProjectWorkspaceState = ProjectWorkspaceState.Default;

            HostProject_For_1_0 = new HostProject("/TestPath/SomePath/Test.csproj", FallbackRazorConfiguration.MVC_1_0, "Test");
            HostProject_For_1_1 = new HostProject("/TestPath/SomePath/Test.csproj", FallbackRazorConfiguration.MVC_1_1, "Test");
            HostProject_For_2_0 = new HostProject("/TestPath/SomePath/Test.csproj", FallbackRazorConfiguration.MVC_2_0, "Test");

            HostProject_For_2_1 = new HostProject(
                "/TestPath/SomePath/Test.csproj",
                new ProjectSystemRazorConfiguration(RazorLanguageVersion.Version_2_1, "MVC-2.1", Array.Empty <RazorExtension>()), "Test");

            HostProject_For_3_0 = new HostProject(
                "/TestPath/SomePath/Test.csproj",
                new ProjectSystemRazorConfiguration(RazorLanguageVersion.Version_3_0, "MVC-3.0", Array.Empty <RazorExtension>()), "Test");

            HostProject_For_UnknownConfiguration = new HostProject(
                "/TestPath/SomePath/Test.csproj",
                new ProjectSystemRazorConfiguration(RazorLanguageVersion.Version_2_1, "Random-0.1", Array.Empty <RazorExtension>()), rootNamespace: null);

            Snapshot_For_1_0 = new DefaultProjectSnapshot(ProjectState.Create(Workspace.Services, HostProject_For_1_0, ProjectWorkspaceState));
            Snapshot_For_1_1 = new DefaultProjectSnapshot(ProjectState.Create(Workspace.Services, HostProject_For_1_1, ProjectWorkspaceState));
            Snapshot_For_2_0 = new DefaultProjectSnapshot(ProjectState.Create(Workspace.Services, HostProject_For_2_0, ProjectWorkspaceState));
            Snapshot_For_2_1 = new DefaultProjectSnapshot(ProjectState.Create(Workspace.Services, HostProject_For_2_1, ProjectWorkspaceState));
            Snapshot_For_3_0 = new DefaultProjectSnapshot(ProjectState.Create(Workspace.Services, HostProject_For_3_0, ProjectWorkspaceState));
            Snapshot_For_UnknownConfiguration = new DefaultProjectSnapshot(ProjectState.Create(Workspace.Services, HostProject_For_UnknownConfiguration, ProjectWorkspaceState));

            CustomFactories = new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>[]
            {
                new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>(
                    () => new LegacyProjectEngineFactory_1_0(),
                    typeof(LegacyProjectEngineFactory_1_0).GetCustomAttribute <ExportCustomProjectEngineFactoryAttribute>()),
                new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>(
                    () => new LegacyProjectEngineFactory_1_1(),
                    typeof(LegacyProjectEngineFactory_1_1).GetCustomAttribute <ExportCustomProjectEngineFactoryAttribute>()),
                new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>(
                    () => new LegacyProjectEngineFactory_2_0(),
                    typeof(LegacyProjectEngineFactory_2_0).GetCustomAttribute <ExportCustomProjectEngineFactoryAttribute>()),
                new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>(
                    () => new LegacyProjectEngineFactory_2_1(),
                    typeof(LegacyProjectEngineFactory_2_1).GetCustomAttribute <ExportCustomProjectEngineFactoryAttribute>()),
                new Lazy <IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>(
                    () => new LegacyProjectEngineFactory_3_0(),
                    typeof(LegacyProjectEngineFactory_3_0).GetCustomAttribute <ExportCustomProjectEngineFactoryAttribute>()),
            };

            FallbackFactory = new FallbackProjectEngineFactory();
        }
        public BackgroundDocumentGeneratorTest()
        {
            Documents = new HostDocument[]
            {
                new HostDocument("c:\\Test1\\Index.cshtml", "Index.cshtml"),
                new HostDocument("c:\\Test1\\Components\\Counter.cshtml", "Components\\Counter.cshtml"),
            };

            HostProject1 = new HostProject("c:\\Test1\\Test1.csproj", RazorConfiguration.Default);
            HostProject2 = new HostProject("c:\\Test2\\Test2.csproj", RazorConfiguration.Default);

            var projectId1 = ProjectId.CreateNewId("Test1");
            var projectId2 = ProjectId.CreateNewId("Test2");
        }
Ejemplo n.º 28
0
        public DefaultVisualStudioDocumentTrackerTest()
        {
            RazorCoreContentType = Mock.Of <IContentType>(c => c.IsOfType(RazorLanguage.ContentType) == true);
            TextBuffer           = Mock.Of <ITextBuffer>(b => b.ContentType == RazorCoreContentType);

            FilePath    = "C:/Some/Path/TestDocumentTracker.cshtml";
            ProjectPath = "C:/Some/Path/TestProject.csproj";

            ImportDocumentManager   = Mock.Of <ImportDocumentManager>();
            WorkspaceEditorSettings = new DefaultWorkspaceEditorSettings(Mock.Of <ForegroundDispatcher>(), Mock.Of <EditorSettingsManager>());

            TagHelperResolver = new TestTagHelperResolver();
            SomeTagHelpers    = new List <TagHelperDescriptor>()
            {
                TagHelperDescriptorBuilder.Create("test", "test").Build(),
            };

            HostServices = TestServices.Create(
                new IWorkspaceService[] { },
                new ILanguageService[] { TagHelperResolver, });

            Workspace = TestWorkspace.Create(HostServices, w =>
            {
                WorkspaceProject = w.AddProject(ProjectInfo.Create(
                                                    ProjectId.CreateNewId(),
                                                    new VersionStamp(),
                                                    "Test1",
                                                    "TestAssembly",
                                                    LanguageNames.CSharp,
                                                    filePath: ProjectPath));
            });

            ProjectManager = new TestProjectSnapshotManager(Dispatcher, Workspace)
            {
                AllowNotifyListeners = true
            };

            HostProject      = new HostProject(ProjectPath, FallbackRazorConfiguration.MVC_2_1);
            OtherHostProject = new HostProject(ProjectPath, FallbackRazorConfiguration.MVC_2_0);

            DocumentTracker = new DefaultVisualStudioDocumentTracker(
                Dispatcher,
                FilePath,
                ProjectPath,
                ProjectManager,
                WorkspaceEditorSettings,
                Workspace,
                TextBuffer,
                ImportDocumentManager);
        }
Ejemplo n.º 29
0
        public OmniSharpHostProject(string projectFilePath, RazorConfiguration razorConfiguration, string rootNamespace)
        {
            if (projectFilePath == null)
            {
                throw new ArgumentNullException(nameof(projectFilePath));
            }

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

            InternalHostProject = new HostProject(projectFilePath, razorConfiguration, rootNamespace);
        }
Ejemplo n.º 30
0
        protected void AddDocument(HostProject hostProject, string filePath, string relativeFilePath)
        {
            ProjectSnapshotManagerDispatcher.AssertDispatcherThread();

            if (_currentDocuments.ContainsKey(filePath))
            {
                return;
            }

            var hostDocument = new HostDocument(filePath, relativeFilePath);

            _projectSnapshotManager.DocumentAdded(hostProject, hostDocument, new FileTextLoader(filePath, defaultEncoding: null));

            _currentDocuments[filePath] = hostDocument;
        }
Ejemplo n.º 31
0
        private void AttachToDocument(uint docCookie, string moniker)
        {
            var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
            var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);

            if (_fileTrackingMetadataAsSourceService.TryAddDocumentToWorkspace(moniker, textBuffer))
            {
                // We already added it, so we will keep it excluded from the misc files workspace
                return;
            }

            // This should always succeed since we only got here if we already confirmed the moniker is acceptable
            var languageInformation = TryGetLanguageInformation(moniker);
            Contract.ThrowIfNull(languageInformation);
            var parseOptions = languageInformation.ParseOptions;

            if (Path.GetExtension(moniker) == languageInformation.ScriptExtension)
            {
                parseOptions = parseOptions.WithKind(SourceCodeKind.Script);
            }

            // First, create the project
            var hostProject = new HostProject(this, CurrentSolution.Id, languageInformation.LanguageName, parseOptions, _metadataReferences);

            // Now try to find the document. We accept any text buffer, since we've already verified it's an appropriate file in ShouldIncludeFile.
            var document = _documentProvider.TryGetDocumentForFile(
                hostProject,
                (uint)VSConstants.VSITEMID.Nil,
                moniker,
                parseOptions.Kind,
                canUseTextBuffer: _ => true);

            // If the buffer has not yet been initialized, we won't get a document.
            if (document == null)
            {
                return;
            }

            // Since we have a document, we can do the rest of the project setup.
            _hostProjects.Add(hostProject.Id, hostProject);
            OnProjectAdded(hostProject.CreateProjectInfoForCurrentState());

            OnDocumentAdded(document.GetInitialState());
            hostProject.Document = document;

            // Notify the document provider, so it knows the document is now open and a part of
            // the project
            _documentProvider.NotifyDocumentRegisteredToProject(document);

            Contract.ThrowIfFalse(document.IsOpen);

            var buffer = document.GetOpenTextBuffer();
            OnDocumentOpened(document.Id, document.GetOpenTextContainer());

            _docCookiesToHostProject.Add(docCookie, hostProject);
        }