VS2017, VSIX: just created AsyncPackage is not being instanced - visual-studio

This is default VSPackage. I added only ProvideAutoLoad attributes.
using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.Win32;
using Task = System.Threading.Tasks.Task;
namespace VSIXProject1
{
/// <summary>
/// This is the class that implements the package exposed by this assembly.
/// </summary>
/// <remarks>
/// <para>
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell. These attributes tell the pkgdef creation
/// utility what data to put into .pkgdef file.
/// </para>
/// <para>
/// To get loaded into VS, the package must be referred by <Asset Type="Microsoft.VisualStudio.VsPackage" ...> in .vsixmanifest file.
/// </para>
/// </remarks>
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)] // Info on this package for Help/About
[Guid(VSPackage1.PackageGuidString)]
[ProvideAutoLoad(UIContextGuids.NoSolution, PackageAutoLoadFlags.BackgroundLoad)]
[ProvideAutoLoad(UIContextGuids.SolutionExists, PackageAutoLoadFlags.BackgroundLoad)]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "pkgdef, VS and vsixmanifest are valid VS terms")]
public sealed class VSPackage1 : AsyncPackage
{
/// <summary>
/// VSPackage1 GUID string.
/// </summary>
public const string PackageGuidString = "cca56365-4b14-4a96-9280-c30dce400195";
/// <summary>
/// Initializes a new instance of the <see cref="VSPackage1"/> class.
/// </summary>
public VSPackage1()
{
// Inside this method you can place any initialization code that does not require
// any Visual Studio service because at this point the package object is created but
// not sited yet inside Visual Studio environment. The place to do all the other
// initialization is the Initialize method.
}
#region Package Members
/// <summary>
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initialization code that rely on services provided by VisualStudio.
/// </summary>
/// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param>
/// <param name="progress">A provider for progress updates.</param>
/// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns>
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
// When initialized asynchronously, the current thread may be a background thread at this point.
// Do any initialization that requires the UI thread after switching to the UI thread.
await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
}
#endregion
}
}
Looks like it's not being instanced. If I'm adding break point or Debug.WriteLine(...) then nothing happening. When I'm adding Command then also nothing. I only can see my extension in Extensions and Updates window.
I recorded the little video with step by step reproduction my problem:
https://youtu.be/B2T311Ug5FQ
What I should to do to my package gets instanced?

I started from the default package template and for me it turned out that adding the attribute
[ProvideAutoLoad(UIContextGuids80.NoSolution, PackageAutoLoadFlags.BackgroundLoad)]
to the package class made things work. Try going back to the default template and add that line, then debug.
To me this is a bug in the template. Templates should just work without needing to hunt around on stackoverflow for ages to find the magical missing incantation. Obviously you just want to hit the debug key and see the breakpoint hit, then build out from there.

I had this problem with an extension taken over from Visual Studio 2017, which was before taken over through all intermediate Visual Studio Versions, I think maybe created on VS2010. I changed two things or more, but I don't know which of these made it work.
Similar to satnhak above had to add
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExists_string, PackageAutoLoadFlags.BackgroundLoad)]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionHasMultipleProjects_string, PackageAutoLoadFlags.BackgroundLoad)]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionHasSingleProject_string, PackageAutoLoadFlags.BackgroundLoad)]
In my .csproj removed a line
<OldToolsVersion>14.0</OldToolsVersion>
I found these by comparing a newly created extension from template and comparing all properties (argh).
Also found out that after uninstalling the extension I had to start up Visual Studio one time with another solution to finish the uninstallation process completely. I guess it has a flag somewhere which blocks the instantiation of a newly installed one until this has been fully completed. Sorry all a bit fuzzy.
In any case also something good to know is that problems are logged in these locations:
%appdata%\Microsoft\VisualStudio\16.0_d1c373d5\ActivityLog.Setup.xml
%appdata%\Microsoft\VisualStudio\16.0_d1c373d5\ActivityLog.xsl
%appdata%..\Local\Temp\dd_VSIXInstaller_*.log
Every successful instantiation is logged in the last one.

