Mouse-state suddenly broke in my project. - c#

This is the most unusual error ever!
I am using XNA(Monogame) and using the following code to get the mouse state:
Mousestate ms = Mouse.GetState();
Then I could check for clicks with the following:
if(ms.RightButton == ButtonState.Pressed)
{
}
Or check for scroll by setting a previous scroll variable and compare it to the current one.
All was working well, until I was working on my system today, and I tested it and all mouse interaction stopped working. But keyboard state did work.
I thought it could be because it was not getting called or was not being checked.
So I placed this is my working update method.
if (ms.LeftButton == ButtonState.Pressed)
{
throw new NullRefrenceException();
}
I tried Left clicking and nothing happened. Made sure it was not something else by removing the if-statement and sure enough it did throw it.
So after being desperate I created a Windows Mono-game Proj and put the same code into the update method.
I left-clicked and the error was thrown sure enough.
I have tried commenting out every line of code which has the word ms/mouseState/Mouse. And only leaving one, but to no avail.
I would create a Minimal, Complete, and Verifiable Example but my project is very large, and I have declared Mouse-state in over 30 classes.
I have tried restarting computer, restarting visual-studio, ending all vs/vs-host processes, using a different mouse and lots of code tweaking.
No errors are thrown, when I try and use break-point near Mouse-state it is not set to null.
If any further information is needed for this question, please say so.

Well. If you initialize Game1.
Game1 g1 = new Game1();
It will break mouseState.
If a class extends : Microsoft.Xna.Framework.Game
And uses its methods. If you initialize it again it will break.
Game1 should not be initialized.

Related

Why would my HitTestResultCallback not be called

