I've got a custom plugin which uses a quickfix and the IDocument.InsertText() method. it inserts a comment at the end of the line of code with the highlighter that was selected but this messes up the position of the rest of the highlighters from the one selected to the end. Is there some way to refresh my daemons Execute function which is in charge of placing the highlights?
Any other ideas on ways to get around this?
Thank you,
Yuval
Before fix:
After fix:
This is due to the abstract syntax tree getting out of sync with the text of the document. Normally, you'd modify the source file by manipulating the syntax tree, which in turn updates the text of the document. When modifying the text directly, you need to make sure the syntax tree is notified of the change, so it knows to update.
You can do this by wrapping the update in a transaction:
using(solution.CreateTransactionCookie(DefaultAction.Commit, "Update text"))
{
document.InsertText(...);
}
You get to specify the default action that will happen when the transaction cookie's Dispose method is called - commit or rollback, and you can call methods directly on the transaction cookie, too. The text passed to the cookie is plain text and is only used for diagnostics purposes, so you can see the transaction that is currently active.
UPDATE:
After looking at the code, the issue here is that you can't modify the text of the document while there's a PSI transaction active. The PSI transaction indicates that you're going to modify the abstract syntax tree of the document, so you can't then modify the text of the document as well - you could easily get into a situation with two conflicting changes and no way to reconcile them.
The PSI transaction is being created by the BulbActionBase base class of the context action, before calling the ExecutePsiTransaction method. You can't modify the text directly in this method.
You have a couple of choices here. You could create a comment node using CSharpElementFactory.GetInstance(...).CreateComment(text) and then add it to the PSI tree using the methods in ModificationUtil, or you can leave ExecutePsiTransaction as an empty method (return null) and implement ExecuteAfterPsiTransaction and call Document.InsertText there (this is what the XAML InsertTextQuickFix class does). Because this method is called while in a transaction, but not while in a PSI transaction, it should update the text, and cause the PSI to be put back in sync.
Incidentally, ReSharper throws an exception when trying to modify the document while the PSI transaction is active, with an appropriate message. If you run Visual Studio with the command line devenv.exe /ReSharper.Internal, this exception should be shown as a tooltip like window in the status bar. Even better, if you're building a plugin, you can install a "checked" build, which includes more checks and reports exceptions by default.
Related
I have a bigger (c#) WPF application with n-classes and m-methods. I would like to place in every single method a breakpoint, so everytime i press a button in my application or any method gets called, i would like the application in VS2010 to hit that breakpoint. I want to understand the flow/progress of the application.
And since i have many methods i would rather not place manually in every and each of them a breakpoint.
Is there any command or tool to place everywhere in my VS2010 solution a breakpoint?
edit: maybe something like the following addin: http://weblogs.asp.net/uruit/archive/2011/08/04/visual-studio-2010-addin-setting-a-class-breakpoint.aspx
edit2: there are some answers but none of them seems like the straight forward easy solution. Anything else?
EDIT: tested only with C++
I came across this article that shows how to set a breakpoint at the beginning of every method in a class. I've tested it with VS 2010. The basic process (when using Visual C++) is:
Go to Debug > New Breakpoint > Breakpoint at Function (Ctrl + B).
In the Function field, insert MyClass::*
This will show up as a single breakpoint in the Breakpoints window, but as soon as one of MyClass's methods is hit, you'll see a breakpoint at the beginning of every function in MyClass, and all of these will be "children" of the original breakpoint in the Breakpoints window.
I imagine this works with C# as well.
This answer suggests a macro that will do as you ask, but my personal recommendation would be to use a profiler instead - one that lets you pause and resume profiling on the fly (nearly all of the commercial profilers do), and then hit the "Start Profiling" button just before you do your button click. Viewing the call tree in the profiler is often a very convenient way of gaining insight into what an application is doing, much more than stepping through in the debugger.
UPDATE: This feature exists in a Visual Studio extension that I'm working on called OzCode. With OzCode, when you click on the icon next to the class definition, you'll see the QuickAction:
Here's a quick and dirty way to do it using a simple text replace:
Format your C# file so that all of the indentations are lined up. You can do this in Edit > Advanced > Format Document
Open up text replace with Ctrl+H
Set the "Text to Find" field this "^ {".
Set the "Replace" field to this " {System.Diagnostics.Debugger.Break();"
Click the little "Use Regular Expressions" button in the window
Click "Replace All" or hit Alt+A
If your file has any classes with nested enums, classes, or structs, you'll have some compiler errors. Remove the Debug calls from them until your code compiles. If your nested classes have their own methods, you'll have to run this process again with more tabs in the replace strings.
How this works: This uses the Visual Studio document formatter and assumes that all methods in a file start with two tabs and then a "{". So any line that starts with two tabs and a "{" will get replaced with the same two tabs, the same "{", and a call to the Debugger.
If your file has nested enums etc., you'll get compiler errors because the text replace doesn't discriminate between methods and enums. For example, you'll see this:
enum MyColors
{ System.Diagnostics.Debugger.Break(); //error here
Red,
Green,
Blue,
}
If you want the ability to disable these breakpoints, the best way I can think of is a simple bool. Somewhere in your code, insert this:
#if DEBUG
private static bool _ignoreDebug = false;
#endif
(I put the #if DEBUG in there as a flag that this code is only for debugging. It's not necessary) Then in step #4 above, use this replace string instead:
" {if(!_ignoreDebug){System.Diagnostics.Debugger.Break();}"
Then when you hit a breakpoint and don't want to hit any more, in the watch window type this and hit enter _ignoreDebug = true. To turn it back on you'll need to insert a manual breakpoint somewhere that has access to the _ignoreDebug bool.
To remove all of this from your code, either do another text replace, or just edit undo everything.
I think you create an 'aspect' for it using a tool like: postsharp
Aspect oriented programming allows you to add code to the start or end of every method (through a postprocessing step). So it's trivial to add the line:
System.Diagnostics.Debugger.Break()
to every method (without actually editing all your sourcecode).
More typically it is used to add log statements to the beginning of every method like: "Entering method DrawLine(x=30,y=80,z=12)" and at the end of a method: "Leaving method DrawLine(x,y,z)". Which makes following the flow of your program easy
You can use my Runtime Flow extension to see all methods called after press of a button without setting breakpoints.
You can use System.Diagnostics.Debugger.Break() on entry to your method.
Something like this perhaps with a bool that you set at the scope?
#if DEBUG
if (BreakPointEveryMethod)
System.Diagnostics.Debugger.Break();
#endif
There will be a quick way too add this for sure in notepad++ but I am not sure there is a quick and easy way for you to achieve this through a simple command line.
I'm working with a .XML document in C# to which I'm selecting nodes from, adding nodes to, and deleting nodes many, many times over a span of my code.
All of the XML editing of this document is contained within a class, which other classes call to.
Since the Data Access class has no way of telling if the classes using it are done with editing the document, it has no logic as to if/when to save.
I could save after every modification of the document, but I'm concerned with performance issues.
Alternatively I could just assume/hope that it will be saved by the other classes that use it (I created a one-line public method to save the document, so another class can request a save).
The second option concerns me as I feel like I should have it globally enforced in some manner to avoid it being called upon and modifications not being committed. To this point there will never be a case where a rollback is needed; any change is a change that should be committed.
Does .Net (Or coding design) have a way to balance performance and safety in such a situation?
If you always want to save the changes (just don't know when) then you could add the save command to the class destructor. This way you know the changes will always be saved.
If you need additional help or want an example please leave a comment, otherwise select an answer as correct.
Update: It has been brought to my attention that the class destructor may fire after other objects (like a FileStream) have already been disposed.
I recommended that you test for this condition in your destructor and also that you implement and use the IDisposable interface. You can then subscribe to the either the Application.Exit event or Application.ApplicationExit event and call dispose there.
Be sure to keep the code in the destructor (but make sure you have it in a try block) in case the program crashes or there is some other, unexpected exit.
Basically your question says i all: You need to save, but you don't know when, as the knowledge about the savepoints is otside your class.
My recommendation is to wrap your calls - assuming you have something like public void MyClass.SomeEditing(int foo), create a wrapper like public void MyClass.SomeEditing(int foo, bool ShouldSave) with shouldsave defaultingto true.
This way, a consumer of your class can decide, wether he wants an immediate save or not, chosing false if he knows, an immediately following other edit will cause the save. Existing code, which calls the "old" API is protected by the default of "save imediately"
I'm writing a diagnostic program that outputs a copy of msinfo32.exe by using a "Process" object. Normally I hide these sort of diagnostics by settings the "CreateNoWindow" property to true.
The problem is, whenever I call it using a process.start() method, no matter what I do, the msinfo32.exe window shows up. Normally this doesn't occur with other command line programs like ipconfig. But msinfo seems to show up. Any suggestions?
There is a utility here : http://www.ntwind.com/software/hstart.html
that you can use.
The syntax for the command is like that : hstart /NOCONSOLE "batch_file_1.bat"
and you can assign priorities also.
Hope I helped you!
I want to cascade the SyntaxHighlighting Engine of AvalonEdit. I have 2 HighlightingDefinitions. The first one is the main syntax. The second one is a complex multiline-preprocessor-markup-language. For this reason it is too complicated to embbed the second grammar in the first one. The easier way is to render the first syntax, and change the affected line-parts (based on the second syntax) afterwards.
So I instantiated a new HighlightingColorizer with the second language and added it to the LineTransformers. But the second language colorizes the complete document and not only the lineparts with the preprocessor-directives: the non-preprocessor-code is black.
As I debugged the ColorizeLine-method of the second line transformer, the lines of the non-highlighted code (= no preprocessor code) have not been colorized, as expected. But the color of the lines are black.
So does the HighlightingColorizer reset all previous highlighting of the whole document before it starts to colorize?
Or what else could be the problem? How can I properly cascade 2 HighlightingColorizers?
The problem is that the HighlightingColorizer does not directly store a reference to the DocumentHighlighter, but instead stores it via TextView.Services. This is done to allow attaching the same colorizer to multiple editors, so that each editor gets its own DocumentHighlighter.
When you attach a second colorizer, it overwrites the IHighlighter stored in the service container; and both colorizers end up using the new highlighter.
Also, note that the 'copy to clipboard' logic in HtmlClipboard directly accesses the IHighlighter service, it does not use any colorizers. (copying text to Word preserves the syntax highlighting only, no other transformations like fold markers)
There are essentially two approaches to solve this issue:
Do not store the additional highlighter as a service. You can do this by creating your own copy of the HighlightingColorizer class, and use a field in that class instead of accessing textView.Services. This is an easy change, but additional highlighters will not be used when copying text to the clipboard.
Create an IHighlighter implementation that combines the HighlightedLines from multiple DocumentHighlighters. This is the approach we are using for the C# semantic highlighting in SharpDevelop 5, which works as an additional highlighter that extends the existing .xshd-based C# highlighting. However, this approach is complex (merging HighlightedLines is non-trivial given the ordering and nesting constraints on the sections), and requires an API change to the IHighlighter interface in order to deal with the OnHighlightStateChanged notification (AvalonEdit 4.x uses a derived class nested in HighlightingColorizer to get access to this callback; AvalonEdit 5.0 will use an event).
I have some nice, working edit-undo functionality in my winforms application. It works using a CommandStack class, which is two Stack<IStateCommand>s (one for undo, one for redo). Each command has an Execute and an Undo method, and the CommandStack object itself has an event that is fired when the stacks are changed.
The CommandStack also works out if the LogCommand method is called from its own Undo function, and therefore adding it to the redo stack, rather than the undo stack. This is done by simply adding the current ManagingThreadId to a List<int> object, then removing it after the Undo command is completed (as opposed to using the stack trace, which I believe would be much slower and a bit dirty).
There is a lot of different commands within my application so this formula is sort of set in stone as it'll take me a few days to redo all those IStateCommands implementations.
The only problem with this, currently, some UI events within also call other UI events, both of which log an IStateCommand to the undo history. Is there any way in C# that I can detect if the LogCommand function has already been called from the same UI event (Click, DragDrop, SelectedIndexChanged, TextChanged, etc), then I can combine the commands into one command (using my CommandList class, which also inherits IStateCommand)?
I've thought of saving the current time when the undo event was called, then if the next command is logged less than x milliseconds later, combine them in the history, but this seems a bit sloppy. I've also considered searching the stack trace, but I don't really know what to look for to find the root UI event, nor do I know whether I would tell the different between one button click, then a different click on the same button.
It may also be helpful to know that all of these commands are being called from the UI thread from event handlers (mostly from events from custom user controls). The only part of my application that uses another thread runs after most UI events, after the undo history is logged.
Thanks!
Sort Version
The same method is being called twice from the same UI event (eg, MouseUp, DragDrop). The second time this method is called, how do I check that it has already been called once by the same UI event?
Edit: The solution (sort of)
It's a bit of a dirty one as I don't have the time to completely re-write this system. However I've implemented it in such a way that gives the option not to be so dirty in the future.
The solution is based on one of Erno's comments on his answer (so I will mark his answer as accepted), where he suggests added a parameter. I added another overload to my LogCommand(IStackCommand) method in the CommandStack class, LogCommand(IStackCommand, string). The string is the actionId, which is stored for each command, and if this string is the same as the last, the commands are combined. This gives the option to go through each event and give a unique ID.
However, the dirty part - to get it working before we have to show the client, the actionId defaults to System.Windows.Forms.Cursor.Position.ToString(), ouch!! Since the cursor position is not changed while the UI thread is executing, this combines each command. It actually even combines TextChanged commands (as long as they don't move their mouse!)
It might be an option to add a local stack of called-commands to a command.
When a command executes other commands add the command to the local stack so you can undo the commands on this local stack when the command must be undone or redone.
EDIT
I am not quite sure what you don't understand.
I would simply add a CommandList property to the StateCommand. Everytime the StateCommand invokes/triggers another StateCommand it should add the new StateCommand to the CommandList. So the global CommandList keeps track of the Commands that can be undone from the UI and each StateCommand keeps track of the StateCommands it invoked (so these are not added to the global undo CommandList)
EDIT 2
If you can't or do not want to change to that setup you would have to pass a parameter to the execution of the commands that links them together.
Did you try to inspect the method stack and analyze it method-by-method:
StackTrace st = new StackTrace();
for ( int i=0; i<st.FrameCount; i++ )
{
StackFrame sf = st.GetFrame(i);
MethodBase mb = sf.GetMethod();
// do whatever you want
}
I don't know what you need exactly to achieve, but I implemented something similar, maybe you can get some ideas...
In summary, you can store some information in a ThreadStatic variable. Then, any time you want to log a command, inspect the thread static variable to find out the context in which you are logging the command. If it's empty, you are starting a new command logging sequence. If not, you are inside a sequence.
Maybe you can store the entry event (e.g. Click, DragDrop,...), or the command itself... It depends on your needs.
When the initial event callback is completed, clean the static variable to signal that the sequence has been completed.
I successfully implemented a similar strategy to track commands executed upon an object model. I encapsulated the logic within an IDisposable class that also implemented the reference counting to handle the nested usings. The first using started the sequence, subsequents using statements increased and decreased the reference counting to know when the sequence was completed. The outermost context disposing fired an event containing all the nested commands. In my specific case it has worked perfectly, I don't know if it may fulfill your needs...