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.
Related
I have a folder called Documentation inside the shared project, named App2 in this case. How do I access the files stored inside the Documentation folder? Attached image below shows the project structure.
Visual Studio Solution Page
I have tried out following commands but they aren't working :
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
AppDomain.CurrentDomain.BaseDirectory
System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
If it's troublesome to access the file in that folder, I'm open to hearing other alternatives.
This is how I have done it for JSON files in my shared project (using PCL). As Jason pointed out in the comments, if you are using .NET Standard, you can simply define the GetSharedFile method in your shared project instead of creating platform specific references.
Add the file to the shared project and set it as Embedded Resource
Create an IFileHelper interface in your shared project
public interface IFileHelper {
Stream GetSharedFile(string fileResourceName);
}
Create a new FileHelper class in each project (Android and iOS) with the following
public class FileHelper : IFileHelper {
public Stream GetSharedFile(string fileResourceName) {
Type type = typeof(IFileHelper); // We could use any type here, just needs to be something in your shared project so we get the correct Assembly below
return type.Assembly.GetManifestResourceStream(fileResourceName);
}
}
Add a documentation handler class in your shared project. Something like below (make sure to change the App namespace to match yours):
public class Documentation {
private const string ResourcePath = "App.Documentation.index.html"; // App would be your application's namespace, you may need to play with the Documentation path part to get it working
public string GetDocs() {
IFileHelper helper = DependencyService.Get<IFileHelper>(); // Your platform specific helper will be filled in here
Stream stream = helper.GetSharedFile(ResourcePath);
using (stream)
using (StreamReader reader = new StreamReader(stream)) {
return reader.ReadToEnd(); // This should be the file contents, you could serialize/process it further
}
}
}
I wrote this mostly by hand so let me know if something is not working. If you cannot load your file, I suggest trying to put it into the root of your shared project and then changing ResourcePath in the code above to the following (again using your app's namespace instead of App):
private const string ResourcePath = "App.index.html";
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!
In my previous investigation I discovered that even though windows file explorer launches word.exe in an embedded state the Documents collection remains empty.
Excel and word opened in Windows Explorer preview panel have Workbooks.Count and Documents.Count equal to 0
A bit further research when I made the embedded applications visible they would load with out a document inside of it:
public static class WordAppExt
{
public static Word.Document GetActiveDoc(this Word.Application App)
{
try
{
App.Visible = true;
if (App.Documents.Count > 0)
{
return App.ActiveDocument;
}
else
{
return null;
}
}
catch (Exception)
{
return null;
}
}
}
SO I came to the conclusion that explorer only needs to launch word, but it does not have the documents hosted inside of word. which means windows explorer is likely a IOleContainer. If true this means any object embedded in the preview pane can be accessed via EnumObjects.
Unfortunately my code runs in a VSTO addin, I don't have access to the explorer com objects so I can't do a QI for IOleContainer. But I have a theory that there maybe another way of accessing the Document COM object, through the PreviewHandler. I think that the reason Word, Powerpoint, and Excel get launched is either to register or initialization of the previewHandler?
So HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\PreviewHandlers has a list of guids associated with IPreviewHandler for different file types.
There are plenty of articles about how to create your own previewHandler for new file types:
Building Preview Handlers
How to Register a Preview Handler
PreviewHandler.cs
Hosting Preview Handlers in Windows Forms Applications
Preview Handlers Revisited
http://www.codeproject.com/Articles/19744/Using-Preview-Handlers-in-Windows-Vista
https://code.msdn.microsoft.com/CppShellExtPreviewHandler-58db53b8
But I want to replace Words Preview Handler with my own. If I can't replace it I'd be more than happy to intercept the existing Preview Handler.
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.
When I create an outlet in Xcode, MonoTouch creates identical properties in the *.designer.cs file for that particular view.
namespace MyApp
{
[Register ("CustomCell")]
partial class CustomCell
{
[Outlet]
MonoTouch.UIKit.UISwitch Toggle { get; set; }
void ReleaseDesignerOutlets ()
{
if (Toggle != null) {
Toggle.Dispose ();
Toggle = null;
}
}
}
}
but as you can see, scopes those properties as private.
Is there a way through XCode or MonoTouch to tell the system these should be generated as public, protected or internal?
Granted I could expose properties in the implementation side of this partial class that act as proxies to these properties but I am hoping there is a cleaner way.
Don't worry that they're properties, this is an implementation detail of outlets. You can think of them as private fields - so it's fine to expose them via more accessible properties on the non-designer class part.
Another way to make them more accessible is to move them to the non-designer class part. Outlets don't have to be in the designer class part.
How syncing works:
The way the designer files work is that when MD syncs to Xcode, it finds all outlets on all parts of the class, including the designer class, and syncs those into the obj-c header file. When it syncs the obj-c header file back to MD, it tries to find each of the outlets in the non-designer class parts, then regenerates the designer file with the unmatched outlets.
This means that if you add an outlet in obj-c header file, it will get added into the designer file. It also means that if you remove an outlet in the obj-c header file, it will effectvely get removed from the designer file when the designer file is regenerated - unless it's in some other class part, in which case the removal will not be synced.
The outlets in the obj-c header file do not have any accessibility, so MD cannot sync that when it regenerates the header file, and private is a good default since it promotes encapsulation, and you can easily expose them if needed via wrapper properties or by moving them.
There is currently no way to make MonoDevelop generate different visibility attributes for outlets exposed.
What is the use case scenario that you have in mind?