public void SetOutput_AcceptsSameVersionedDocuments()
        {
            // Arrange
            var services     = TestWorkspace.Create().Services;
            var hostProject  = new HostProject("C:/project.csproj", RazorConfiguration.Default);
            var projectState = ProjectState.Create(services, hostProject);
            var project      = new DefaultProjectSnapshot(projectState);

            var text           = SourceText.From("...");
            var textAndVersion = TextAndVersion.Create(text, VersionStamp.Default);
            var hostDocument   = new HostDocument("C:/file.cshtml", "C:/file.cshtml");
            var documentState  = new DocumentState(services, hostDocument, text, VersionStamp.Default, () => Task.FromResult(textAndVersion));
            var document       = new DefaultDocumentSnapshot(project, documentState);
            var newDocument    = new DefaultDocumentSnapshot(project, documentState);

            var csharpDocument = RazorCSharpDocument.Create("...", RazorCodeGenerationOptions.CreateDefault(), Enumerable.Empty <RazorDiagnostic>());

            var version   = VersionStamp.Create();
            var container = new GeneratedCodeContainer();

            container.SetOutput(document, csharpDocument, version, version);

            // Act
            container.SetOutput(newDocument, csharpDocument, version, version);

            // Assert
            Assert.Same(newDocument, container.LatestDocument);
        }
Exemplo n.º 2
0
        public ProjectState WithHostProject(HostProject hostProject)
        {
            if (hostProject == null)
            {
                throw new ArgumentNullException(nameof(hostProject));
            }

            if (HostProject.Configuration.Equals(hostProject.Configuration))
            {
                return(this);
            }

            var documents = Documents.ToImmutableDictionary(kvp => kvp.Key, kvp => kvp.Value.WithConfigurationChange(), FilePathComparer.Instance);

            // If the host project has changed then we need to recompute the imports map
            var importsToRelatedDocuments = EmptyImportsToRelatedDocuments;

            foreach (var document in documents)
            {
                var importTargetPaths = GetImportDocumentTargetPaths(document.Value.HostDocument);
                importsToRelatedDocuments = AddToImportsToRelatedDocuments(importsToRelatedDocuments, document.Value.HostDocument, importTargetPaths);
            }

            var state = new ProjectState(this, ProjectDifference.ConfigurationChanged, hostProject, ProjectWorkspaceState, documents, importsToRelatedDocuments);

            return(state);
        }