My scenario was: I created a VSIX project in VS2022 and then added an AsyncPackage to it. I hadn't noticed that the VSIX project already contained another package.
The other AsyncPackage was both instantiated and initialized. Therefore, I removed the one I added and used the pre-existing one, problem solved.
I cannot find any documentation about it, but it looks that each VSIX only loads just one package.
see VSIX: how to pack two or more vspackage into a vsix

It is now 2022 and the template is still not fixed. Very happy I found this post after just a few hours of going insane.
adding
[ProvideAutoLoad(UIContextGuids80.NoSolution, PackageAutoLoadFlags.BackgroundLoad)]
to the main AsyncPackage made it load!

Related

Visual Studio WInForms Designer Images from Resources file

When I set the Image property of a Button control to point to an image in the Projects resource file, it shows up just fine in the application when I compile and run it, but if I try to load the form in the designer, it gives me an 3error message.
The type 'CoP.LAS.Properties.Resources' has no property named
'Adobe1'.
Although when I look in the auto-generated Resources file, it is clearly there:
namespace CoP.LAS.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute(
"System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
// Other stuff...
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Adobe1 { // <--- HERE!!!
get {
object obj = ResourceManager.GetObject("Adobe1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
And the designer will not load the form unless I ignore this error, which removes the setting from the form code. The only way I have been able to fix this is to import the graphic into the project for each place in the project where I want to display it. This is, obviously redundant, as the image is being "imported" for every usage. I should be able to use images in the project's common resource file and still load the form into the designer.
What's going on here and how do I fix this.

Visual Studio Extension: Track when new code window is opened?

I'm trying to write a Visual Studio Extension that tracks when a new code window is opened. I found a class IVsCodeWindowEvents that seems to provide listener methods for that:
public int OnNewView(IVsTextView pView)
However, I have a problem that I don't know how to register to listen to these events.
My class looks like this:
public sealed class VSTrackerPackage : Package, IVsCodeWindowEvents
In this class, I implement the OnNewView method, but how can I register this listener in my Initialize method?
Yes you can register for Visual Studio events via the DTE and more specifically DTE2.
First step is to get access from your Package via the Initialize method:
public sealed class VSTrackerPackage : Package
{
DTE2 dte = GetService(typeof (DTE)) as DTE2;
}
At this point, I'd recommend attaching to the DocumentEvents.DocumentOpened event. From there you can check if it's a document you are interested in or not. You can also get the Window if you need to interact with it there:
_dte.Events.DocumentEvents.DocumentOpened += document =>
{
//double check this logic.
if (document.Language != "C#")
return;
//do work
//or - load window document.ActiveWindow.
};
If it helps, I have an open source Visual Studio plugin (shameluss plug: pMixins ) that attaches to a number of VS events. Relevant class is on GitHub: https://github.com/ppittle/pMixins/blob/master/CopaceticSoftware.CodeGenerator.StarterKit/Infrastructure/VisualStudioEventProxy.cs. Class definition starts on line 243.

Strange MethodMissingException

I have stumbled upon interesting problem which is destroying me last couple of hours. I have project in VS, in references I have library Communication.dll, which contains class Service.
I am invoking following method:
public void ConnectPipe()
{
Service service = new Service();
service.ConnectionMode = ConnectionModes.PIPE;
service.Connect();
}
when I run it, on second line I get MissingMethodException - Method not found: 'Void Service.set_ConnectionMode()'
when I press F12 on service class, I get the Assembly info for the class. When I look for my property, setter is in place, so it does not look like problem with referenced library:
public ConnectionModes ConnectionMode { get; set; }
has anyone any idea where problem might be please?
Had the same issue. Fixed by updating reference to the library.
Point to the exact file on the local, through button "Browse..." don't choose from the library list in references manager - that doesn't work correctly sometimes.
And rebuild the referenced assembly.

MVVM-light There is already a factory registered for INavigationService

I'm trying to adjust my WP8 project from self made MVVM implementation to MVVM Light.
The application compiles without errors, but when I open my MainPage.xaml in Expression Blend, I will get this error:
Class project.Services.INavigationService is already registered. App.xaml
My ViewModelLocator.cs:
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
}
else
{
if (!SimpleIoc.Default.IsRegistered<INavigationService>())
{
SimpleIoc.Default.Register<INavigationService>(() => new NavigationService());
}
}
SimpleIoc.Default.Register<MainPage>();
SimpleIoc.Default.Register<SettingsEditViewModel>();
}
As you can see from my code comment, I've already tried the fix supposed here, but I'm still getting this error in Blend. There is no other place left where I could register the INavigationService, so what could be the problem?
Any ideas? :)
I had the same issue, and this seems to be a Visual Studio issue in combination with XAML-Designer, Static Factories/Locators and Design-Time creation of objects. However: The solutions were the following:
Register without a factory (not recommended)
SimpleIoc.Default.Register<INavigationService>();
Or if you want to use a factory, unregister before registering the factory
SimpleIoc.Default.Unregister<INavigationService>();
SimpleIoc.Default.Register<INavigationService>(() => new NavigationService());
Prevent the ViewModelLocator from being created more than once by the designer/Blend by making the constructor static
static ViewModelLocator() { ... }
The error is cumbersome but could happen in this scenario: You create objects during design-time (the ViewModelLocator within App.xaml probably) and whenever you change something in your Code, the Compiler is triggered and the ViewModelLocator gets re-created without ever unregistering the services. Therefore it will complain that in the factory has already been registered. In theory, when registering classes without factories multiple times, there should be an error as-well.
Might already be solved by now, but I think you can just solve the issue in your example case by not using the factory method override.
SimpleIoc.Default.Register<INavigationService, NavigationService>();
If you do need a factory method, then you can mix this line in with your factory method approach using the design mode check like you have been.
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<INavigationService, NavigationService>();
}
else
{
SimpleIoc.Default.Register<INavigationService>(CreateNavigationService);
}
This seems like a super old question, but after hours of googling, this is the only question that's similar to my problem, so answering here for other people.
Make sure that you have IsDataSource on your ViewModelLocator:
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
That solved my problem and my design data popped up straightaway.
Weirdly, after putting that on, all my "INavigationService is already registered" errors goes away!
Not sure why, but I only get this error when my xaml designer window is open. When I compile with it closed, the error goes away and the project is built and runs successfully.

