Пользовательское расширение Visual Studio не выполняет командуC#

Место общения программистов C#
Ответить
Anonymous
 Пользовательское расширение Visual Studio не выполняет команду

Сообщение Anonymous »

Сейчас я пробую свое первое собственное расширение Visual Studio 2022. Подробно я хочу создать холст, который рисует точки на основе двойных значений. Теоретически все это происходит, когда я устанавливаю точку останова в другом исходном коде, смотрю на IEnumerable и проверяю представление с помощью увеличительного стекла.
Я просмотрел руководство, которое нашел в Microsoft, и все настроил. и дошел до того, что появилось сообщение, известное как «Привет, мир», теперь я реализовал свою логику, но не могу заставить ее работать и не знаю почему.
Кнопка для ее вызова все еще здесь и Я не получаю сообщения об ошибке
вот мой Command.cs

Код: Выделить всё

using Microsoft;
using Microsoft.VisualStudio.Extensibility;
using Microsoft.VisualStudio.Extensibility.Commands;
using Microsoft.VisualStudio.Extensibility.Shell;
using System.Diagnostics;
using System.Windows.Controls;
using System.Windows.Shapes;
using System.Windows;
using System.Windows.Media;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace MTEnumVisualizer
{
/// 
/// Command1 handler.
/// 
[VisualStudioContribution]
internal class Command1 : Command
{
private readonly TraceSource logger;

/// 
/// Initializes a new instance of the  class.
/// 
/// 
Trace source instance to utilize.
public Command1(TraceSource traceSource)
{

this.logger = Requires.NotNull(traceSource, nameof(traceSource));
}

/// 
public override CommandConfiguration CommandConfiguration => new("%MTEnumVisualizer.Command1.DisplayName%")
{
Icon = new(ImageMoniker.KnownValues.Extension, IconSettings.IconAndText),
Placements = [CommandPlacement.KnownPlacements.ExtensionsMenu],
};

/// 
public override Task InitializeAsync(CancellationToken cancellationToken)
{
this.logger.TraceInformation("Command1 initialized.");
return base.InitializeAsync(cancellationToken);
}

/// 
public override async Task ExecuteCommandAsync(IClientContext context, CancellationToken cancellationToken)
{
this.logger.TraceInformation("ExecuteCommandAsync started.");

Requires.NotNull(context, nameof(context));

// Retrieve debugger data
var dataPoints = await GetDebuggerDataPointsAsync(context, cancellationToken);
if (dataPoints is null || !dataPoints.Any())
{
this.logger.TraceInformation("No data points were retrieved from the debugger.");
return;
}

// Determine the highest value and calculate canvas height
double maxValue = dataPoints.Max();
double canvasHeight = maxValue * 1.1;

// Create window
var window = new Window
{
Title = "Data Points Visualization",
Width = 800,
Height = 600
};

// Create canvas
var canvas = new Canvas
{
Width = 800,
Height = canvasHeight
};

// Draw points on the canvas
foreach (var point in dataPoints)
{
var ellipse = new Ellipse
{
Width = 5,
Height = 5,
Fill = Brushes.Black
};

Canvas.SetLeft(ellipse, point * 100); // Example X-coordinate
Canvas.SetTop(ellipse, canvasHeight - (point * 100)); // Example Y-coordinate

canvas.Children.Add(ellipse);
}

// Add canvas to window
window.Content = canvas;

// Show message
MessageBox.Show("The window will now be displayed.");

// Display window
window.ShowDialog();
}

private async Task GetDebuggerDataPointsAsync(IClientContext context, CancellationToken cancellationToken)
{
// This is where the code to retrieve data points from the debugger should go
await Task.Delay(100); // Simulates an asynchronous operation

// Example data points
var dataPoints = new List  { 1.0, 2.5, 3.8, 4.2, 5.0 };

this.logger.TraceInformation($"Retrieved data points: {string.Join(", ", dataPoints)}");

return dataPoints;
}
}
}

По запросу я выделил минимальный код, точно показывающий фиктивные данные, и асинхронное выполнение, которое, похоже, не выполняется должным образом

Код: Выделить всё

        public override async Task ExecuteCommandAsync(IClientContext context, CancellationToken cancellationToken)
{
this.logger.TraceInformation("ExecuteCommandAsync started.");

Requires.NotNull(context, nameof(context));

// Retrieve debugger data
var dataPoints = await GetDebuggerDataPointsAsync(context, cancellationToken);
if (dataPoints is null || !dataPoints.Any())
{
this.logger.TraceInformation("No data points were retrieved from the debugger.");
return;
}

// Determine the highest value and calculate canvas height
double maxValue = dataPoints.Max();
double canvasHeight = maxValue * 1.1;

// Create window
var window = new Window
{
Title = "Data Points Visualization",
Width = 800,
Height = 600
};

// Create canvas
var canvas = new Canvas
{
Width = 800,
Height = canvasHeight
};

// Draw points on the canvas
foreach (var point in dataPoints)
{
var ellipse = new Ellipse
{
Width = 5,
Height = 5,
Fill = Brushes.Black
};

Canvas.SetLeft(ellipse, point * 100); // Example X-coordinate
Canvas.SetTop(ellipse, canvasHeight - (point * 100)); // Example Y-coordinate

canvas.Children.Add(ellipse);
}

// Add canvas to window
window.Content = canvas;

// Show message
MessageBox.Show("The window will now be displayed.");

// Display window
window.ShowDialog();
}

private async Task GetDebuggerDataPointsAsync(IClientContext context, CancellationToken cancellationToken)
{
// This is where the code to retrieve data points from the debugger should go
await Task.Delay(100); // Simulates an asynchronous operation

// Example data points
var dataPoints = new List { 1.0, 2.5, 3.8, 4.2, 5.0 };

this.logger.TraceInformation($"Retrieved data points: {string.Join(", ", dataPoints)}");

return dataPoints;
}
Я попытался просто добавить MessageBox.Show(), чтобы определить, не сломается ли мой код в какой-то момент, и моя логика просто неверна. Но он не появился, поэтому я могу только предположить, что этот блок вообще не вызывается. Я вернул его в исходное состояние с помощью «Hello World», и все работало нормально

Подробнее здесь: https://stackoverflow.com/questions/789 ... te-command
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»