Exemplo n.º 3
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", FallbackRazorConfiguration.MVC_1_0);
            HostProject2 = new HostProject("c:\\Test2\\Test2.csproj", FallbackRazorConfiguration.MVC_1_0);

            Workspace = TestWorkspace.Create();

            var projectId1 = ProjectId.CreateNewId("Test1");
            var projectId2 = ProjectId.CreateNewId("Test2");

            var solution = Workspace.CurrentSolution
                           .AddProject(ProjectInfo.Create(
                                           projectId1,
                                           VersionStamp.Default,
                                           "Test1",
                                           "Test1",
                                           LanguageNames.CSharp,
                                           "c:\\Test1\\Test1.csproj"))
                           .AddProject(ProjectInfo.Create(
                                           projectId2,
                                           VersionStamp.Default,
                                           "Test2",
                                           "Test2",
                                           LanguageNames.CSharp,
                                           "c:\\Test2\\Test2.csproj"));;

            WorkspaceProject1 = solution.GetProject(projectId1);
            WorkspaceProject2 = solution.GetProject(projectId2);
        }
        public void HostProjectChanged_WithWorkspaceProject_RetainsComputedState_NotifiesListeners_AndStartsBackgroundWorker()
        {
            // Arrange
            ProjectManager.HostProjectAdded(HostProject);
            ProjectManager.WorkspaceProjectAdded(WorkspaceProject);
            ProjectManager.Reset();

            // Adding some computed state
            var snapshot      = ProjectManager.GetSnapshot(HostProject);
            var updateContext = snapshot.CreateUpdateContext();

            ProjectManager.ProjectUpdated(updateContext);
            ProjectManager.Reset();

            var project = new HostProject(HostProject.FilePath, FallbackRazorConfiguration.MVC_1_0); // Simulate a project change

            // Act
            ProjectManager.HostProjectChanged(project);

            // Assert
            snapshot = ProjectManager.GetSnapshot(project);
            Assert.True(snapshot.IsDirty);
            Assert.True(snapshot.IsInitialized);

            Assert.True(ProjectManager.ListenersNotified);
            Assert.True(ProjectManager.WorkerStarted);
        }
        public void ProjectUpdated_WhenHostProjectChanged_StillDirty_WithSignificantChanges_NotifiesListeners_AndStartsBackgroundWorker()
        {
            // Arrange
            ProjectManager.HostProjectAdded(HostProject);
            ProjectManager.WorkspaceProjectAdded(WorkspaceProject);
            ProjectManager.Reset();

            // Generate the update
            var snapshot      = ProjectManager.GetSnapshot(HostProject);
            var updateContext = snapshot.CreateUpdateContext();

            var project = new HostProject(HostProject.FilePath, FallbackRazorConfiguration.MVC_1_0); // Simulate a project change

            ProjectManager.HostProjectChanged(project);
            ProjectManager.Reset();

            // Act
            ProjectManager.ProjectUpdated(updateContext);

            // Assert
            snapshot = ProjectManager.GetSnapshot(project);
            Assert.True(snapshot.IsDirty);

            Assert.True(ProjectManager.ListenersNotified);
            Assert.True(ProjectManager.WorkerStarted);
        }
        public BackgroundDocumentGeneratorTest()
        {
            Documents = new HostDocument[]
            {
                TestProjectData.SomeProjectFile1,
                TestProjectData.AnotherProjectFile1,
            };

            HostProject1 = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_1_0);
            HostProject2 = new HostProject(TestProjectData.AnotherProject.FilePath, FallbackRazorConfiguration.MVC_1_0);

            var projectId1 = ProjectId.CreateNewId("Test1");
            var projectId2 = ProjectId.CreateNewId("Test2");

            var solution = Workspace.CurrentSolution
                           .AddProject(ProjectInfo.Create(
                                           projectId1,
                                           VersionStamp.Default,
                                           "Test1",
                                           "Test1",
                                           LanguageNames.CSharp,
                                           TestProjectData.SomeProject.FilePath))
                           .AddProject(ProjectInfo.Create(
                                           projectId2,
                                           VersionStamp.Default,
                                           "Test2",
                                           "Test2",
                                           LanguageNames.CSharp,
                                           TestProjectData.AnotherProject.FilePath));;

            WorkspaceProject1 = solution.GetProject(projectId1);
            WorkspaceProject2 = solution.GetProject(projectId2);

            DynamicFileInfoProvider = new RazorDynamicFileInfoProvider(new DefaultDocumentServiceProviderFactory());
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
0
        // Must be called inside the lock.
        protected async Task UpdateProjectUnsafeAsync(HostProject project)
        {
            await CommonServices.ThreadingService.SwitchToUIThread();

            var projectManager = GetProjectManager();

            if (_current == null && project == null)
            {
                // This is a no-op. This project isn't using Razor.
            }
            else if (_current == null && project != null)
            {
                projectManager.HostProjectAdded(project);
            }
            else if (_current != null && project == null)
            {
                projectManager.HostProjectRemoved(_current);
            }
            else
            {
                projectManager.HostProjectChanged(project);
            }

            _current = project;
        }
        public DocumentStateTest()
        {
            TagHelperResolver = new TestTagHelperResolver();

            HostProject = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_2_0);
            HostProjectWithConfigurationChange = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_1_0);

            var projectId = ProjectId.CreateNewId("Test");
            var solution  = Workspace.CurrentSolution.AddProject(ProjectInfo.Create(
                                                                     projectId,
                                                                     VersionStamp.Default,
                                                                     "Test",
                                                                     "Test",
                                                                     LanguageNames.CSharp,
                                                                     TestProjectData.SomeProject.FilePath));

            WorkspaceProject = solution.GetProject(projectId);

            SomeTagHelpers = new List <TagHelperDescriptor>();
            SomeTagHelpers.Add(TagHelperDescriptorBuilder.Create("Test1", "TestAssembly").Build());

            HostDocument = TestProjectData.SomeProjectFile1;

            Text       = SourceText.From("Hello, world!");
            TextLoader = () => Task.FromResult(TextAndVersion.Create(Text, VersionStamp.Create()));
        }
