2

I'm trying to make a extension for visual studio after watching a video on Youtube of how to get started. After following some instructions I ran across a littler error when trying to set up the extension for a custom command in the Menu under tools.

DTE2 dte = (DTE2)ServiceProvider.GetServiceAsync(typeof(DTE));

My ServiceProvider is a IAsyncServiceProvider rather than ServiceProvider. So is there a way I can make a DTE2 object wihtout changing everything from IAsyncServiceProvider to ServiceProvider.

My Code:

<code>       public static async Task InitializeAsync(AsyncPackage package)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);
            OleMenuCommandService commandService = await package.GetServiceAsync((typeof(IMenuCommandService))) as OleMenuCommandService;
            Instance = new FRC(package, commandService);
    }

        public static void ExecuteCommand(DTE2 dte, string commandName)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var command = dte.Commands.Item(commandName);
            if (command.IsAvailable)
            {
                dte.ExecuteCommand(command.Name);
            }
        }

        private void Execute(object sender, EventArgs e)
        {
            DTE2 dte = package.GetServiceAsync(typeof(DTE2)) as DTE2;
            ThreadHelper.ThrowIfNotOnUIThread();
            ExecuteCommand(dte, string.Format("View.ClassView"));
        }
    }
</code>

His code: var dte = (DTE2)ServiceProvider.GetService(typeof(DTE));

TomCold
  • 83
  • 6
Jacob Chafin
  • 130
  • 12

2 Answers2

4

The video you are talking about : https://www.youtube.com/watch?v=MFiRotBsVKU

I used Andre.L solution and its working.

There is two line to change in the code and its in the function

private void Execute(object sender, EventArgs e)

first by adding to keyword async into the function signature

private async void Execute(object sender, EventArgs e)

and then by changing this line

DTE2 dte = package.GetServiceAsync(typeof(DTE2)) as DTE2;

into this

var dte = await package.GetServiceAsync(typeof(DTE)).ConfigureAwait(false) as DTE2;
1

It's an async function, try this instead:

private async void Execute(object sender, EventArgs e)
{
    var dte = await package.GetServiceAsync(typeof(DTE));
    DTE2 dte2 = dte2 as DTE2;
    if(dte2 != null){
        ExecuteCommand(dte2, string.Format("View.ClassView"));
    }
}

Or, with ConfigureAwait:

private async void Execute(object sender, EventArgs e)
{
    DTE2 dte2 = await package.GetServiceAsync(typeof(DTE)).ConfigureAwait(false) as DTE2;
    if(dte2 != null){
        ExecuteCommand(dte2, string.Format("View.ClassView"));
    }
}
Andre.L
  • 36
  • 1
  • 7