VS SDK: ToolWindowPane hides when debugging - visual-studio

I used the VS 2010 SDK to create and show a custom ToolWindowPane with a WPF control as content. I create a new instance and show it each time a Tool menu item is clicked (the ProvideToolWindow attribute has MultiInstances = true).
When the user attaches the debugger (e.g., hits F5 while in C# project) my ToolWindowPane suddenly hides. I'd like to make sure my tool window is always visible while open, no matter what context the user is in. Is there a way I can enforce that?
I've tried using the ProvideToolWindowVisibility attribute but that automatically shows a new instance of my tool window rather than keeping a remaining one open.

For VS 2010 SDK Microsoft added a new flag __VSCREATETOOLWIN2.CTW_fDocumentLikeTool
You can use this way:
public override void OnToolWindowCreated()
{
IVsWindowFrame windowFrame = Frame as IVsWindowFrame;
object varFlags;
windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_CreateToolWinFlags, out varFlags);
int flags = (int)varFlags | (int)__VSCREATETOOLWIN2.CTW_fDocumentLikeTool;
windowFrame.SetProperty((int)__VSFPROPID.VSFPROPID_CreateToolWinFlags, flags);
}
This way Tool Window persist open at "Document Well" when you go Debugging
However I have to say this give us some problems when debugging projects, avoiding us to open code files while debugging, like if Visual Studio document management was 'block', there are not so much information for this new flag...
So we preferred to hook to EnvDTE.DebuggerEvents and show the ToolWindow if hide when a debugging session start...
(our ToolWindow has MultiInstances = false)

Implement QueryShowTool
public:
int QueryShowTool(Guid % rguidPersistenceSlot, System::UInt32 dwId, [Runtime::InteropServices::Out] int % pfShowTool);
Enables the VSPackage to control whether to show or hide the tool
window. The shell calls this method when the user switches views or
contexts, for example Design, Debugging, Full Screen.
See https://learn.microsoft.com/en-us/visualstudio/extensibility/opening-a-dynamic-tool-window?view=vs-2017

Related

Is there a keyboard shortcut to enable/disable "Common Language Runtime Exceptions" in Visual Studio exception settings?