Exemplo n.º 10
0
        public DefaultProjectSnapshotTest()
        {
            TagHelperResolver = new TestTagHelperResolver();

            HostProject = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_2_0);
            HostProjectWithConfigurationChange = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_1_0);
            ProjectWorkspaceState = new ProjectWorkspaceState(new[]
            {
                TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly").Build(),
            });

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

            Documents = new HostDocument[]
            {
                TestProjectData.SomeProjectFile1,
                TestProjectData.SomeProjectFile2,

                // linked file
                TestProjectData.AnotherProjectNestedFile3,
            };
        }
        public DefaultProjectSnapshotManagerTest()
        {
            TagHelperResolver = new TestTagHelperResolver();

            Documents = new HostDocument[]
            {
                TestProjectData.SomeProjectFile1,
                TestProjectData.SomeProjectFile2,

                // linked file
                TestProjectData.AnotherProjectNestedFile3,

                TestProjectData.SomeProjectComponentFile1,
                TestProjectData.SomeProjectComponentFile2,
            };

            HostProject = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_2_0, TestProjectData.SomeProject.RootNamespace);
            HostProjectWithConfigurationChange = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_1_0, TestProjectData.SomeProject.RootNamespace);

            ProjectManager = new TestProjectSnapshotManager(Dispatcher, Enumerable.Empty <ProjectSnapshotChangeTrigger>(), Workspace);

            ProjectWorkspaceStateWithTagHelpers = new ProjectWorkspaceState(TagHelperResolver.TagHelpers, default);

            SourceText = SourceText.From("Hello world");
        }
        public override void DocumentAdded(HostProject hostProject, HostDocument document, TextLoader textLoader)
        {
            if (hostProject == null)
            {
                throw new ArgumentNullException(nameof(hostProject));
            }

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

            _foregroundDispatcher.AssertForegroundThread();

            if (_projects.TryGetValue(hostProject.FilePath, out var entry))
            {
                var loader = textLoader == null ? DocumentState.EmptyLoader : (Func <Task <TextAndVersion> >)(() =>
                {
                    return(textLoader.LoadTextAndVersionAsync(Workspace, null, CancellationToken.None));
                });
                var state = entry.State.WithAddedHostDocument(document, loader);

                // Document updates can no-op.
                if (!object.ReferenceEquals(state, entry.State))
                {
                    var oldSnapshot = entry.GetSnapshot();
                    entry = new Entry(state);
                    _projects[hostProject.FilePath] = entry;
                    NotifyListeners(new ProjectChangeEventArgs(oldSnapshot, entry.GetSnapshot(), document.FilePath, ProjectChangeKind.DocumentAdded));
                }
            }
        }
        public DefaultRazorDocumentInfoProviderTest()
        {
            ProjectSnapshotManager = new TestProjectSnapshotManager(Workspace);

            var hostProject = new HostProject("C:/path/to/project.csproj", RazorConfiguration.Default, "RootNamespace");

            ProjectSnapshotManager.ProjectAdded(hostProject);

            var hostDocument   = new HostDocument("C:/path/to/document.cshtml", "/C:/path/to/document.cshtml");
            var sourceText     = SourceText.From("Hello World");
            var textAndVersion = TextAndVersion.Create(sourceText, VersionStamp.Default, hostDocument.FilePath);

            ProjectSnapshotManager.DocumentAdded(hostProject, hostDocument, TextLoader.From(textAndVersion));

            ProjectSnapshot  = ProjectSnapshotManager.Projects[0];
            DocumentSnapshot = ProjectSnapshot.GetDocument(hostDocument.FilePath);
            var factory = new Mock <VisualStudioMacDocumentInfoFactory>();

            factory.Setup(f => f.CreateEmpty(It.IsAny <string>(), It.IsAny <ProjectId>()))
            .Returns <string, ProjectId>((razorFilePath, projectId) =>
            {
                var documentId   = DocumentId.CreateNewId(projectId);
                var documentInfo = DocumentInfo.Create(documentId, "testDoc", filePath: razorFilePath);
                return(documentInfo);
            });
            Factory = factory.Object;
        }
        public override void DocumentRemoved(HostProject hostProject, HostDocument document)
        {
            if (hostProject == null)
            {
                throw new ArgumentNullException(nameof(hostProject));
            }

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

            _foregroundDispatcher.AssertForegroundThread();
            if (_projects.TryGetValue(hostProject.FilePath, out var entry))
            {
                var state = entry.State.WithRemovedHostDocument(document);

                // Document updates can no-op.
                if (!object.ReferenceEquals(state, entry.State))
                {
                    var oldSnapshot = entry.GetSnapshot();
                    entry = new Entry(state);
                    _projects[hostProject.FilePath] = entry;
                    NotifyListeners(new ProjectChangeEventArgs(oldSnapshot, entry.GetSnapshot(), document.FilePath, ProjectChangeKind.DocumentRemoved));
                }
            }
        }
