Conditional Break point at Multiple hitcount Times in Visual Studio - c#

How can I set the breakpoint to be hit on multiple hitcounts.
Like in above figure I want it to be hit at times when the hit count is 234 ,345,567,1234 ,2314 etc.
It doesn't allow me to put a comma as well.

You CAN set "when breakpoint is a multiple of the counter". In your example, this would be "234, 468, 702, ...":
MSDN: Breakpoint Hit Count Dialog Box
Q: Is that sufficient?
Q: If not, is there any specific reason (besides sheer perverseness) you'd need a different hit count each breakpoint?
ONE OTHER ALTERNATIVE:
If you wanted, you can you can keep your own counter, and programatically invoke a break in C# any time you want:
MSDN: System.Diagnostics.Debugger.Break()

Related

How to set a breakpoint in a try statement before the catch is thrown?

Trying to debug a try catch that gets iterated through MANY times before an error pops up in one of the iterations. Is there a way other then setting a breakpoint at the beginning of the try catch and spamming f10? This is problematic for many reasons...
Guess I could do a count and display what iteration its failing on but that seems so extra. Does anything exist that can help me?
P.S. I'm on VS2015 Enter
Is there a way other then setting a breakpoint at the beginning of the
try catch and spamming f10?
Yes there is and that's known as conditional break point. Put a break point and then hold your mouse on the break point. Click on the settings icon and select the condition checkbox and provide your condition (say, when iteration becomes 10). It will break only when condition meets or condition become true
If you know something about the state that triggers the exception you can use a conditional breakpoint.
https://blogs.msdn.microsoft.com/visualstudioalm/2014/10/06/new-breakpoint-configuration-experience-in-visual-studio-2015/

Declaring variables slow down program

