Een query uitvoeren op het projectsysteem

Gebruik de Project Query-API om projecten, bestanden en eigenschappen in een Visual Studio-oplossing te lezen en te wijzigen.

Note

In deze handleiding wordt de VisualStudio.Extensibility SDK gebruikt. Zie Het juiste uitbreidbaarheidsmodel kiezen voor modelvergelijking.

Volledig voorbeeld

De volledige implementatie:

// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace VSProjectQueryAPISample;

using System.Globalization;
using System.Text;
using Microsoft.VisualStudio.Extensibility;
using Microsoft.VisualStudio.Extensibility.Commands;
using Microsoft.VisualStudio.Extensibility.Shell;
using Microsoft.VisualStudio.ProjectSystem.Query;

/// <summary>
/// A sample command for querying the project system.
/// </summary>
[VisualStudioContribution]
public class QueryFileCommand : Command
{
    /// <inheritdoc />
    public override CommandConfiguration CommandConfiguration => new("%VSProjectQueryAPISample.QueryFileCommand.DisplayName%")
    {
        Placements = [CommandPlacement.KnownPlacements.ToolsMenu],
        Icon = new(ImageMoniker.KnownValues.Extension, IconSettings.IconAndText),
    };

    /// <inheritdoc />
    public override async Task ExecuteCommandAsync(IClientContext context, CancellationToken cancellationToken)
    {
        var result = await this.Extensibility.Workspaces().QueryProjectsAsync(
            project => project.With(project => project.Name)
                              .With(project => project.Path)
                              .With(project => project.Files.With(file => file.FileName)),
            cancellationToken);

        StringBuilder message = new StringBuilder($"\n \n === Querying File === \n");

        foreach (var project in result)
        {
            _ = message.Append(CultureInfo.CurrentCulture, $"{project.Name}\n");

            foreach (var file in project.Files)
            {
                _ = message.Append(CultureInfo.CurrentCulture, $" \t {file.FileName}\n");
            }
        }

        await this.Extensibility.Shell().ShowPromptAsync(message.ToString(), PromptOptions.OK, cancellationToken);
    }
}

Tip

Bekijk het volledige werkende voorbeeld: VSProjectQueryAPISample ↗

Gerelateerde concepten:Project concepten — project systeemarchitectuur en querypatronen

Begrijp het voorbeeld

Werkruimte ophalen

WorkspacesExtensibility workspace = this.Extensibility.Workspaces();

workspace.Queryable biedt toegang tot de hoofdprojectqueryruimte voor geavanceerde query's en abonnementen. Voor veelvoorkomende query's gebruikt u de onderstaande helpers QueryProjectsAsync en QuerySolutionAsync.

Openen en sluiten van oplossing observeren

QueryableSpaceChanged wordt asynchroon uitgevoerd wanneer een oplossing wordt geopend of gesloten. SolutionPath wordt null bij sluiten. Houd de listenerfunctie actief zolang u meldingen nodig hebt en meld u af wanneer deze wordt opgeschoond:

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Extensibility;
using Microsoft.VisualStudio.ProjectSystem.Query;

internal sealed class SolutionChangeListener : IDisposable
{
    private readonly WorkspacesExtensibility workspace;

    public SolutionChangeListener(VisualStudioExtensibility extensibility)
    {
        this.workspace = extensibility.Workspaces();
        this.workspace.QueryableSpaceChanged += this.OnChangedAsync;
    }

    private Task OnChangedAsync(ProjectQueryableSpaceChangedEventArgs args)
    {
        Trace.WriteLine(args.SolutionPath is null
            ? "Solution closed"
            : $"Solution opened: {args.SolutionPath}");
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        this.workspace.QueryableSpaceChanged -= this.OnChangedAsync;
    }
}

Het actieve document en project ophalen

In een opdracht legt de clientcontext de huidige IDE-status vast. De actieve document-URI en projectmomentopname kunnen beide afwezig zijn:

Uri? documentUri = await context.GetActiveDocumentUriAsync(cancellationToken);
IProjectSnapshot? activeProject = await context.GetActiveProjectAsync(cancellationToken);