Exemplo n.º 15
0
        protected void UpdateProjectUnsafe(HostProject project)
        {
            var projectManager = GetProjectManager();

            if (Current is null && project is null)
            {
                // This is a no-op. This project isn't using Razor.
            }
Exemplo n.º 16
0
        public DefaultProjectSnapshot WithHostProject(HostProject hostProject)
        {
            if (hostProject == null)
            {
                throw new ArgumentNullException(nameof(hostProject));
            }

            return(new DefaultProjectSnapshot(hostProject, this));
        }
Exemplo n.º 17
0
        // Internal for testing
        internal async Task OnProjectChanged(IProjectVersionedValue <IProjectSubscriptionUpdate> update)
        {
            if (IsDisposing || IsDisposed)
            {
                return;
            }

            await CommonServices.TasksService.LoadedProjectAsync(async() =>
            {
                await ExecuteWithLock(async() =>
                {
                    if (TryGetConfiguration(update.Value.CurrentState, out var configuration))
                    {
                        TryGetRootNamespace(update.Value.CurrentState, out var rootNamespace);

                        // We need to deal with the case where the project was uninitialized, but now
                        // is valid for Razor. In that case we might have previously seen all of the documents
                        // but ignored them because the project wasn't active.
                        //
                        // So what we do to deal with this, is that we 'remove' all changed and removed items
                        // and then we 'add' all current items. This allows minimal churn to the PSM, but still
                        // makes us up to date.
                        var documents        = GetCurrentDocuments(update.Value);
                        var changedDocuments = GetChangedAndRemovedDocuments(update.Value);

                        await UpdateAsync(() =>
                        {
                            var hostProject = new HostProject(CommonServices.UnconfiguredProject.FullPath, configuration, rootNamespace);

                            if (TryGetIntermediateOutputPath(update.Value.CurrentState, out var intermediatePath))
                            {
                                var projectRazorJson = Path.Combine(intermediatePath, "project.razor.json");
                                _razorProjectChangePublisher.SetPublishFilePath(hostProject.FilePath, projectRazorJson);
                            }

                            UpdateProjectUnsafe(hostProject);

                            for (var i = 0; i < changedDocuments.Length; i++)
                            {
                                RemoveDocumentUnsafe(changedDocuments[i]);
                            }

                            for (var i = 0; i < documents.Length; i++)
                            {
                                AddDocumentUnsafe(documents[i]);
                            }
                        }).ConfigureAwait(false);
                    }
                    else
                    {
                        // Ok we can't find a configuration. Let's assume this project isn't using Razor then.
                        await UpdateAsync(UninitializeProjectUnsafe).ConfigureAwait(false);
                    }
                }).ConfigureAwait(false);
            }, registerFaultHandler : true);
        }
Exemplo n.º 18
0
        public WorkspaceProjectStateChangeDetectorTest()
        {
            EmptySolution = Workspace.CurrentSolution.GetIsolatedSolution();

            var projectId1 = ProjectId.CreateNewId("One");
            var projectId2 = ProjectId.CreateNewId("Two");
            var projectId3 = ProjectId.CreateNewId("Three");

            CshtmlDocumentId = DocumentId.CreateNewId(projectId1);
            var cshtmlDocumentInfo = DocumentInfo.Create(CshtmlDocumentId, "Test", filePath: "file.cshtml.g.cs");

            RazorDocumentId = DocumentId.CreateNewId(projectId1);
            var razorDocumentInfo = DocumentInfo.Create(RazorDocumentId, "Test", filePath: "file.razor.g.cs");

            BackgroundVirtualCSharpDocumentId = DocumentId.CreateNewId(projectId1);
            var backgroundDocumentInfo = DocumentInfo.Create(BackgroundVirtualCSharpDocumentId, "Test", filePath: "file.razor__bg__virtual.cs");

            PartialComponentClassDocumentId = DocumentId.CreateNewId(projectId1);
            var partialComponentClassDocumentInfo = DocumentInfo.Create(PartialComponentClassDocumentId, "Test", filePath: "file.razor.cs");

            SolutionWithTwoProjects = Workspace.CurrentSolution
                                      .AddProject(ProjectInfo.Create(
                                                      projectId1,
                                                      VersionStamp.Default,
                                                      "One",
                                                      "One",
                                                      LanguageNames.CSharp,
                                                      filePath: "One.csproj",
                                                      documents: new[] { cshtmlDocumentInfo, razorDocumentInfo, partialComponentClassDocumentInfo, backgroundDocumentInfo }))
                                      .AddProject(ProjectInfo.Create(
                                                      projectId2,
                                                      VersionStamp.Default,
                                                      "Two",
                                                      "Two",
                                                      LanguageNames.CSharp,
                                                      filePath: "Two.csproj"));

            SolutionWithOneProject = EmptySolution.GetIsolatedSolution()
                                     .AddProject(ProjectInfo.Create(
                                                     projectId3,
                                                     VersionStamp.Default,
                                                     "Three",
                                                     "Three",
                                                     LanguageNames.CSharp,
                                                     filePath: "Three.csproj"));

            ProjectNumberOne   = SolutionWithTwoProjects.GetProject(projectId1);
            ProjectNumberTwo   = SolutionWithTwoProjects.GetProject(projectId2);
            ProjectNumberThree = SolutionWithOneProject.GetProject(projectId3);

            HostProjectOne   = new HostProject("One.csproj", FallbackRazorConfiguration.MVC_1_1, "One");
            HostProjectTwo   = new HostProject("Two.csproj", FallbackRazorConfiguration.MVC_1_1, "Two");
            HostProjectThree = new HostProject("Three.csproj", FallbackRazorConfiguration.MVC_1_1, "Three");
        }
Exemplo n.º 19
0
        public override void ReportError(Exception exception, HostProject hostProject)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            var snapshot = hostProject?.FilePath == null ? null : GetLoadedProject(hostProject.FilePath);

            _errorReporter.ReportError(exception, snapshot);
        }