I've inherited a program that uses hit testing to handle mouse events against a bunch of drawings on a canvas. Under some circumstances my HitTestResultCallBack stops being called.
Here's where the HitTest is called (this is called from the mousemove event):-
internal void HitTest(System.Windows.Input.MouseEventArgs e)
{
m_visualTrackerHit = m_visualTrackerHit2 = null;
Point location = e.GetPosition(this);
Geometry g = new RectangleGeometry(new Rect(location.X - m_connectDistance, location.Y - m_connectDistance, m_connectDistanceX2, m_connectDistanceX2));
HitTestParameters parameters = new GeometryHitTestParameters(g);
HitTestResultCallback callback = new HitTestResultCallback(this.HitTestCallback);
System.Diagnostics.Debug.Print("About to Hit Test");
VisualTreeHelper.HitTest(this, null, callback, parameters);
}
Here's my call back function:-
private HitTestResultBehavior HitTestCallback(HitTestResult result)
{
System.Diagnostics.Debug.Print("HitTestCallBack");
DrawingVisual visual = result.VisualHit as DrawingVisual;
if (visual != null)
{
VisualTracker visualTracker = visual.GetValue(FrameworkElement.TagProperty) as VisualTracker;
if (visualTracker != null && visualTracker.Type != VisualType.Selection && visualTracker.Type != VisualType.Ignore)
{
if (m_visualTrackerHit == null || visualTracker.Type < m_visualTrackerHit.Type)
{
m_visualTrackerHit = visualTracker;
}
}
}
return HitTestResultBehavior.Continue;
}
This all works fine until I take a particular, apparently unrelated action. (In this case each drawing represents a "component" that will have various properties. Setting a property to an invalid value causes the problem but this is all domain stuff and almost certainly isn't relevant to my question). Once that action is taken the call back method just stops being called. N.b. not just for the drawing the property was changed on either, the call back stops getting called for both the canvas and all the objects on it.
I've traced through the code path from the action and can't see anything obvious in there but it's highly complex and I could well have missed something so I'd like to come at this from the other direction. What are the possible reasons the callback wouldn't be called.
I've checked the following:-
The RectangleGeometry is being defined with correct values so it should indicate a collision with the drawing
Nothing is setting IsHitTestVisible to false anywhere.
Any suggestions?
I wanted to come back on this as I finally found the answer - or part of it at least. The property that was set to an invalid value on the component was causing a divide by zero error in the draw method of that component. That meant that the component was not redrawn but the old drawing of it was left in place, meaning it was not obvious that an error had occurred.
I've tested around this a bit and any unhandled error drawing to the canvas seems to result in the hitTestCallback no longer being called for anything on that canvas. I don't know why that is but it's easy for me to solve at this point as I can just guard against divide by zero exceptions
Debug your program using Snoop:
identify the path of events for a working case
identify the path of events for a non-working case
once you pinpoint the cause, you can come up with a fix for it

How do I take a screenshot when there's an AssertionException? (Xamarin.UITest, C#)

I have built a Xamarin.UITest suite and I'm testing locally on a real Android device. I notice that one or two tests fail, but not necessarily the same tests. Whenever I try to re-run such tests to see why they're failing, they pass! Therefore I need to add functionality to see what's on the screen when a test fails. I don't seem to be able to find a guide specifically for this - just bits and pieces...
I've added EnableLocalScreenshots() to my StartApp() call, but I'm not sure of the next steps. So I have some questions:
Do I need to specify the location of where the screenshots are saved, or is this done automatically?
Do I need to explicitly write code to take a screenshot when there's an AssertionException, or is this what the screenshot functionality does by default?
If I need to write code to take a screenshot when there's an AssertionException, please can you point me to an example of this code so I can add it to my suite?
Thank you
EDIT: Re: Take screenshot on test failure + exceptions
I have tried the following in my Hooks.cs file:
[OneTimeTearDown]
public void OneTimeTearDown()
{
if (TestContext.CurrentContext.Result.Outcome == ResultState.Error || TestContext.CurrentContext.Result.Outcome == ResultState.Failure)
{
App.Screenshot(TestContext.CurrentContext.Test.Name);
}
}
Upon debugging this method, I find that it is never called. Not even if I use TearDown and AfterScenario attributes. So great - that Intellisense likes my code, bad - because it never gets called. It shouldn't be this hard!
I am using Specflow in this suite, could that be anything to do with why I'm getting this issue? This is why I can't implement the solution on the above thread as follows because Specflow manages the NUnit tests...
UITest(() =>
{
// Do your test steps here, including asserts etc.
// Any exceptions will be caught by the base class
// and screenshots will be taken
});
Ok so for me this was the answer.
Added [Binding] attribute above class (dumb error on my part)...
[Binding]
class TestInitialise : BasePage
Added [AfterScenario()] above my screenshot method, and made it a static method...
[AfterScenario()]
public static void TakeScreenshot()
Specified where to save the screenshot...
App.Screenshot(TestContext.CurrentContext.Test.Name).CopyTo(#"C:\Users\me\Desktop\" + TestContext.CurrentContext.Test.Name + ".png");
So I'm guessing App.Screenshot(string title) simply takes a screenshot and holds it in memory, but you actually need to save it somewhere explicitly to get it, rather than assuming it just saves to a default location.
That's that then!

Windows Form Won't Display in Debug Mode

I recently upgraded to VS 2012. I have a set of coded UI tests that I've coded in VS 2010 and I'm trying to spin them up in VS 2012. I have a windows form that I'm displaying at the beginning of the test run by using the AssemblyInitialize attribute. I use this form to allow users to select from sets of values and those values are used to data feed the tests. Here's a copy of my code that displays the form:
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
ProcessUtility.TerminateAll();
if (!File.Exists(Directory.GetCurrentDirectory() + #"\RunInfo.ser"))
{
InitializeForm initForm = new InitializeForm();
initForm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
initForm.ShowDialog();
}
}
So, here's my headache: the form displays just fine in Run mode. However, if I try to spin it up in Debug mode, it never displays. I've stepped through the code. It's loading all of the controls for the form with no errors. I make it to the 'initForm.ShowDialog()' line of code. It runs that line of code but then nothing happens. I don't receive any errors and the status in the lower left of the IDE is 'Ready'. It's almost as if the IDE thinks the form is displayed but it's not. I've double-checked the Task Manager and it's just not there. I've verified the build configuration is set to Debug. I've tried cleaning the solution and re-building. This code continues to work in VS 2010. Please tell me someone out there has ran into a similar problem because I'm out of ideas. I'm new to stackoverflow so let me know if there is anything else I can provide to better explain the issue. Thank you in advance for taking a look at it.
Not sure why this solution works, but I was able to solve this issue in VS2013 by setting the visible property on the form I was trying to display to true and then false before calling ShowDialog.
VB.Net example code
Dim form as Form = new Form
form.Visible = True
form.Visible = False
form.ShowDialog
I was able to get the form to display using the following code instead of ShowDialog. I still have no idea why ShowDialog wasn't working but this does the trick:
InitializeForm initForm = new InitializeForm();
initForm.Visible = true;
initForm.Focus();
Application.Run(initForm);
Most likely a exception is happening during the initialization, Go in to the Debug->Exceptions dropdown menu and be sure the checkbox thrown for Common Language Runtime Exceptions is checked, this will let your code break on the exception that is happening.
If you are still not catching the exception go to Debug->Option and Settings then uncheck the box for Enable Just My Code and check the box for Break when exceptions cross AppDomain or managed/native boundries
This may give you some "read herring" exceptions, as some .NET processes use exceptions for control of flow logic. So just be aware that the first exception you see may not be the cause of your problem.
I was experiencing the same thing while debugging an old code and resolved the situation by adding [STAThread] attribute on top of container method which contains form.ShowDialog();
For example:
[STAThread]
public void MessageBoxShow(string errorMessage)
{
using (frmError errorForm = new frmError(errorMessage))
{
errorForm.ShowDialog();
}
}
This has solved any hanging occured while hitting-continuing debug point.
Platform Windows 7 x64 enterprise edition and VS2008 (both has latest updates as of today).
Hope this helps.
Update 1: Please ignore using statement in example since I am using a custom form which inherits IDisposable in addition to Windows.Form and has custom disposition routines. Sorry if it has created any confusion.

Boolean seemingly changing itself (XNA)

I am currently working on a save system in my XNA game that fires off an event when it's finished saving.
My game has multiple screens which are managed by a screen manager, each screen has its own Update and Draw methods.
In the constructor, my _newSave boolean is flagged as true, this boolean starts off the game save process (which is managed by helper), and once it starts the process, it is flagged to false to prevent constant looping (since i only want to save once per save screen).
When helper is finished saving, it fires off the event, back inside the SaveScreen class, which sets _newSave back to true, and tells the ScreenManager to change screens.
Playing the game everything seems to work correctly, until the second time saving, when this save is attempted the game freezes. It is worth noting that this bool is private and only used in this method the 4 times shown (found usage by visual studio to confirm)
class SaveScreen : LoadingScreen
{
private bool _newSave;
private Player _player;
public SaveScreen(EventHandler screenEvent, ContentManager Content, GraphicsDevice GraphicsDevice, Player player)
: base(screenEvent, Content, GraphicsDevice)
{
screenTexture = Content.Load<Texture2D>("saving");
_newSave = true;
this._player = player;
helper.FinishedSaving = new EventHandler(FinishedSaving);
}
public override void Update(GameTime gameTime)
{
if (_newSave)
{
helper.RequestSave(_player);
_newSave = false;
}
helper.UpdateSaving();
base.Update(gameTime);
}
private void FinishedSaving(object o, EventArgs e)
{
_newSave = true;
screenEvent.Invoke(this, new EventArgs());
}
}
With a breakpoint inside the FinishedSaving event, i confirmed that the bool is changing to true, which is correct, however, a following breakpoint on the next save cycle on the if statement, shows that bool is false.
I am so completely confused by this, as the only _newSave = false statement is inside the if statement that needs to be true to access, the breakpoint inside the event shows that it is true, yet on the first "new" loop of the update code, it is false.
I am really pulling my hair out with this and cannot understand what's happening.
Any help is hugely appreciated, and i'm sorry if it's something silly, i'm a relatively new programmer :)
Thank You! <3
EDIT: Pastebin of entire Helper.cs class: http://pastebin.com/uJ0g6e00
Loading Screen Class: pastebin.com/8W8HxBnq
Screen Class: pastebin.com/qr29gzuq
Are you using multiple threads? If so, I wonder whether it's a race condition.
For example:
Update is called
Let's suppose that _newSave is true
RequestSave is called
Before RequestSave returns, Update is called again, but _newSave is still true...
I figured out the problem, apologies to everyone for wasting their time, and thank you for trying to help, turns out that simply switching the _newSave; = false and helper.RequestSave(_player); statements around fixed the issue, I thought that the problem was isolated into this class alone due it being the only place where the changes happened, in fact the issue was that i invoked the delegate inside the RequestSave method when the player score was not greater than the high score, this caused the code to then return to the if block and since the "_newSave = false;" statement was directly after the method call, it was reverting the statement back to false!
So silly of me but sometimes it's really hard to see the simple problems :P Thank you again!
<3

"The debugger cannot continue running the process."

I've been messing with VS 2010 debugging settings, trying to get stepping into the .NET Framework working. Well, I can't get it to work. I've also tried the Reflector VS plugin and that was working at one point.
Then I randomly started getting this error:
This only happens when I have a breakpoint on a line that calls IEnumerable<T>.ToList(). If I try to step-over or step-into on that line where my breakpoint is set, I get this error dialog and my debugging session ends.
If I move the breakpoint to the line below, the debugger makes it past the ToList() call!
I've tried the following to no avail:
Removing the Reflector plugin.
Undoing my changes in the Tools > Options > Debugging window (unchecked the option to step into the .NET Framework; unchecked the source server option; checked the just my code option).
Unchecked Microsoft Source Server in the Tools > Options > Debugging > Symbols window.
Cleared the symbol cache.
What is going on?
Because this was the first place I came to when I searched for an answer, I'll add what I found out.
In my case, I had the debugger set up in the solution to start multiple projects. For some reason this setting was changed by Visual Studio so that no project was starting. Correcting the setting in the solution immediately solved the problem.
The problem was not difficult to solve, but the error message was more than a bit irritating.
I've just found this answer useful. All I did was change my start-up project to another, and back to normal.
My project probably lost this setting somewhere, and resetting it made it available again.
It was a ToString() override that make the debugger crash ! (After the evaluation the debugger will show you the result with the ToString() method). And if you get an exception in the ToString(), you will never catch an exception because you cannot code them on the debugger behaviour.
I've got this answer from msdn
I suffered from same problem....
I found one solution which heard uncommon....
The debugger cannot continue running the process.Process was terminated
While debugging your code step by step , you will find the line , from where error redirecting.
If you are using " ToString() " anywhere in that file ,please remove that .
Instead of the ,you can use Value / Text .
It works fine.
............
If you were not used ToString() any where in program , then reload project copy by removing completely.
I had the same problem. I traced it down to a class(step-by-step debugging) and finally to a property(commenting all the code, then step-by-step uncommenting).
this property returned a typed dataSet from a table.Dataset
private typedDataSet myDataSet
{
return this.DataSet as typedDataSet;
}
this was in a DataTable partial class.
After I removed this property everything went OK.
I ran into this issue with a code bug from copy/paste. Instead of get/setting the private member variable, I did a get/set on itself. When I referenced the property in other code the debugger terminated (2010):
public bool ProdToDeve
{
get { return ProdToDeve; } // <= missing underbar
set { ProdToDeve = value; }
}
private bool _ProdToDeve = false;
This message will also show up when you're trying to debug a Xamarin solution but you have a class library selected as the startup project instead of your application porject.
It occurred to me when I was doing the following:
throw new Exception(timeout.TotalSeconds + " second(s)");
That's because timeout.TotalSeconds.ToString() which indeed is an override method for an object of type double, was throwing a Parameter not valid exception.
Finally, for safety I ended up doing the following:
throw new Exception(System.Convert.ToString(timeout.TotalSeconds));
Well, typically, this is also the kind of error message you can get in a multi-threads context. In brief, it involves concurrency : make sure that your resource accesses are always secured.
In my case, I got this error message when I forgot to secure resource accesses at some places within my code. To solve this issue, I just had to decorate the critical sections with a lock instruction (on the concerned resource). I hope this will help those who are in this context.

Categories

Resources