I find myself enabling and disabling the "Common Language Runtime Exceptions" checkbox in Exception Settings with considerable regularity. I'm tired of having to open the window every time. Is there a keyboard shortcut?
EDIT: as the answer as of June 2020 appears to be "no", I've requested a feature here: https://developercommunity.visualstudio.com/idea/1073035/keyboard-shortcut-to-enabledisable-the-common-runt.html
Is there a keyboard shortcut to enable/disable “Common Language
Runtime Exceptions” in Visual Studio exception settings?
I think there is no such quick shortcut to do that.
Actually, the shortcut for the Exception window is Ctrl+Alt+E, you can call such window by that.
However, VS only has a shortcut key to open a window, and there is no shortcut key to enable or disable an exception, and there are many different types of exceptions in the exception window. So it can be a bit difficult.
So you should use shortcut Ctrl+Alt+E to open Exception and then set the exception manually.
Besides, if you still want that feature to have a keyboard shortcut to enable/disable Common Language Runtime Exceptions, you can suggest this feature on our User Voice Forum.
After that, you can share the link with us here and anyone who is interested in this feature will vote it so that it will get more attention from Microsoft.
It is managed by the DebuggerServiceHelper class in VSDebugCoreUI.dll:
ExceptionSettingsBatchOperation{_operationDepth=3} DebuggerServiceHelper.BeginExceptionBatchOperation()
DebuggerServiceHelper.UpdateException(EXCEPTION_INFO150{bstrProgramName=null, bstrExceptionName="Common Language Runtime Exceptions", dwCode=0, dwState=16418})
ExceptionSettingsBatchOperation.EndBatchOperation()
But these are all internal classes and not easily accessible from external code.
Another approach is to find this WPF CheckBox on screen (by the TextBlock following it with the given Text property) and click it programmatically.
I really wish Exception Breaker worked for later versions of Visual Studio.
In combination with this answer to a similar question, I was able to get something to work. It is not ideal, but you might give this a try.
Note: I am using Visual Studio 2019
Tool required
The free version of the Visual Commander extension that allows Visual Studio macros in later versions.
Note: I tried (a little) to use the Macros for Visual Studio extension, but with no luck
Steps
Using Visual Commander, add a new command with the code below, save and compile.
Run with one of:
Run directly from the Visual Commander UI
Modify a toolbar and add the Extensions/Command01 command to it
Add a Keyboard shortcut via Options and select VCmd.Command01
Code
Notes:
I tried toggling the <All Common Language Runtime Exceptions not in this list> item, but did not have luck with it.
I tried looping through all of the Exceptions in the group but it was really slow (i.e. 15 seconds :-( ) so I picked the most important exceptions for my project.
I was unsuccessful finding a away to toggle the parent Common Language Runtime Exceptions, but if you find it, please leave a comment.
using EnvDTE;
using EnvDTE80; // DTE2 type
using EnvDTE90; // Debugger3
public class M : VisualCommanderExt.ICommand
{
public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
{
var lDebugger = DTE.Debugger as Debugger3;
var lExceptionSettings = lDebugger.ExceptionGroups.Item("Common Language Runtime Exceptions");
// Use this Exception as the master toggle
bool lExceptionsEnabledToSet = !lExceptionSettings.Item("System.ArgumentException").BreakWhenThrown;
// 2 examples
lExceptionSettings.SetBreakWhenThrown(lExceptionsEnabledToSet, lExceptionSettings.Item("System.ArgumentException"));
lExceptionSettings.SetBreakWhenThrown(lExceptionsEnabledToSet, lExceptionSettings.Item("System.OutOfMemoryException"));
// This does not work to set the whole group on/off:
//lExceptionSettings.SetBreakWhenThrown(true, lExceptionSettings.Item("<All Common Language Runtime Exceptions not in this list>"));
// This is really slow
//foreach (var lExceptionSetting in lExceptionSettings)
//{
// lExceptionSettings.SetBreakWhenThrown(lExceptionsEnabledToSet, lExceptionSetting as ExceptionSetting);
//}
}
}

CMFCToolbar ReplaceButton() causes button to disappear

Using Visual Studio 2010 and working with an MFC SDI Application.
I have a CMFCToolbar object owned by the Main Frame.
When the document in this application is created, the MainFrame calls a function to replace one of the buttons in the CMFCToolbar object with a CMFCToolbarMenuButton. The contents of the menu button are populated with information from the document. The menu creation always works. The call to ReplaceButton always succeeds. But there's a visual symptom of the call that I haven't yet figured out.
Any time ReplaceButton is called, the button disappears. Not only is it not drawn, it's not clickable. It's temporarily gone. I assume this is because there's a dangling reference to the old button, which I have just destroyed with the call to ReplaceButton.
I've tried calling Invalidate(), RecalcLayout() to trigger a re-draw, but neither has worked yet. The only reliable method I have for getting the button to show up is re-sizing the application window manually or by un-docking/re-docking the toolbar. I assume there's some kind of lower-level refresh that occurs in these situations, but I don't know how to trigger it manually.
Is there a way to make sure my button is drawn immediately?
Edit: code sample
Count = m_Doc->...->GetCount();
for (Index = 0; Index < Count; ++Index)
{
Caption.Format(L"%s", m_Doc->...->GetName());
m_pLayerMenu->AppendMenu(MF_ENABLED | MF_STRING, LAYER_DROP_SEED+Index, Caption.GetData());
}
m_wndBrushBar.ReplaceButton(ID_BRUSH_TERRAIN,
CMFCToolBarMenuButton(ID_BRUSH_TERRAIN, *m_pLayerMenu, GetCmdMgr()->GetCmdImage(ID_BRUSH_TERRAIN)));
Update:
Calling m_wndBrushBar.AdjustLayout() seems to stabilize the visual behavior of these CMFCToolbar buttons. So that's a partial solution.
Partial because of the following:
It's hard to tell what the real visual behavior is. It turns out that all visual settings/states are stored in the Registry with these MFC objects, and it can hold onto states of dynamically created objects that really alter the startup behavior of the app.
I've gone in to delete the registry values under
Current User -> "Local App-Wizard Generated Applications" -> [My App Name].
Done this a number of times, just to find out what the real behavior of my app is. Feel like I'm missing some fundamental knowledge with the current version of MFC. Lots of bugs arising from the registry deal.
Is there a way to prevent registry settings for certain objects, or to shut off this behavior altogether? Otherwise, I guess my shutdown process will have to be a LOT more thorough with resetting all the visual elements. Registry values seem to ignore, override, or bypass my startup code. I can code how I want an object to look at startup, but if there are values in the registry, it does no good.
You've discovered a sometimes annoying aspect for the CMFC code. That is, the concept of a Workspace. The Workspace manages the concept of the application state. I, too, have had problems like the one you describe. But, you have the flexibility to manage how those objects are recreated by overriding the LoadState () and SaveState () methods.

Outlook addin has failed to find Office control by ID

I've just built an MS Outlook Add In using Visual Studio and Office 2010. I've installed it ok on 4 machines, but one user is getting the following error -
Error found in Custom UI XML of "...."
...
...
Failed to find Office control by ID
Everyone is running Windows 7 and Outlook 2010 - not sure why this person is having a problem. Can anyone suggest how to diagnose this?
For those having similar issues, you don't have to remove any add-in.
What is happening is: Outlook will try to load all ribbons (found in your ribbon xml) into any window the user goes to. Then it'll complain about not finding ID x or y.
Just make sure your GetCustomUI method in Ribbon.cs does not load the entire ribbon XML at once but rather loads it per fragment.
If you're not sure what IDs you need to target, use a breakpoint in GetCustomUI then start Outlook, surf different views (main, new email, new appointment, calendar...etc) in order to gather the IDs for the views wherein you need to show you add-in.
In my case, I needed Microsoft.Outlook.Explorer, Microsoft.Outlook.Mail.Compose and Microsoft.Outlook.Appointment.
Therefore I changed my GetCustomUI to:
public string GetCustomUI(string ribbonID)
{
switch (ribbonID)
{
case "Microsoft.Outlook.Explorer":
return GetResourceText("MyAddin.RibbonsForOutlookExplorer.xml");
case "Microsoft.Outlook.Mail.Compose":
return GetResourceText("MyAddin.RibbonForOutlookMailCompose.xml");
case "Microsoft.Outlook.Appointment":
return GetResourceText("MyAddin.RibbonForOutlookAppointment.xml");
default:
return null;
}
}
Of course, I had to break down my Ribbon.xml into the three XML files mentioned above. The result: Outlook will ONLY load the fragment needed for a given screen (appointment, new email ...) and will not complain about "not finding an ID on screen X or Y".
Finally, for those who are not sure why some users get that error while others don't: it's because of "Show add-in user interface errors" option (in Options -> Advanced). If that is unchecked then Outlook will ignore the malformed ribbon XML errors. If it checked, users will get related errors about your add-in (if any exists) and also about other add-ins.
If it works for everyone except one user. As #Brijesh Mishra mentioned check if the user has got any other addin and if he is having own quick access tool bar customized.
If he has got any of this then, remove the other addins and try to install or reset the quick access tool bar customization.
For all of you that use a Designer-based VSTO plugin, and not the XML solution.
I searched all the web for this problem, but only found XML-based solutions.
There's nothing for Visual Designer on the web, because in this case you don't have to override the "GetCustomUI" method.
Ribbons designed by using the Visual Designer return a RibbonManager by default.
This RibbonManager object represents all Ribbon (Visual Designer) items in the project and is automatically handled in background through the active window inspector.
So you don't have to write any special code to handle different windows.
To configure it correctly you just have to:
Add one extra Visual Designer Ribbon for every window the user goes to
in the Ribbon Object go under "RibbonType", open the checkbox list an only activate the corresponding window, where the ribbon should appear.
If there is more than one window checked in the list, Outlook trys to insert the ribbon in all the marked windows. Even if the corresponding window is currently not opened. That's the reason, why the error "Failed to find control ID" appears.
the actual fix for me was to separate the ribbon XML files containing the customUI and redirecting to the correct one in the GetCustomUI method (implemented using Office.IRibbonExtensibility)
in example:
public string GetCustomUI(string RibbonID)
{
switch (RibbonID)
{
case "Microsoft.Outlook.Mail.Read":
return GetResourceText("namespace.type1.xml");
case "Microsoft.Outlook.Mail.Compose":
return GetResourceText("namespace.type2.xml");
default:
return null;
}
}

How to attach a debugger dynamically to a specific process

I am building an internal development tool to manage different processes commonly used in our development environment. The tool shows the list of the monitored processes, indicating their running state and allows to start or stop each process.
I'd like to add the functionality of attaching a debugger to a monitored process from my tool instead of going in Debug -> Attach to process in Visual Studio and finding the process.
My goal is to have something like Debugger.Launch() that would show a list of the available Visual Studio. I can't use Debugger.Launch(), because it launches the debugger on the process that makes the call. I would need something like Debugger.Launch(processId).
How do I achieve this functionality?
A solution could be to implement a command in each monitored process to call Debugger.Launch() when the command is received from the monitoring tool, but I would prefer something that does not require to modify the code of the monitored processes.
Side question:
When using Debugger.Launch(), instances of Visual Studio that already have a debugger attached are not listed. Visual Studio is not limited to one attached debugger, you can attach on multiple process when using Debug → Attach to process.
How do I bypass this limitation when using Debugger.Launch() or an alternative?
A coworker ended up with a solution using DTE, and I posted the code on PasteBin.
The methods of interest are AttachVisualStudioToProcess and TryGetVsInstance
Source Code
public static void AttachVisualStudioToProcess(Process visualStudioProcess, Process applicationProcess)
{
_DTE visualStudioInstance;
if (TryGetVsInstance(visualStudioProcess.Id, out visualStudioInstance))
{
//Find the process you want the Visual Studio instance to attach to...
DTEProcess processToAttachTo = visualStudioInstance.Debugger.LocalProcesses.Cast<DTEProcess>().FirstOrDefault(process => process.ProcessID == applicationProcess.Id);
// Attach to the process.
if (processToAttachTo != null)
{
processToAttachTo.Attach();
ShowWindow((int)visualStudioProcess.MainWindowHandle, 3);
SetForegroundWindow(visualStudioProcess.MainWindowHandle);
}
else
{
throw new InvalidOperationException("Visual Studio process cannot find specified application '" + applicationProcess.Id + "'");
}
}
}
private static bool TryGetVsInstance(int processId, out _DTE instance)
{
IntPtr numFetched = IntPtr.Zero;
IRunningObjectTable runningObjectTable;
IEnumMoniker monikerEnumerator;
IMoniker[] monikers = new IMoniker[1];
GetRunningObjectTable(0, out runningObjectTable);
runningObjectTable.EnumRunning(out monikerEnumerator);
monikerEnumerator.Reset();
while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
{
IBindCtx ctx;
CreateBindCtx(0, out ctx);
string runningObjectName;
monikers[0].GetDisplayName(ctx, null, out runningObjectName);
object runningObjectVal;
runningObjectTable.GetObject(monikers[0], out runningObjectVal);
if (runningObjectVal is _DTE && runningObjectName.StartsWith("!VisualStudio"))
{
int currentProcessId = int.Parse(runningObjectName.Split(':')[1]);
if (currentProcessId == processId)
{
instance = (_DTE)runningObjectVal;
return true;
}
}
}
instance = null;
return false;
}
WinDbg does the chain debugging for native code by default. If you want to launch another instance of Visual Studio, check Launch the Debugger Automatically on MSDN:
To automate the existing debugger, use Marshal.GetActiveObject to get the current EnvDTE.Debugger then let it attach to the process you just created.
Sometimes, you may need to debug the startup code for an application that is launched by another process. Examples include services and custom setup actions. In these scenarios, you can have the debugger launch and automatically attach when your application starts.
To setup an application to launch the debugger automatically
Start the Registry Editor (regedit).
In the Registry Editor, open the HKEY_LOCAL_MACHINE folder.
Navigate to HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\currentversion\image file execution options.
In the Image File Execution Options folder, locate the name of the application you want to debug, such as myapp.exe. If you cannot find the application you want to debug:
a. Right-click the Image File Execution Options folder, and on the shortcut menu, click New Key.
b. Right-click the new key, and on the shortcut menu, click Rename.
c. Edit the key name to the name of your application; myapp.exe, in this example.
Right-click the myapp.exe folder, and on the shortcut menu, click New String Value.
Right-click the new string value, and on the shortcut menu, click Rename.
Change the name to debugger.
Right-click the new string value, and on the shortcut menu, click Modify.
The Edit String dialog box appears.
In the Value data box, type vsjitdebugger.exe.
Click OK.
From the Registry menu, click Exit.
The directory containing vsjitdebugger.exe must be in your system path. To add it to the system path, follow these steps:
a. Open the Control Panel in Classic view, and double-click System.
b. Click Advanced System Settings.
c. In System Properties, click the Advanced tab.
d. On the Advanced tab, click Environment Variables.
e. In the Environment Variables dialog box, under System variables, select Path, then click the Edit button.
f. In the Edit System Variable dialog box, add the directory to the Variable value box. Use a semicolon to separate it from other entries in the list.
g. Click OK to close the Edit System Variable dialog box.
h. Click OK to close the Environment Variables dialog box.
i. Click OK to close the System Properties dialog box.
Now, use any method to start your application. Visual Studio will start and load the application.
Here is some information about how you can programmatically attach the debugger to multiple processes:
Attach to locally running processes
Attach to remotely running processes

Debugging in Dynamics AX

I'm facing some troubles still while learning, so I guess it tends to get worse once I play with the big kids: warnings in dynamics aren't as precise and informative as VS's, there are no mouse-over tips, and exceptions to show me exactly where I've got it wrong.
I'm just too used to Visual Studio, it's intellisense and all the tools (dynamics is quite new when compared to Visual Studio)
More than solving simple code issues, i'd like to learn how to solve upcomming ones i might have in code not written by me or anything else i'd solve in 3 minutes in Visual Studio, as well as tips on how to survive in dynamics ax without all the Visual Studio tools.
The code editor in Dynamics AX has some intellisense, typing the name of a table or class variable followed by . or :: will give you a list of fields or methods available for that item. After you type the ( to start a method call, a tooltip pops up with parameters available on that method. When starting a new line, you can right click and List Tables, List Classes, List Types, etc. Most of those commands are also available via Shortcut Keys. Note that the intellisense only works if all the code in the method up to the location of your cursor is syntactically correct.
Make sure you have updated the cross reference in your development environment (Tools/Development tools/Cross-reference/Periodic/Update). With an updated cross reference, you can right click an any table, field, class, method, extended data type, or enum in the AOT and choose Add-Ins/Cross-reference/Used by to see where that item is used in the system.
You can also use Tools/Development tools/Code explorer to view the source to the application with all types, variables, and methods turned into hyperlinks so you can click to go right to the definition of that item.
Another useful tool is Application hierarchy tree, available either under Tools/Development tools, or on the right click Add-Ins menu. This will show you the class hierarchy, so you can easily see, for example, that SalesFormLetter derives from FormLetter, which derives from RunBaseBatch.
In the editor, you can highlight text and right click to Lookup Properties/Methods or Lookup Definition.
If you are trying to track down where in the system a particular infolog message is generated there are two strategies to use:
Set a breakpoint on the first line
of the method Info.add(). Then when
you run the code generating the
message, you will pop into the
debugger as soon as the infolog is
generated. You can then look at the stack
trace in the debugger to see where the code is that
generated the message.
Run Tools/Development
tools/Label/Label editor and search
for the text of the message. Select
the Label ID of the message, then
click Used by to see where that
message is used in the system.
There is also http://www.axassist.com/ which extends intellisense and many other extensions
What these guys said already is very interesting and helpful.
I'd like to add that within AX in real life you are probably working with multiple contexts. e.g. Code running in the client, code running in server, code running in p-code and in IL, COM integrations, Enterprise portal and so on.
My point is, if you want to figure something out through debugging, you must first understand where the code(s) you'd like to debug is running.
Knowing that is important because you might have to allow debugging or give permissions in multiple places.
Examples:
Windows AD debugging users (add yourself)
Allow debugging on client
Allow it on server
Disable IL if you want to use MorphX, otherwise attach the process in VS.
Allow World Wide Web Publishing Service to interact with desktop for EP.
One last thing, you are starting to work with ax right now, perhaps you will need to work with AX7(Dynamics 365 for Operations). This version of the system works only with visual studio. It is still x++, but you have a lot of the things VS provides you.
Take a look on EditorScripts Class,On AX Editor you can use it by right click and choose "Scripts". It is a kind of intellisense that can make by your self, for example: here is my in-line comment whenever I type "mycom" and press "tab"
public void template_flow_mycom(Editor editor)
{
xppSource xppSource = new xppSource(editor.columnNo());
int currentline = editor.currentLineNo();
int currentcol = editor.columnNo();
Source template = "//Partner comment "+date2str(today(),123,2,1,3,1,4, DateFlags::FormatAll )+" at "+time2str(timenow(), 1, 1)+" by MAX - Begin\n";
template+=strRep(" ", currentcol)+ "\n";
template+=strRep(" ", currentcol)+ "//Partner comment "+date2str(today(),123,2,1,3,1,4, DateFlags::FormatAll )+" at "+time2str(timenow(), 1, 1)+" by MAX - End\n";
editor.insertLines(template);
//move cursor to the empty line between the comments
editor.gotoLine(currentline+2);
editor.gotoCol(currentcol+4);
}

Resources