WPF application sometimes(randomly) selects wrong value while printing - c#

I am not sure as how to put this up. Actually the code is right. 99% of the time, the print-out shows correct values but, now and then it prints some other value. If i again try to print the same page, the correct value is restored.
What can be the reason for this and how can i determine it for this error. Because whenever i try to run the application in VS on my development PC everything seems correct. Can this happen or has happened to someone else not just in WPF but windows or web application.
EDIT
After doing ~50 test entries, i was able to produce the error once and the noticeable thing i discovered following : (rather than writing code i am trying to explain in general)
A = 100
B = 9
C = A+B // but sometime C gets the value of 1000 treating B as 900
Actual code
VatOnAmount = ((decimal)record.Element("Amount") +
(decimal)record.Element("Invoice").Element("CommissionAmount"))

It sounds like you have an issue where you data binding / element values may not be updated at the time the property is called to get the value. You may want to put some trace statements in your code to output values to see. Also - do you get the same issues if you step through via the debugger? Sometimes that changes race condition issues such as this.

Related

Trouble referencing labels with Active Reports

Ok, so to start off, this is my first time working with C#, and the top it off I am attempting to work with it in a report editor for MYOBs AEPM software, which doesn't exactly give me a lot of info or flexibility. What I have been able to work out is that it uses some version of Data Dynamics Active Reports, but not sure which one. I also cannot seem to figure out what naming they have used for much of the report. Anyway, back to the main issue.
I am needing to add some calculations to the report that the visual editor wont allow me to do(it is restricted to Count, Sum, Min, Max, Avg, Var, so not really helpful). Now the calculations are pretty simple(One is a total x .7, and the other being the result of the first x 74 but this value might be changed in the future). Figured the best way would be to just have 2 text boxes with a value in each of them of "0", and then just once the main report is pretty much done run the calculations and replace the values of the two text boxes. So I made the text boxes in the appropriate section and labelled them CalcTotal1 and CalcTotal2.
Now in the editor it allows me to select the object and an event to trigger it, so selected ReportFooter as the object and AfterPrint as the event. I then just put in a line to chance the CalcTotal1 value and tried to generate the report resulting in the following error:
Error Message: Report Script Compile Error on line 8 Error = The name 'CalcTotal1' does not exist in the current context
public void ReportFooter_AfterPrint()
{
CalcTotal1.Text = "Hello";
}
I have tried looking at the documentation for Active Reports but I am not having much luck, so any ideas would be incredibly welcome.
just add "this" word in the code like
this.CalcTotal1.Test = "Hello";
http://helpcentral.componentone.com/nethelp/AR8Help/AR8_HelpOnlineEN/Scripts.html provides some more tips.
The MYOB AE PM feature referred to is called Smart Reports.
I was able to replicate the error and consequently resolved the problem by using the following syntax:
((TextBox)rpt.Sections["Detail"].Controls["TextBox2"]).Text= "$2000.00";
eg:
public void Detail_AfterPrint()
{
((TextBox)rpt.Sections["Detail"].Controls["TextBox2"]).Text= "$2000.00";
}

Why is my encoding showing twice?

byte[] lengthBytes = new byte[4];
serverStream.Read(lengthBytes, 0, 4);
MessageBox.Show("'>>" + System.Text.Encoding.UTF8.GetString(lengthBytes) + "<<'");
MessageBox.Show("Hello");
This is the code I used for debugging. I get 2 messageboxes now. If I used Debug.WriteLine it was also printed twice.
Msgbox 1: '>>/ (Note that this is still 4 characters long, the last 3 bytes are null.
Msgbox 2: '>>{"ac<<'
Msgbox 3: Hello
I'm trying to send 4 bytes with an integer, the length of the message. This is going fine ('/ ' is utf8 for 47). The problem is that the first 4 bytes of the message are also being read ('{"ac'). I totally dont know how this happens, I'm already debugging this for several hours and I just can't get my head around it. One of my friends suggested to make an account on StackOverflow so here I am :p
Thanks for all the help :)
EDIT: The real code for the people who asked
My code http://kutj.es/2ah-j9
You are making traditional programmer mistakes, everybody has to make them once to learn how to avoid it and do it right. This primarily went off the rails by writing debugging code that is buggy and made it lot harder to find your mistake:
Never write debugging code that uses MessageBox.Show(). It is a very, very evil function, it causes re-entrancy. And expensive word that means that it only freezes the user interface, it doesn't freeze your program. It continues to run, one of the things that can go wrong is that the code that you posted is executed again. Re-entered. You'll see two message boxes. And you'll have a completely corrupted program state because your code was never written to assume it could be re-entered. Which is why you complained that 4 bytes of data were swallowed.
The proper tool to use here is the feature that really freezes your program. A debugger breakpoint.
Never assume that binary data can be converted to text. Those 4 bytes you received contain binary zeros. There is no character for it. Worse, it acts as a string terminator to many operating system calls, the kind used by the debugger, Debug.WriteLine() etc. This is why you can't see the "<<"
The proper tool to use here is a debugger watch or tooltip, it lets you look into the array directly. If you absolutely have to generate a diagnostic string then use BitConverter.GetString().
Never assume that a stream's Read() method will always return the number of bytes you asked for. Using the return value in your code is a hard requirement. This is the real bug in your program, the only you are actually trying to fix.
The proper solution is to continue to call Read() until you counted down the number of bytes you expected to receive from the length you read earlier. You'll need a MemoryStream to store the chunks of byte[]s you get.
Perhaps this link regarding Encoding.GetString() will help you out a bit. The part to pay attention to being:
If the data to be converted is available only in sequential blocks
(such as data read from a stream) or if the amount of data is so large
that it needs to be divided into smaller blocks, you should use the
Decoder object returned by the GetDecoder method of a derived class.
The problem was that I started the getMessage void 2 times. This started the while 2 times (in different threads).
Elgonzo helped me finding the problem, he is a great guy :)

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.

Problem with C# multiline textbox memory usage

I am using a multiline text box in C# to just log some trace information. I simply use AppendText("text-goes-here\r\n") as I need to add lines.
I've let this program run for a few days (with a lot of active trace) and I noticed it was using a lot of memory. Long story short, it appears that even with the maxlength value to something very small (256) the content of the text box just keeps expanding.
I thought it worked like a FIFO (throwing away the oldest text that exceeds the maxlength size). It doesn't, it just keeps increasing in size. This is apparently the cause of my memory waste. Anybody know what I'm doing wrong?
Added a few hours after initial question...
Ok, I tried the suggested code below. To quickly test it, I simply added a timer to my app and from that timer tick I now call a method that does essentially the same thing as the code below. The tick rate is high so that I can observe the memory usage of the process and quickly determine if there is a leak. There wasn't. That was good; however, I put this in my application and memory usage did not change (still leaking). That sure seems to imply that I have a leak somwehere else :-( however, if I simply add a return at the top of that method, the usage drops back to stable. Any thoughts on this? The timer-tick-invoked code did not accumulate memory but my real code (same method) does. The difference is that I'm calling the method from a variety of different places in the real code. Can the context of the call affect this somehow? (note, if it isn't already obvious, I'm not a .NET expert by any means)...
TextBox will allow you to append text regardless of MaxLength value - it's only used to control user entry. You can create a method that will be adding new text after verifying that maxlength is not reached, and if it is, just remove x lines from the beginning.
You could use a simple function to append text:
int maxLength = 256;
private void AppendText(string text)
{
textBox1.AppendText(text);
if(textBox1.Text.Length > maxLength)
textBox1.Text = textBox1.Text.Substring(textBox1.Text.Length - maxLength);
}

Categories

Resources