Exemplo n.º 20
0
        public override void ReportError(Exception exception, HostProject hostProject)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            var project = hostProject?.FilePath == null ? null : this.GetProjectWithFilePath(hostProject.FilePath);

            _errorReporter.ReportError(exception, project);
        }
Exemplo n.º 21
0
        // Internal for testing
        internal async Task OnProjectChanged(IProjectVersionedValue <IProjectSubscriptionUpdate> update)
        {
            if (IsDisposing || IsDisposed)
            {
                return;
            }

            await CommonServices.TasksService.LoadedProjectAsync(async() =>
            {
                await ExecuteWithLock(async() =>
                {
                    var languageVersion      = update.Value.CurrentState[Rules.RazorGeneral.SchemaName].Properties[Rules.RazorGeneral.RazorLangVersionProperty];
                    var defaultConfiguration = update.Value.CurrentState[Rules.RazorGeneral.SchemaName].Properties[Rules.RazorGeneral.RazorDefaultConfigurationProperty];

                    RazorConfiguration configuration = null;
                    if (!string.IsNullOrEmpty(languageVersion) && !string.IsNullOrEmpty(defaultConfiguration))
                    {
                        if (!RazorLanguageVersion.TryParse(languageVersion, out var parsedVersion))
                        {
                            parsedVersion = RazorLanguageVersion.Latest;
                        }

                        var extensions = update.Value.CurrentState[Rules.RazorExtension.PrimaryDataSourceItemType].Items.Select(e =>
                        {
                            return(new ProjectSystemRazorExtension(e.Key));
                        }).ToArray();

                        var configurations = update.Value.CurrentState[Rules.RazorConfiguration.PrimaryDataSourceItemType].Items.Select(c =>
                        {
                            var includedExtensions = c.Value[Rules.RazorConfiguration.ExtensionsProperty]
                                                     .Split(';')
                                                     .Select(name => extensions.Where(e => e.ExtensionName == name).FirstOrDefault())
                                                     .Where(e => e != null)
                                                     .ToArray();

                            return(new ProjectSystemRazorConfiguration(parsedVersion, c.Key, includedExtensions));
                        }).ToArray();

                        configuration = configurations.Where(c => c.ConfigurationName == defaultConfiguration).FirstOrDefault();
                    }

                    if (configuration == null)
                    {
                        // Ok we can't find a language version. Let's assume this project isn't using Razor then.
                        await UpdateProjectUnsafeAsync(null).ConfigureAwait(false);
                        return;
                    }

                    var hostProject = new HostProject(CommonServices.UnconfiguredProject.FullPath, configuration);
                    await UpdateProjectUnsafeAsync(hostProject).ConfigureAwait(false);
                });
            }, registerFaultHandler : true);
        }
