As a little finger exercise I thought a Visual Studio extension would be good to explain the code – thanks to OpenAI this should be no problem.
It was not.
First, I installed the Extensibilty Template Pack 2022 for Visual Studio 2022.
After that it could begin:
The first thing I did was add a Tool Window. A toolwindow is basically nothing more than a XAML user control and a class that derives from BaseToolWindow
public class ExplicareToolWindow : BaseToolWindow<ExplicareToolWindow>
{
public override string GetTitle(int toolWindowId) => "Explicare";
public override Type PaneType => typeof(Pane);
public override async Task<FrameworkElement> CreateAsync(int toolWindowId, CancellationToken cancellationToken)
{
var dte = await Package.GetServiceAsync(typeof(EnvDTE.DTE)) as EnvDTE80.DTE2;
return new ExplicareToolWindowControl(dte,Package);
}
[Guid("b8381bcb-59d1-4b5c-9951-fdbfb44990c9")]
internal class Pane : ToolWindowPane
{
public Pane()
{
BitmapImageMoniker = KnownMonikers.ToolWindow;
}
}
}
ExplicareToolWindowControl(dte,Package); is the actual UserControl – where we can put any UI elements.
I have now added only one button which I called “Explain to me”.
Quick and dirty in the code-behind made a button click event.
Now read the text from the Visual Studio Editor this is done with:
var textSelection = (TextSelection)MyDTE.ActiveDocument.Selection;
if (String.IsNullOrEmpty(textSelection.Text))
{
TextDocument doc = (TextDocument)(MyDTE.ActiveDocument.Object("TextDocument"));
var p = doc.StartPoint.CreateEditPoint();
TextToExplain = p.GetText(doc.EndPoint);
}
else
{
TextToExplain = textSelection.Text;
}
So the most difficult I have behind me now still a call to the OpenAI API call. This is actually quite simple
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = client.PostAsync("https://api.openai.com/v1/completions", content).Result;
if (response.IsSuccessStatusCode)
{
string responseStr = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<OpenAIResponse>(responseStr);
explained = result.choices[0].text;
}
else
{
throw new BadRequestExecption();
}
The whole source is on Git Hub gpiwonka/Explicare: A small extension for Visual Studio to better understand code using OpenAI. (github.com)
Also available as extension: Explicare – Visual Studio Marketplace