A favorable outcome would be preventing this exception, preferably, or at least handling it gracefully.
I am getting an exception thrown within Microsoft code. On top of that, the method throwing the exception is System.Windows.Input.Manipulations.ManipulationSequence.ProcessManipulators, which I can't find in Microsoft Reference Source.
When the exception is thrown, I can see that one line down in the Call Stack window it references Windows.Input.Manipulations.ManipulationProcessor2D.ProcessManipulators, which does exist in Microsoft Reference Source.
But as you can see, it doesn't have a sibling class named ManipulationSequence.
As for the exception itself, it is a System.Argument.OutOfRangeException with a value of Timestamp values must not decrease. Parameter name: timestamp Actual value was 6590630705479.
The fully qualified signature of the method throwing the exception is System.Windows.Input.Manipulations.ManipulationSequence.ProcessManipulators(long timestamp, System.Collections.Generic.IEnumerable<System.Windows.Input.Manipulations.Manipulator2D> manipulators, System.Windows.Input.Manipulations.ManipulationSequence.ISettings settings)
It appears as if one other person in the universe has had this problem, but it could not be reproduced according to the only comment.
I have 6 MediaElement objects on a canvas that are all running videos when being manipulated, so I feel as though it might have something to do with the CPU being taxed and slowing down, possibly making timestamps be sent into the method out of order (though the same problem occurs when using Image rather than MediaElement). The exception happens sporadically, sometimes it will happen after just a few seconds of messing around with the objects, sometimes it can go for a few minutes or more of manipulating the objects.
My code that does the actual manipulation within ManipulationDelta looks like this:
//Get current values to manipulate
TransformGroup group = (TransformGroup)element.RenderTransform.Clone();
TranslateTransform translate = (TranslateTransform)group.Children[0].Clone();
ScaleTransform scale = (ScaleTransform)group.Children[1].Clone();
RotateTransform rotate = (RotateTransform)group.Children[2].Clone();
//...does manipulations on each by changing values...
//Apply transformation changes
group.Children[0] = translate;
group.Children[1] = scale;
group.Children[2] = rotate;
element.RenderTransform = group;
I have a Storyboard in XAML messing with the RotateTransform, so I can't really use MatrixTransform.
I am creating this using WPF with .NET 4.5.1. The error occurs in both Windows 8.1 and Windows 7. Any ideas on how to prevent this exception from occurring?
Some thoughts as I investigate the problem:
I also have ManipulationInertiaStarting in play here as a possible
cause of this error.
I just added e.Handled = true; to the end of ManipulationCompleted, which wasn't there before. I haven't got the error since (though, again, very sporadic, so it is hard to tell when it is fixed).
If a ManipulationDelta method is not yet complete, and it is hit again from user input, could there be some sort of race condition occurring where the first method hit is starved for CPU resources and the second runs through, then when the first method finally completes the timestamp created is in the past?
Per a comment, this isn't likely.
I conferred with a co-worker to gain better understanding. He helped me realize I can't swallow the exception from within my methods that handle manipulation events because the exception is happening before it gets there, in the actual creation of the manipulation data. So the only place I can handle the exception is on App.Main() (the first place in the Call Stack where my code exists), which makes handling it gracefully all the more difficult.
I had this exact problem myself.
After a lot of testing it could be reproduced with slower machines under heavy load.
The Application was for Digital Signage and showed a lot of different items ( Video, Html , Images , etc ) and had also some animations.
I am not sure about it but it seems to be a problem of handling the input events in time.
For myself i could "solve" this issue with outsourcing code from the manipulating to other code asynchronous and also profiling and rewriting code performance-wise.( shortened the path to run inside the event as much as possible and did everything needed to do also later with a Task )
Also i added an Exceptionhandler to my application to "ignore and log" this issue, because it had no other impact.
Feel free to contact me for more info on this.
PS: this is my first answer here, so i hope it is alright the way i wrote it
I had similar problems when developing for WinRT.
It's sometimes possible to use DispatcherUnhandledException event to ignore one particular exception. To do that, add event listener, check if exception is the one you want (because it's generally bad idea to suppress all exception), and then set Handled property.
Related
First of all, here's the C# code (even though the question is language-independent):
public static void PollClick(IWebElement element, int timeout = defaultTimeout, int pollingInterval = defaultPollingInterval)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
while (stopwatch.Elapsed < TimeSpan.FromSeconds(timeout))
{
try
{
element.Click();
break;
}
catch (Exception)
{
System.Threading.Thread.Sleep(pollingInterval);
}
}
}
This one is for clicking an element, but I could easily replace the click command with something else (visibility check, send text, etc). I'm setting up automation for IE, Edge, Firefox, and Chrome. I've come across a few situations where a certain web driver has a bug or the web page misbehaves for a browser (an element remains obscured, a crash with no stack trace, and other strange issues). This method has been used sparingly (once or twice) as I already have made use of the existing waits available for Selenium and have even created wrapper functions around those waits (including one that waits until an exception is no longer being thrown). Is it a bad idea to have this method handy? It did pass code review but I'm just curious as to what else I could do for anomalous situations.
There’s nothing wrong with executing such a strategy. In point of fact, the language bindings themselves do exactly that in the WebDriverWait construct. In C# (and other language bindings too, I believe) there is a generic version that is not specific to waiting on elements called DefaultWait which gives the user more control over things like what exceptions are caught and ignored, what timing interval to use, and so on. The caveat to repeating actions on the page like clicking elements is that there is a chance for the action to happen more than once, which may have unexpected side effects.
Apparently there is no issue at all in implementing a custom polling method as per your code.
But the question is Why?
The Selenium Language Bindings Java, Python, C#, Ruby internally implements the same and provides us the APIs to achieve the same. So adding one more layer to the existing layers will definitely will have an impact on the performance of your Script Execution.
Nevertheless, in general as per this discussion when you creating a new function the usual costs of making the function call are :
Push the variables onto the stack memory.
Push the return address onto the stack memory.
Branch-out to the destination function.
Creating a new stack frame in the destination function.
Now, at the end of the function the undoing of all the above :
Destroy the local objects created.
Pop the return address.
Destroy the pass-by-value parameters.
Reset the stack pointer to where it was before the parameters were pushed to stack memory.
So, creating and calling an extra function stands pretty costly in terms of System Resources. To avoid that we can easily avail the services exposed by the APIs particularly the ExpectedConditions Class as follows :
Presence of elements : An expectation for checking that all elements present on the web page that match the locator.
Visibility of elements : An expectation for checking that all elements present on the web page that match the locator are visible. Visibility means that the elements are not only displayed but also have a height and width that is greater than 0.
Click/Interactibility of element : An expectation for checking an element is visible and enabled such that you can click it.
I am writing an application that will do some processing on the live preview images on windows phone 8. To achieve a good performance, I decided to use to the native interfaces provided with new sdk. Everythings work Ok for initializing the camera in native side, and feeding frames to a Image component in xaml. Now, I will write the code that will run in OnFrameAvailable method.
My problem is getting a processed value from the native component. Just to make things as simple as possible I just set an integer value in OnFrameAvailable and wrote an accessor of this value through a WinRT component to make it accesible in managed side.
I got stuck on what is an elegant way of accessing this value. When I try to access it in a loop in a thread i get the notorious "attempted to read or write protected memory " exception. I know the code does not make very much sense but I tried to minimize to point out the issue.
Here is how I do it:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
nativeCapture = new NativeCapture();
while (nativeCapture.Done == false) ;
viewFinderBrush.SetSource(nativeCapture.NPhotoCaptureDevice);
DrawElementThread = new Thread(drawElementsFunction);
DrawElementThread.Start();
base.OnNavigatedTo(e);
}
void drawElementsFunction()
{
while(true)
{
int a = nativeCapture.DetectedRectangleCoordinates; // Exception occurs here
}
}
Here you'll also notice that I am accsessing another value, Done, but I dont get the exception for it. However, I should note that is just set in the constructor of the native component whereas DetectedRectangleCoordinates is set everytime OnFrameAvailable called which I expect anytime a preview frame from the camera is available.
Therefore, I susptected that there might be some locking mechanism on WinRT components. Each time the OnFrameAvaible method called DetectedRectangleCoordinates becomes unaccessible. However, I could not find a statement about this and couldn't figure out how to debug such a thing.
I would really appreciate if you provide me with some pointers related to this or similar issues? Is it something related to access mechanisms in WinRT components? Or it is a bad threading practice I am doing? If so, how would I synchronize the thread in managed code and native code?
EDIT:
Putting a breakpoint on the line giving the exception and stepping does not cause the exception, and I get the expected value.
EDIT:
I put a breakpoint on the get function on native side. this pointer is pointing to null there. I could not understand why it is because it is being called from the object that is just constructed. ( nativeCapture object).
I have worked quite some time on what may be going wrong, but adding the code to Loaded event handler of the page solved the issue. I am not sure what it is related about, but when the code piece I have given in the question is run in OnNavigatedTo method, nativeCapture component might have self null pointer (this->) on its methods.
I hope this could help people if they have similar problems.
Under certain circumstances, I get an NRE when closing a form using its Close button, which simply calls the native (WinForms) Close() method.
Certain paths through the code do fine, but one particular path causes the Null Reference Exception. Since this is nominally a scenario where something that is null is being referenced, how could this be taking place when the form is simply being closed? I can imagine there being a memory leak, perhaps, but something null being referenced I'm not understanding.
What potential causes in the code might there be?
UPDATE
Answer to Jon Skeet:
I'm unable to debug this in the normal way for reasons boring and laborious to relate (again), but what I can do is this:
catch (Exception ex)
{
MessageBox.Show(ex.Message);
MessageBox.Show(ex.InnerException.ToString());
SSCS.ExceptionHandler(ex, "frmEntry.saveDSD");
}
The last is an internal/custom exception processing method.
All I get from these lines is:
"Null Reference Exception"
Nothing (empty string)
"Exception: NullReferenceException Location: frmEntry.btnSave.click
Note that the last exception shown now implicates btnSave.click as the culprit, whereas it formerly pointed the finger at saveDSD. Curiouser and curiouser. Is this a case of the Hawthorne Effect* in action (well, a modified Hawthorne Effect, in the sense that adding this debugging code might be changing things).
The canonical Hawthorne Effect being more like this sort of scenario: A bunch of cats are playing basketball. Some girls walk up and watch. The cats start showing off and hotdogging, and one breaks his leg. Is it the girls' fault? No. Would it have happened had they not been watching? No.
UPDATE 2
Talk about the Hawthorne Effect: When I copied the two MessageBox.Show() calls to the catch block of frmEntry.btnSave.click, I then got:
"Null Reference Exception"
"Null Reference Exception"
"Exception: NullReferenceException Location: frmEntry.Closing"
IOW, the location of the NRE keeps moving about, like a squirrel on a country road when [h,sh]e meets two cars going opposite directions.
UPDATE 3
And it happened once more: adding those MessageBox.Show()s to the form's Closing event causes the NRE to pop up out of a different hole and declare itself. This inbred code is begetting (or cloning) half-wits by the score, or so it seems.
UPDATE 4
If writing bad code were a crime, the cat who wrote this stuff should be in solitary confinement in a SuperMax.
Here's the latest egregious headscratcher/howler:
int cancelled = ListRecords.cancelled;
if (cancelled == 0)
. . .
The public "cancelled" member of ListRecords (in another class) is only ever assigned values of 0 and 1. Thus, not only does cancelled sound like a bool, it acts like a bool, too. Why was it not declared as a bool?!?!?
The official image of this codebase should be Edvard Munch's "The Scream"
UPDATE 5
Maybe I'm venting, but recent experiences have caused me to come up with a new name for certain types of code, and an illustration for many projects. Code that doesn't go anywhere, but simply takes up space (assignments made, but are then not acted on, or empty methods/handlers called) I now call "Winchester Mystery House code."
And for the typical project (I've been a "captured" employee as well as a contractor on many projects now, having almost 20 years experience in programming), I now liken the situation to a group of people wallowing in quicksand. When they hire new people to "come aboard," they really want them to jump into the quicksand with them. How is this going to help matters? Is it just a case of "misery loves company"? What they should be doing is saying "Throw us a rope!" not "Come on in, the quicksand is fine!"
Many times it's probably just entropy and "job security" at play; if they keep wrestling with the monstrosity they've chosen or created, their hard-won knowledge in how to keep the beast more-or-less at bay will keep them in their semi-comfy job. If they make any radical changes (most teams do need to make some radical improvements, IMO), this may endanger their employment status. Maybe the answer is to employ/contract "transition teams" to move teams/companies from prehistoric dinosaur-clubbing times into the 21st Century, training the "old guard" so that they can preserve their jobs. After all, there aren't enough of these "saviors" to steal the old hands' jobs anyway - train them up, get them up to speed, and move on. All would benefit. But many seemingly prefer to continue wallowing in the mire, or quicksand.
Before anybody hires a programmer, they should give them at the minimum a test wherein passing the test would prove that they are at least familiar with the basic tenets delineated in Steve McConnell's "Code Complete."
Okay, back to battling the quicksand...
UPDATE 6
Or: "Refactoring Spo-dee-o-dee":
A "gotcha" with refactoring is if you change the name of a variable such as this:
ChangeListType chgLst; // ChangeListType is an enum
...to this:
ChangeListType changeListType;
...and if there is a data table with a column named "chgLst", SQL statements can also get changed, which can ruin, if not your day, at least part of it.
Another potential gotcha is when you get, "[var name] is only assigned but its value is never used" hints. You may think you can just cavalierly 86 all of these, but beware that any related code which you may comment out along with assignments to these dead vars is not producing relied-upon side effects. Admittedly, this would be a bad way to code (side effectual methods storing their return vals in vars that are ignored), but ... it happens, especially when the original coder was a propeller-head mad scientist cowboy.
This code is so chock full of anti-patterns that I wouldn't be surprised if Butterick and/or Simplicity put out a contract on this guy.
On second thought, aside from the architecture, design, coding, and formatting of this project, it's not really all that bad...
Mary Shelley's "Frankenstein" was very prescient indeed, but not in the way most people have thought. Rather than a general foreboding about technology run amok, it is much more specific than that: it is a foregleam of most modern software projects, where "pieces parts" from here and there are jammed together willy-nilly with little regard to whether "the hip bone's connected to the thigh bone" (or should be) and whether those parts match up or will reject one another; the left hand doesn't know what the right is doing, and devil take the hindmost! Etc.
That can happen under any of these situations:
object obj is null and your code has obj.ToString()
string item is null and your code has item.Trim()
Settings mySettings is null and your code has mySettings.Path
Less common things would be a thread running that posts information or a serial port that tries to receive data after the SerialDataReceivedEventHandler has been removed.
Look at what your suspect form's code and the parent form's code are doing about the time this suspect form is closed and what other processes might be running on the suspect form.
I have a class 'b' that inherits from class 'a'. In class 'a' there is some code that performs an action if an event is not null. I need that code to fire in class 'b' during specific times in the application. So in 'b' I subscribed to a new Handler(event).
If I leave the autogenerated event 'as is' in class 'b' with the throw new NotImplementedException(); line, the code works/runs as expected. As soon as I remove the thow exception, the application no longer works as expected.
So, what is the throw new NotImplementedException doing besides throwing the exception?
I realize I'm probably trying to solve my coding problem the wrong way at this point, and I am sure I will find a better way to do it (I'm still learning), but my question remains. Why does that line change the outcome of code?
EDIT:
I reallize I wan't very specific with my code. Unfortunately, because of strict policies, I can't be. I have in class 'a' an if statement.
if (someEvent != null)
When the code 'works', the if statement is returning true. When it isn't working as expected, it is returning 'false'. In class 'b', the only time the application 'works' (or the if statement returns true), is when I have the throw new NotImplementedException(); line in class 'b's event method that is autogenerated when I attached the new event.
Think about this: what if you want to add two integers with the following method...
private int Add(int x, int y)
{
}
...and have no code inside to do such (the method doesn't even return an integer). This is what NotImplementedException is used for.
NotImplementedException is simply an exception that is used when the code for what you're trying to do isn't written yet. It's often used in snippets as a placeholder until you fill in the body of whatever has been generated with actual code.
It's good practice to use a NotImplementedException as opposed to an empty block of code, because it will very clearly throw an error alerting you that section of your code isn't complete yet. If it was blank, then the method might run and nothing would happen, and that's a pain to debug sometimes.
It is simply an exception, as for why it means your application "works" is entirely dependent on the code handling any exceptions.
It is not a "special" exception as opposed to a normal exception (other than being derived from Exception like the rest). You tend to see it with code generation as a placeholder for implementing the member it is throwing inside. It is a lot easier to do this than have code generation try to understand the member structure in order to output compiling code.
When you say "no longer works as expected", I am assuming it compiles. If removing this stops the code from compiling then the chances are good you have a compilation error about a return value.
Perhaps the code that triggers the event expects a certain response from handlers, or if there are no handlers or exceptions occur it defaults the response and carries on. In your case, there is a handler and no exception so it expects a better response?
Complete guesswork.
If there is code in a that you need to use in b, consider making the method that houses the code protected and optionally virtual if you need to override the behaviour.
NotImplementedException, I believe, has a little special meaning: "this code is still in development and needs to be changed". Developers put this exception to make some code compileable, but not executable (to avoid data damage).
Information about this exception type can be found in documentation, it explains the meaning very detailed: https://learn.microsoft.com/en-us/dotnet/api/system.notimplementedexception?view=netcore-3.1
Some development tools, like Resharper, for example, generates new members with NotImplementedException inside, thus protecting you from execution the code, which is not ready. Same time they highlight this exceptions same way as "//todo:" comment
For other situations, for example, when you don't need to implement an interface or virtual member, or may be, you don't implement some paths in switch/case, if/else etc statements, you probably will use NotSupportedException, OutOfRangeException, ArgumentNullException, InvalidOperationException etc.
At the end, consider this situation to understand the purpose of NotImplementedException:
We are writing banking application, and, at the moment, implementing money transferring feature, we have:
public void Transfer(sourceAccount, destAccount, decimal sum)
{
sourceAccount.Credit(sum);
destAccount.Debit(sum);
}
Here we are calling two methods which do not exist yet. We are generating both with default NotImplementedException, and going to first one (Credit) to implement it. Lets say, implementation took some time, we have written test for it, and even have done several manual tests. We completely forgot about second method "Debit" and deploying our application to beta, or even to production. Testers or users start using our application and soon they are coming to money transfer functionality. They are trying to call Transfer, which shows them a general message "We are so sorry, we got some errors", same time we, as a developer team, receive notification about NotImplementedException happened with the stack trace pointing us to the method "Debit". Now we are implementing it, and releasing new version, which can do money transfers.
Now imagine, what would happen, if there was not an exception there: users would spend lot of money trying to do that transfers, trying several times, each time throwing money in to a hole.
Depending on the purposes of the application it can be bigger or smaller problem: may be button on your calculator does not work, or may be that was scientific calculator and we just missed some important math while calculating vaccine code against some aggressive virus.
The NotImplementedException is a way of declaring that a particular method of an interface or base class is simply not implemented in your type. This is the exception form of the E_NOTIMPL error code.
In general an implementation shouldn't be throwing a NotImplementedException unless it's a specifically supported scenario for that particular interface. In the vast majority of scenarios this is not the case and types should fully implement interfaces.
In terms of what it's doing though. It's simply throwing an exception. It's hard to say why the program keeps function in the face of the exception and breaks without it unless you give us a bit more information.
I got this error when trying to update an image.
It was a cross-thread update, but I used .Invoke(), so that shouldn't be the problem, should it.
(Answering my own question, for others, and for future reference)
I think (not yet entirely sure) that this is because InvokeRequired will always return false if the control has not yet been loaded/shown. I have done a workaround which seems to work for the moment, which is to simple reference the handle of the associated control in its creator, like so:
var x = this.Handle;
(See http://ikriv.com:8765/en/prog/info/dotnet/MysteriousHang.html - down? cached version)
(Related question: Boiler plate code replacement - is there anything bad about this code?)
If the handle doesn't yet exist, you can force it by subclassing the control and calling CreateHandle; however, the bigger question is: why are you doing things with a form that hasn't been loaded? Personally I'd only start such an operation after Load.