Exemplo n.º 22
0
        protected void UpdateProjectUnsafe(HostProject project)
        {
            var projectManager = GetProjectManager();

            if (_current == null && project == null)
            {
                // This is a no-op. This project isn't using Razor.
            }
            else if (_current == null && project != null)
            {
                // This is temporary code for initializing the companion project. We expect
                // this to be provided by the Managed Project System in the near future.
                var projectContextFactory = GetProjectContextFactory();
                if (projectContextFactory != null)
                {
                    var assembly = Assembly.Load("Microsoft.VisualStudio.ProjectSystem.Managed, Version=2.7.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                    var type     = assembly.GetType("Microsoft.VisualStudio.ProjectSystem.LanguageServices.IProjectHostProvider");

                    var exportProviderType = CommonServices.UnconfiguredProject.Services.ExportProvider.GetType();
                    var method             = exportProviderType.GetMethod(nameof(ExportProvider.GetExportedValue), Array.Empty <Type>()).MakeGenericMethod(type);
                    var export             = method.Invoke(CommonServices.UnconfiguredProject.Services.ExportProvider, Array.Empty <object>());
                    var host = new IProjectHostProvider(export);

                    var displayName = Path.GetFileNameWithoutExtension(CommonServices.UnconfiguredProject.FullPath) + " (Razor)";
                    _projectContext = projectContextFactory.CreateProjectContext(
                        LanguageNames.CSharp,
                        displayName,
                        CommonServices.UnconfiguredProject.FullPath,
                        Guid.NewGuid(),
                        host.UnconfiguredProjectHostObject.ActiveIntellisenseProjectHostObject,
                        null,
                        null);
                }

                // END temporary code

                projectManager.HostProjectAdded(project);
            }
            else if (_current != null && project == null)
            {
                Debug.Assert(_currentDocuments.Count == 0);
                projectManager.HostProjectRemoved(_current);
                _projectContext?.Dispose();
                _projectContext = null;
            }
            else
            {
                projectManager.HostProjectChanged(project);
            }

            _current = project;
        }
Exemplo n.º 23
0
        private ProjectState(
            HostWorkspaceServices services,
            HostProject hostProject,
            Project workspaceProject)
        {
            Services         = services;
            HostProject      = hostProject;
            WorkspaceProject = workspaceProject;
            Documents        = EmptyDocuments;
            Version          = VersionStamp.Create();

            _lock = new object();
        }
Exemplo n.º 24
0
        public ProjectStateGeneratedOutputTest()
        {
            HostProject = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_2_0, TestProjectData.SomeProject.RootNamespace);
            HostProjectWithConfigurationChange = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_1_0, TestProjectData.SomeProject.RootNamespace);

            SomeTagHelpers = new List <TagHelperDescriptor>();
            SomeTagHelpers.Add(TagHelperDescriptorBuilder.Create("Test1", "TestAssembly").Build());

            HostDocument = TestProjectData.SomeProjectFile1;

            Text       = SourceText.From("Hello, world!");
            TextLoader = () => Task.FromResult(TextAndVersion.Create(Text, VersionStamp.Create()));
        }