I have a program which uses a RichTextBox (which is part of Tab Control) and in the TextChanged event I these variable declarations:
RichTextBox programTextBox = (RichTextBox)tabControl.TabPages[tabControl.SelectedIndex].Controls[0];
int selectStart = programTextBox.SelectionStart;
int programCurrentLine = programTextBox.GetLineFromCharIndex(programTextBox.SelectionStart);
int programCurrentLineIndex = programTextBox.GetFirstCharIndexFromLine(programCurrentLine);
int programCurrentLineLength = programTextBox.Lines[programCurrentLine].Length;
string programCurrentLineText = programTextBox.Lines[programCurrentLine].ToString();
All of them are important in that particular event and I use them multiple times for multiple purposes. However, recalculating every single time slows down my program.
For example, I've noticed that if I open a somewhat large file (with my RichTextBox) and then start pressing e.g. the 'a' button, there is some noticable lag. Deleting every single piece of code except the declaration of these variables does not help at all with the lag, but also deleting the code above, completely solves the problem.
I have two questions: 1) Why do these declarations slow down that much the TextChanged event and 2) What can I do? (Is there a faster way to calculate these variables?)
It's not the variable declarations - it's the code you're using to initialize them. I wouldn't be at all surprised to find that GetLineFromCharIndex and GetFirstCharIndexFromLine were expensive - and currently you're calling the Lines property twice.
You could probably improve matters at least slightly just by removing one of those Lines calls, simply by fetching the line first and then looking at its length:
// No need to call ToString() - Lines is a string[]
string programCurrentLineText = programTextBox.Lines[programCurrentLine];
int programCurrentLineLength = programCurrentLineText.Length;
It's a shame there isn't some way of saying "Get all the information about the position of the given index: its line, first char index from line, and the line itself" in one call :(
If it is not important to recalculate on every key press you might be better off implementing a boolean variable which is set on keypress then has a timer to reset it. For example adding a 1.2 second delay on the event. I am not sure the needs of your app so that time might be a bit much.

What are tracepoints used for?

They can only be placed on method names. How are they used and what are they for?
The Debugger team has a good blog post on this subject with examples as well: http://blogs.msdn.com/b/visualstudioalm/archive/2013/10/10/tracepoints.aspx
https://web.archive.org/web/20190109221722/https://blogs.msdn.microsoft.com/devops/2013/10/10/tracepoints/
Tracepoints are not a new feature at all (they been in Visual Studio since VS 2005). And they aren't breakpoints per se, as they don't cause the program execution to break. That can be useful when you need to inspect something, but not stop the program as that causes the behavior of a bug not to repro, etc.
Tracepoints are an attempt to overcome the case when you can't stop the program to inspect something as that will cause some behavior not to repro, by allowing a breakpoint to log information to the debug output window and continue, without pausing at the UI. You can also do this with macros, but it can be more time consuming.
To set a tracepoint, first set a breakpoint in code. Then use the context menu on the breakpoint and select the “When Hit...” menu item. You can now add log statements for the breakpoint and switch off the default Stop action, so that you log and go. There is a host of other info you can add to the log string, including static information about the location of the bp, such as file, line, function and address. You can also add dynamic information such as expressions, the calling function or callstack. Things like adding thread info and process info, can help you track down timing bugs when dealing with multiple threads and/or processes.
Use case where it can prove really helpful in debugging:
There could a case when you want to debug a function which gets called numerous number of times (say in hundreds), and you may just want to see the trend in which a local variable is changing. Doing this is possible by putting breakpoint, but think about stopping(while debugging) at that function hundreds of times and taking the pain of noting down the values in notepad. Doing this is so easy by using tracepoint, it directly puts the logs in "Output" window, which can be easily analysed or even cleared. Saving hours of manual effort and patience.
Example log at Output window(can run to hundreds of lines):
keyframeNo = 2, time = 1100
keyframeNo = 1, time = 0
keyframeNo = 1, time = 1
keyframeNo = 1, time = 1
keyframeNo = 1, curTime =22
curTime=1132835, keyframeno=15
keyframeNo = 2, time = 1
keyframeNo = 2, time = 1
How to use it:
right-click mouse at code > BreakPoint > Insert TracePoint
Advantage of using TracePoint:
There is no need to add code for generating logs. So, no tension to build the code, also no overhead of cleaning the code.
It doesn't obstruct the flow of code under execution, unlike breakpoints.
It can print value of local variables as well. Enter {local_variable} after clicking "When Hit"
You can also insert tracepoints in Debugging state, just as you can do for breakpoint.
According to MSDN:
Tracepoints are a new debugger feature in Visual Studio. A tracepoint is a breakpoint with a custom action associated with it. When a tracepoint is hit, the debugger performs the specified tracepoint action instead of, or in addition to, breaking program execution.

How to prevent loops in JavaScript that crash the browser or Apps?

I am creating a live editor in Windows 8.1 App using JavaScript. Almost done with that, but the problem is whenever I run such bad loops or functions then it automatically hangs or exits.
I test it with a loop such as:( It just a example-user may write its loop in its own way..)
for(i=0;i<=50000;i++)
{
for(j=0;j<5000;j++){
$('body').append('hey I am a bug<br>');
}
}
I know that this is a worst condition for any app or browser to handle that kind of loop. So here I want that if user uses such a loop then how I handle it, to produce their output?
Or if its not possible to protect my app for that kind of loop, if it is dangerous to my app so I alert the user that:
Running this snippet may crash the app!
I have an idea to check the code by using regular expressions if code have something like for(i=0;i<=5000;i++) then the above alert will show, how to do a Regex for that?
Also able to include C# as back-end .
Unfortunately, without doing some deep and complex code analysis of the edited code, you'll not be able to fully prevent errant JavaScript that kills your application. You could use, for example, a library that builds an abstract syntax tree from JavaScript and not allow code execution if certain patterns are found. But, the number of patterns that could cause an infinite loop are large, so it would not be simple to find, and it's likely to not be robust enough.
In the for example, you could modify the code to be like this:
for(i=0;!timeout() && i<=50000;i++)
{
for(j=0;!timeout() && j<5000;j++){
$('body').append('hey I am a bug<br>');
}
}
I've "injected" a call to a function you'd write called timeout. In there, it would need to be able to detect whether the loop should be aborted because the script has been running too long.
But, that could have been written with a do-while, so that type of loop would need to be handled.
The example of using jQuery for example in a tight loop, and modifying the DOM means that solutions that trying to isolate the JavaScript into a Web Worker would be complex, as it's not allowed to manipulate the DOM directly. It can only send/receive "string" messages.
If you had used the XAML/C# WebView to host (and build) the JavaScript editor, you could have considered using an event that is raised called WebView.LongRunningScriptDetected. It is raised when a long running script is detected, providing the host the ability to kill the script before the entire application becomes unresponsive and is killed.
Unfortunately, this same event is not available in the x-ms-webview control which is available in a WinJS project.
I've got 2 solutions:
1.
My first solution would be defining a variable
startSeconds=new Date().getSeconds();.
Then, using regex, I'm inserting this piece of code inside the nested loop.
;if(startSecond < new Date().getSeconds())break;
So, what it does is each time the loop runs, it does two things:
Checks if startSecond is less than current seconds new Date().getSeconds();.
For example, startSecond may be 22. new Date().getSeconds() may return 24.Now, the if condition succeeds so it breaks the loop.
Mostly, a non dangerous loop should run for about 2 to 3 seconds
Small loops like for(var i=0;i<30;i++){} will run fully, but big loops will run for 3 to 4 seconds, which is perfectly ok.
My solution uses your own example of 50000*5000, but it doesn't crash!
Live demo:http://jsfiddle.net/nHqUj/4
2.
My second solution would be defining two variables start, max.
Max should be the maximum number of loops that you are willing to run. Example 1000.
Then, using regex, I'm inserting this piece of code inside the nested loop.
;start+=1;if(start>max)break;
So, what it does is each time the loop runs, it does two things:
Increments the value of start by 1.
Checks whether start is greater than the max. If yes, it breaks the loop.
This solution also uses your own example of 50000*5000, but it doesn't crash!
Updated demo:http://jsfiddle.net/nHqUj/3
Regex I'm using:(?:(for|while|do)\s*\([^\{\}]*\))\s*\{([^\{\}]+)\}
One idea, but not sure what is your editor is capable of..
If some how you can understand that this loop may cause problem(like if a loop is more than 200 times then its a issue) and for a loop like that from user if you can change the code to below to provide the output then it will not hang. But frankly not sure if it will work for you.
var j = 0;
var inter = setInterval( function(){
if( j<5000 ){
$('#test').append('hey I am a bug<br>');
++j;
} else {
clearInterval(inter);
}
}, 100 );
Perhaps inject timers around for loops and check time at the first line. Do this for every loop.
Regex: /for\([^{]*\)[\s]*{/
Example:
/for\([^{]*\)[\s]*{/.test("for(var i=0; i<length; i++){");
> true
Now, if you use replace and wrap the for in a grouping you can get the result you want.
var code = "for(var i=0; i<length; i++){",
testRegex = /(?:for\([^{]*\)[\s]*{)/g,
matchReplace = "var timeStarted = new Date().getTime();" +
"$1" +
"if (new Date().getTime() - timeStarted > maxPossibleTime) {" +
"return; // do something here" +
"}";
code.replace(textRegex, matchReplace);
You cannot find what user is trying to do with a simple regex. Lets say, the user writes his code like...
for(i=0;i<=5;i++)
{
for(j=0;j<=5;j++){
if(j>=3){
i = i * 5000;
j = j * 5000;
}
$('body').append('hey I am a bug<br>');
}
}
Then with a simple regex you cannot avoid this. Because the value of i is increased after a time period. So the best way to solve the problem is to have a benchmark. Say, your app hangs after continuos processing of 3 minutes(Assume, until your app hits 3 minutes of processing time, its running fine). Then, whatever the code the user tries to run, you just start a timer before the process and if the process takes more than 2.5 minutes, then you just kill that process in your app and raise a popup to the user saying 'Running this snippet may crash the app!'... By doing this way you dont even need a regex or to verify users code if it is bad...
Try this... Might help... Cheers!!!
Let's assume you are doing this in the window context and not in a worker. Put a function called rocketChair in every single inner loop. This function is simple. It increments a global counter and checks the value against a global ceiling. When the ceiling is reached rocketChair summarily throws "eject from perilous code". At this time you can also save to a global state variable any state you wish to preserve.
Wrap your entire app in a single try catch block and when rocket chair ejects you can save the day like the hero you are.

Is it possible to configure VS2008 to single step the heading of a for as if it were one step?

When single stepping into a for loop such as:
for (int = 1; i <= 2; i++)
{
Console.WriteLine(i);
}
The debugger goes thru each part of the for "header" individually thus requiring 4 keypresses to step each loop iteration.
Is it possible to instruct the debugger to consider the "for (int i = 1 ... etc" as one step instead of 3 ? thus requiring only two keypresses per loop iteration ?
Thank you for your help.
I do not think this is possibile because the operations performed in the loop header are different instructions.
The easier way is to put a breakpoint at the beginning of your loop and jump there with F5 (start debug).
You can put conditional break points. Like break only when value of i equal to 3.
http://msdn.microsoft.com/en-us/library/7sye83ce.aspx
How about putting a breakpoint on the opening brace? You can then just hit F5 to step into each iteration.

Categories

Resources