Zie de active project command ↗ voor een voorbeeld waarmee een ontbrekend project wordt verwerkt. De document-URI weerspiegelt de actieve selectie wanneer de context is gemaakt, niet een liveweergave van latere wijzigingen.

Queries uitvoeren op projecten met eigenschappen

// Get all projects with name, path, and GUID
IQueryResults<IProjectSnapshot> projects = await workspace.QueryProjectsAsync(
    project => project.With(p => p.Name)
                      .With(p => p.Path)
                      .With(p => p.Guid),
    cancellationToken);

Projecten filteren op capaciteit

// Get only .NET Core web projects
IQueryResults<IProjectSnapshot> webProjects = await workspace.QueryProjectsAsync(
    project => project.Where(p => p.Capabilities.Contains("DotNetCoreWeb"))
        .With(p => p.Path)
        .With(p => p.Guid),
    cancellationToken);

Projectbestanden opvragen

// Get all files in a specific project
IQueryResults<IFileSnapshot> files = await workspace.QueryProjectsAsync(
    project => project.Where(p => p.Guid == knownGuid)
        .Get(p => p.Files.With(f => f.FileName)),
    cancellationToken);

Een bestand toevoegen aan een project

IQueryResults<IProjectSnapshot> updated = await workspace.UpdateProjectsAsync(
    project => project.Where(p => p.Guid == knownGuid),
    project => project.CreateFile("NewFile.cs"),
    cancellationToken);

De naam van een bestand wijzigen

await workspace.UpdateProjectsAsync(
    project => project.Where(p => p.Guid == knownGuid),
    project => project.RenameFile(oldPath, newName),
    cancellationToken);

Een project maken

// Build entire solution
IQueryResults<ISolutionSnapshot> solutions = await this.Extensibility.Workspaces().QuerySolutionAsync(
    s => s, cancellationToken);
foreach (var solution in solutions)
{
    await solution.AsQueryable().BuildAsync(cancellationToken);
}

// Build a single project by name
var result = await this.Extensibility.Workspaces().QueryProjectsAsync(
    project => project.Where(p => p.Name == "MyApp"),
    cancellationToken);
await result.First().BuildAsync(cancellationToken);

Doorzoek NuGet-pakketten

// Get all package references for a project
IQueryResults<IProjectSnapshot> result = await workspace.QueryProjectByGuidAsync(
    project => project.With(p => p.ActiveConfigurations
        .With(c => c.PackageReferences
            .With(pkg => pkg.Name)
            .With(pkg => pkg.Version))),
    knownGuid,
    cancellationToken);

Projecteigenschappen opvragen

IQueryResults<IProjectSnapshot> props = await workspace.QueryProjectsAsync(
    project => project.With(p => p.PropertiesByName("RootNamespace", "AssemblyVersion")),
    cancellationToken);

De oplossing doorzoeken

IQueryResults<ISolutionSnapshot> solution = await workspace.QuerySolutionAsync(
    s => s.With(sol => sol.Path)
          .With(sol => sol.Guid)
          .With(sol => sol.ActiveConfiguration),
    cancellationToken);

Tips

✅ DO

  • Gebruik altijd .With() om op te geven welke eigenschappen u nodig hebt
  • Filteren op capability voordat u de capabilityspecifieke eigenschappen opent
  • Gebruik UpdateProjectsAsync voor mutaties
  • Geef CancellationToken door aan alle asynchrone aanroepen

❌ NIET DOEN

  • Voer geen query's uit zonder eerst te filteren — grote oplossingen worden traag
  • Stel niet dat alle projecttypen alle eigenschappen ondersteunen (bijvoorbeeld SQL-projecten)
  • Probeer IProjectSnapshot niet rechtstreeks te wijzigen — het is onveranderbaar
  • Niet gebruiken CancellationToken.None in productie-extensies

🔧 Problemen oplossen

Symptom Repareren
Eigenschap genereert een uitzondering Controleer PropertiesAvailableStatus eerst
Query retourneert lege resultaten Het filter heeft niets gevonden: controleer de projectmogelijkheden of -namen
CreateFile Mislukt Controleer of het project is geladen en beschrijfbaar is
Capaciteitsspecifieke eigenschappen ontbreken Gebruik WithRequired om te filteren op projecten die daadwerkelijk de eigenschap hebben

Volgende stappen