Exemplo n.º 25
0
        public DefaultProjectSnapshot(HostProject hostProject, Project workspaceProject, VersionStamp?version = null)
        {
            if (hostProject == null)
            {
                throw new ArgumentNullException(nameof(hostProject));
            }

            HostProject      = hostProject;
            WorkspaceProject = workspaceProject; // Might be null

            FilePath = hostProject.FilePath;
            Version  = version ?? VersionStamp.Default;
        }
        public BackgroundDocumentGeneratorTest()
        {
            Documents = new HostDocument[]
            {
                TestProjectData.SomeProjectFile1,
                TestProjectData.AnotherProjectFile1,
            };

            HostProject1 = new HostProject(TestProjectData.SomeProject.FilePath, FallbackRazorConfiguration.MVC_1_0, TestProjectData.SomeProject.RootNamespace);
            HostProject2 = new HostProject(TestProjectData.AnotherProject.FilePath, FallbackRazorConfiguration.MVC_1_0, TestProjectData.AnotherProject.RootNamespace);

            DynamicFileInfoProvider = new RazorDynamicFileInfoProvider(new DefaultDocumentServiceProviderFactory());
        }
        public DefaultProjectSnapshotManagerTest()
        {
            HostProject = new HostProject("Test.csproj", FallbackRazorConfiguration.MVC_2_0);

            Workspace      = TestWorkspace.Create();
            ProjectManager = new TestProjectSnapshotManager(Dispatcher, Enumerable.Empty <ProjectSnapshotChangeTrigger>(), Workspace);

            var projectId = ProjectId.CreateNewId("Test");
            var solution  = Workspace.CurrentSolution.AddProject(ProjectInfo.Create(
                                                                     projectId,
                                                                     VersionStamp.Default,
                                                                     "Test",
                                                                     "Test",
                                                                     LanguageNames.CSharp,
                                                                     "Test.csproj"));

            WorkspaceProject = solution.GetProject(projectId);

            var vbProjectId = ProjectId.CreateNewId("VB");

            solution = solution.AddProject(ProjectInfo.Create(
                                               vbProjectId,
                                               VersionStamp.Default,
                                               "VB",
                                               "VB",
                                               LanguageNames.VisualBasic,
                                               "VB.vbproj"));
            VBWorkspaceProject = solution.GetProject(vbProjectId);

            var projectWithoutFilePathId = ProjectId.CreateNewId("NoFile");

            solution = solution.AddProject(ProjectInfo.Create(
                                               projectWithoutFilePathId,
                                               VersionStamp.Default,
                                               "NoFile",
                                               "NoFile",
                                               LanguageNames.CSharp));
            WorkspaceProjectWithoutFilePath = solution.GetProject(projectWithoutFilePathId);

            // Approximates a project with multi-targeting
            var projectIdWithDifferentTfm = ProjectId.CreateNewId("TestWithDifferentTfm");

            solution = Workspace.CurrentSolution.AddProject(ProjectInfo.Create(
                                                                projectIdWithDifferentTfm,
                                                                VersionStamp.Default,
                                                                "Test (Different TFM)",
                                                                "Test",
                                                                LanguageNames.CSharp,
                                                                "Test.csproj"));
            WorkspaceProjectWithDifferentTfm = solution.GetProject(projectIdWithDifferentTfm);
        }
Exemplo n.º 28
0
        public static ProjectState Create(HostWorkspaceServices services, HostProject hostProject, Project workspaceProject = null)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

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

            return(new ProjectState(services, hostProject, workspaceProject));
        }
Exemplo n.º 29
0
        // Internal for testing
        internal async Task OnProjectChanged(IProjectVersionedValue <IProjectSubscriptionUpdate> update)
        {
            if (IsDisposing || IsDisposed)
            {
                return;
            }

            await CommonServices.TasksService.LoadedProjectAsync(async() =>
            {
                await ExecuteWithLock(async() =>
                {
                    string mvcReferenceFullPath = null;
                    if (update.Value.CurrentState.ContainsKey(ResolvedCompilationReference.SchemaName))
                    {
                        var references = update.Value.CurrentState[ResolvedCompilationReference.SchemaName].Items;
                        foreach (var reference in references)
                        {
                            if (reference.Key.EndsWith(MvcAssemblyFileName, StringComparison.OrdinalIgnoreCase))
                            {
                                mvcReferenceFullPath = reference.Key;
                                break;
                            }
                        }
                    }

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

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

                    var configuration = FallbackRazorConfiguration.SelectConfiguration(version);
                    var hostProject   = new HostProject(CommonServices.UnconfiguredProject.FullPath, configuration);
                    await UpdateAsync(() =>
                    {
                        UpdateProjectUnsafe(hostProject);
                    }).ConfigureAwait(false);
                });
            }, registerFaultHandler : true);
        }
Exemplo n.º 30
0
        private ProjectState(
            HostWorkspaceServices services,
            HostProject hostProject,
            ProjectWorkspaceState projectWorkspaceState)
        {
            Services                  = services;
            HostProject               = hostProject;
            ProjectWorkspaceState     = projectWorkspaceState;
            Documents                 = EmptyDocuments;
            ImportsToRelatedDocuments = EmptyImportsToRelatedDocuments;
            Version = VersionStamp.Create();
            DocumentCollectionVersion = Version;

            _lock = new object();
        }