PROBLEM :An error message cannot be displayed because an optional resource assembly containing it cannot be found

I created Windows Mobile Application and I loaded web service that contain one method (GetNumber). When I call this method from my emulator I got a following exception
An error message cannot be displayed because an optional resource assembly containing it cannot be found.
Can anyone help me. This is my code from WM Application, it is very siple.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MobileClientApp;
namespace MobileClientApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MobileClientApp.localhost.WebService m = new MobileClientApp.localhost.WebService();
int result;
bool resbool;
m.GetNumber(10, true, out result, out resbool);
label1.Text = result.ToString();
}
}
}
For a very good explanation:
http://blogs.msdn.com/b/netcfteam/archive/2004/08/06/210232.aspx
(excerpt from above)
There has been some confusion about the error message: "Could not find resource assembly". Basically, this means that there is some exception that has happened in the program. The error did not happen because it could not find the resource assembly. The resource assembly that it is searching for contains exception messages (strings) that would be helpful in debugging what went wrong with the program.
Since the user is never expected to see this error message if the program works as expected and all exceptions are handled appropriately, it was decided (due to size constraints) that the resource assembly that has these error strings are never put on a user's device. Thus the main target audience of these error strings are developers who would like to debug issues. Hence, when you do an F5 deploy onto the device, the System.SR.dll assembly which have these error strings are copied to the device and the developer can see the error messages. But in case .Net Compact Framework is installed from a redistributable or you are using .Net Compact Framework that come with the device (as a user of the device would be doing), the System.SR.dll is not present on the device. Hence, if the application did come upon an exceptional condition that wasn't handled by the application, this "Could not find resource assembly" message would be shown to the user.
If you are not using Visual Studio F5 deploy to the device and would still like to see the exception messages, you can achieve this by taking the System_SR_[Language].CAB where [Language] corresponds to the language in which you want to see the error message to appear and clicking on the cab file to install it
Sounds like you are missing an assembly in your deployment.

Resources