Advanced Templates/Snippets for Visual Studio - visual-studio

I'm using Visual Studio 2013 with Resharper 8.1 installed and I'm all about finding shortcuts for regular tasks. One such task that I do regularly is add new constructor dependencies to MVC Controllers. So for example, I might have the following:
public class MyController : Controller {
private readonly ICustomerManager _customerManager;
public MyController(ICustomerManager customerManager) {
_customerManager = customerManager;
}
Now I want to add in an IOrderManager, so I have 3 different lines to adapt: I have to add a private variable to store it, add a parameter to the constructor, and add a line inside the constructor to set the private variable.
I'd love to be able to write a macro/template/snippet that would allow me to enter "IOrderManager" and have it add all the code for me. Is there any way I can do this in VS2013 or Resharper?

The easiest thing is to add the field manually, then Alt+Enter and let ReSharper initialise the field from the constructor. It will add the parameter, and initialise the field with it.

Related

VisualStudio IntelliSense suggestion failure

I have a problem with IntelliSense and it is driving me crazy, I kept calm for 1 month but I can't stand it anymore.
IntelliSense keeps on suggesting things that are obviously incorrect suggestions.
Let's say I have a class called "PlayerModel" and a field/parameter of that type called "playerModel".
When I start typing "player" I somehow expect that the suggestions list will start with the field/parameter and not with the class, also given that the class obviously does not contain public constants or anything I might be using.
But this is not the case, IntelliSense gives me this every time:
Obviously I want to refer to the parameter and not the class.
This doesn't work also if I need to assign a value to a field.
PlayerModel anotherPlayerModel = player...
will also suggest the class instead of that parameter. So every time I need to manually select the second (and proper) suggestion.
Please help, I think this should be common sense. Thank you!
These are my installation package details:
Microsoft Visual Studio Community 2017
Version 15.8.5
VisualStudio.15.Release/15.8.5+28010.2036
Microsoft .NET Framework
Version 4.7.02556
Installed Version: Community
C# Tools 2.9.0-beta8-63208-01
FormatDocumentOnSave 1.0
NuGet Package Manager 4.6.0
ProjectServicesPackage Extension 1.0
Visual Basic Tools 2.9.0-beta8-63208-01
Visual Studio Code Debug Adapter Host Package 1.0
Visual Studio Tools for Unity 3.8.0.7
And this is my PlayerModel class: (ignore the Unity related stuff it is not relevant to the structure of the class)
using UnityEngine;
using static Constants;
public class PlayerModel : ObjectModel {
public int userId;
public int activeItemIndex;
public int kills;
public PlayerModel(int id, Vector3 position, Quaternion rotation, float hitpoints, int userId, int activeItemIndex) : base(id, ObjectType.PLAYER, position, rotation, hitpoints) {
this.userId = userId;
this.activeItemIndex = activeItemIndex;
}
}
Please try switching your locale--as a test--from 1026 bg-BG to 1033 en-US. So, first close all instances of Visual Studio, apply the locale change, then restart Visual Studio. I suspect that this might fix the issue. If it does then you can decide which international setting you want to continue to use...

Can I pass an argument/switch/parameter to a VSPackage MenuCommand?

I was hoping someone here might be able to help me out with this. I'm not the most experienced programmer but I'm making progress on a project.
I've got a need to programmatically interact with Visual Studio. Some success has been had using EnvDTE Interop stuff, but it seems that some of what I need to do needs to be done inside VS so I'm attempting to utilize a VSPackage MenuCommand to do various things. Sorry the vagueness.
I'm currently successfully creating a custom MenuCommand with a VSPackage extension, and also am able to trigger that MenuCommand programmatically from another application using the DTE.
What I'm wondering is: is it possible to define a MenuCommand that CAN take arguments passed along to it from the triggering external application?
Using the VS Package Template in Visual Studio 2012 using the Menu Command option, all my code lives inside this method:
private void MenuItemCallback(object sender, EventArgs e)
{
// my code...
}
There is obviously a lot of other auto-generated code plumbing this all together, but all MY code lives in this method. Is there a way to alter this method so that it will allow parameters to be passed to it? What other changes must I make to the other files to declare/register this differently-functioning method once I do so (if I can)?
For example:
static void Main(string[] args)
{
Type visualStudioType = Type.GetTypeFromProgID("VisualStudio.DTE.11.0");
DTE dte = Activator.CreateInstance(visualStudioType) as DTE;
dte.MainWindow.Visible = true;
dte.ExecuteCommand("myCommand");
}
This works. But what I'd like to do is change that last command to:
dte.ExecuteCommand("myCommand", "myArguments");
When I attempt to do something like this, I receive the following exception:
"Command \"myCommand\" does not accept arguments or switches."
Sorry if I'm not being clear. Any help would be greatly appreciated.
Commands created from add-ins accept parameters by default.
Commands created from packages need to specify the <CommandFlag>AllowParams</CommandFlag> when defining the command in the .vsct file. See: http://msdn.microsoft.com/en-us/library/bb491716.aspx
And see also this thread:
IOleComandTarget::exec for commands with parameters
https://social.msdn.microsoft.com/Forums/en-US/134983e8-049c-40e1-a212-312fa637698b/iolecomandtargetexec-for-commands-with-parameters?forum=vsx
Then, it should work, either using dte.ExecuteCommand or dte.Commands.Raise(...). See:
HOWTO: Pass parameters programmatically to a command from a Visual Studio add-in
http://www.visualstudioextensibility.com/articles/add-ins/

VSIX doesn't register itself to Help/About window in VS2013

I'm trying to develop a VS extension using the Visual Adornment project template.
The extension is working on the experimental instance of VS (it simply adds a text layer on the editor window), but now I'm trying to add 2 features, with no luck:
Help/About entry for the extension
Settings page for some basic configurations
So I started to study some other extension to understand how they do that, taking as example this from Phil Haack Encourage.
No way I can get it to work. I created a class that inherits from Microsoft.VisualStudio.Shell.Package and I've decorated it with all the needed attribute to have the Help/About entry, without any success.
[PackageRegistration(UseManagedResourcesOnly = true)]
[ComVisible(true)]
[InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
[Guid("665d2c8c-0d47-42b6-ae34-e1db4ac2ed0f")]
public sealed class MyPackage : Package
{
public MyPackage()
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
}
protected override void Initialize()
{
base.Initialize();
Debug.WriteLine("Initialize MyPackage");
}
}
Not only the package is not registering, but the debug lines are not written at all, I cannot even step in with the debugger.
I took a look around the web, and any article I found sounds like this one, even following any single step, my package is not registering itself BUT, and it is the strange thing, the viewport adornment it's working as expected...
UPDATE:
I can add some details: it seems that during the build the .pkgdef file is not created at all in the debug folder, and it's not added to the VSIX file (if I open it with 7zip there's no .pkgdef)
No way I can get it to work. I created a class that inherits from Microsoft.VisualStudio.Shell.Package and I've decorated it with all the needed attribute to have the Help/About entry, without any success.
I didn't understand that part quite. You're supposed to use Visual Studio "project template" for "Visual Studio packages". That will create all the stuff necessary to build VSIX file. Start with that, if you already haven't.
By default, Visual Studio extensions(>=2013) don't load automatically. This took me few hours of debugging, but you're supposed to decorate your package with an attribute if you'd like to load when Visual Studio starts up. Alternatively, there's an option to load your VSPackage once a solution is loaded.
This is a peek of my package definition:
[PackageRegistration(UseManagedResourcesOnly = true)]
[InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
[Guid(Guids.GuidMyStudioPackageString)]
[ProvideAutoLoad(UIContextGuids.NoSolution)]
[ProvideMenuResource("Menus.ctmenu", 1)]
public sealed class MyPackage : CommonPackage
Notice the [ProvideAutoLoad(...)] option. It says that load the package once visual studio starts.

Extracting an interface from .NEt System classes

When using Visual Studio it is easy to extract an interface from a class that I have written myself. I right click on the class and select 'Refactor' then select 'Extract Interface'.
Let's assume for a second that I wanted to create a ConfigurationManager wrapper and write some tests around it. A quick way to do that would be to extract an interface from ConfigurationManager by right clicking it, then 'Go To Definition' and then from inside the class select 'Refactor' then select 'Extract Interface'. Then I would simply create my wrapper class, inherit from my newly created interface, and then implement it and I have a great starting point for my wrapper class.
However, extracting an interface from any .NET system classes is not possible, probably because it's just meta data about the classes and not the classes themselves (or I am doing it wrong).
Is there an easy way to do what I am trying to accomplish? I want to ensure I am not wasting time typing what I don't need to be typing.
Thanks
The problem is not so much to extract the interface - you could also do this 'by hand'
But you have no way to tell the CLR that the System-defined Configuration manager implements this interface since this (meta-)information is stored in the framework assembly which you cannot modify.
EDIT:
To ease the 'extraction by hand' you can click with the right button on the type and select "Go to Definition". Visual Studio creates a class definition (without implementation) from the metadata. You can then use copy and paste into a new file. Anyway you'll still have to do some modifications by hand
Replace the class keyword by interface
remove all non-public methods/properties
remove the public and override access modifiers (they are invalid in an interface definition)
This can be done easily using search&replace. You'll even get the documentation strings with this approach.

How does visual studio associate mfc dialog classes with dialog resources?

I was wondering how Visual Studio associates MFC CDialog derived classes with their corresponding dialog resources. I'm not interested in how the connection is made at run time (as asked here), but rather at design time.
When I add a message handler to a dialog, how does it know which class to add the handler to.
Also, is it possible to have several CDialog derived classes associated with the same dialog resource and vice versa?
I have searched the project directory for the IDD_SOMEDIALOG string but have only found it in SomeDialog.h, resource.h and Project.rc in the expected places so I guess it somehow deduces the connection from those files, most likely the enum in SomeDialog.h:
// in class CSomeDialog:
enum { IDD = IDD_SOMEDIALOG };
I'm asking this mostly out of curiosity.
It depends on what version of dev studio.
In VS6 it was all kept in the CLW (Class Wizard File).
In newer versions of dev studio it doesn't use the CLW anymore and I don't know specifically how it knows, but i suspect its a live parsing instead of using a cached CLW.
As for having multiple derived dialogs using the same resource, it can be done manually. You can duplicate the created class files and rename them and remove the enum from header and edit the use of the IDD enum in the source file to be the actual dialog resource id (IDD_SOMEDIALOG).
AFAIK Dev Studio will only 'happily' handle one class to a dialog at a time. In my experience trying to re-use a dialog resource like this just ends up in a bit of battle with MFC & Dev Studio since they were not intended to do this.
To add to Ruddy's answer:
I noticed that some of my dialog classes in which I replaced the enum { IDD } with static const int IDD was not any longer associated with its dialog resource. Reverting to the enum re-associated them. So it seems that visual studio parses the source code to determine the relationships.
As for resource sharing, it would be ambiguous as to which class should receive the event handler code. Class sharing seems to be be impossible since it relies on the IDD which can not be assigned to a IDD_SOMETHING and IDD_SOMETHING_ELSE simultaneously.

Resources