First, i'm not too good known to programming (17 and still learning it), so sorry if my code isn't that good ^^
I've seen something about 2D Engine in C#, and that they're actually not that hard to code, so i wanted to give it a shot, but now i've got a problem:
I created a Panel in the Form, and then it's getting painted I "extract" the Graphics Object, and give it to my "Engine"
private void panel1_Paint(object sender, PaintEventArgs e)
{
Console.WriteLine("Draw");
graphics.setG(e.Graphics);
}
The Engine just "saves" the Graphics object
public void setG(Graphics g)
{
this.g = g;
}
Now i've got the usual Game Loop, executing an Update and a Draw method every 1/60 Seconds, part of the draw Method:
for(int i = 0;i < images.Count; i++)
{
var curr = images[i];
g.DrawImage(curr.img, (int)Math.Round(curr.x), (int)Math.Round(curr.y));
}
Where of course img is an Image, x and y are floats, casted to ints, now i get "unhandled exception of type 'System.ArgumentException' occured in System.Drawing.dll" in the Line
g.DrawImage(curr.img, (int)Math.Round(curr.x), (int)Math.Round(curr.y));
Exception Detail (Tried to translate a few words, original log is german):
System.ArgumentException was unhandled
HResult=-2147024809
Message=Invalid Parameter.
Source=System.Drawing
StackTrace:
at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y)
at _2D_Engine.GraphicsEngine.Draw(Graphics g) in C:\Users\Paul\Documents\Visual Studio 2015\Projects\2D Engine\2D Engine\GraphicsEngine.cs:Line 38.
at _2D_Engine.Form1.gameLoop() in C:\Users\Paul\Documents\Visual Studio 2015\Projects\2D Engine\2D Engine\Form1.cs:Line 54.
at _2D_Engine.Form1.gameLoop() in C:\Users\Paul\Documents\Visual Studio 2015\Projects\2D Engine\2D Engine\Form1.cs:Line 58.
at _2D_Engine.Form1.gameLoop() in C:\Users\Paul\Documents\Visual Studio 2015\Projects\2D Engine\2D Engine\Form1.cs:Line 58.
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
This happens whatever i'm trying to draw to the Panel, also when I try to draw a Polygon for example, i get the same Exception. Not sure if I misunderstood anything about how to write the Game Loop, because it doesn't happen when i just call the draw Method from the Paint method, but the Paint Method isn't called everytime I want an object to move, so I can't use only it for the Draw Loop, i'm pretty puzzled right now ^^
Related
I'm encountering a very strange bug which appears only when compiling in Release mode, while in Debug mode the code runs perfectly. Moreover, the bug is encountered only in one machine (a user reported this).
This is the stack trace:
System.IO.FileNotFoundException: Unable to find file 'C:\Users...\FileName.txt'.
File name: 'C:\Users...\FileName.txt'
in System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
in System.IO.FileInfo.get_Length()
in PatcherNET4.FileHandler.LocalFile.get_Size()
in PatcherNET4.FileHandler.CachedFile.IsLocalValid(LocalFile file)
in PatcherNET4.FileHandler.FileManager.<>c__DisplayClassd.b__9(CachedFile file)
in System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source, Func2 predicate)
in PatcherNET4.FileHandler.FileManager.RemoveLocalFiles()
in PatcherNET4.FileHandler.FileManager.DownloadMissingFiles()
in System.Threading.ThreadHelper.ThreadStart_Context(Object state)
in System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
in System.Threading.ThreadHelper.ThreadStart()
And this is the code:
// CachedFile
...
public bool IsLocalValid(LocalFile file)
{
var checkName = file.Name == Name;
var checkSize = file.Size == Size;
var checkLastWrite = file.LastWriteTime == LastWriteTime;
return checkName && checkSize && checkLastWrite;
}
...
//LocalFile
...
public uint Size
{
get
{
_info.Refresh();
return (uint)_info.Length;
}
}
...
How is this possible? I can assure you that there is no difference in the interested pieces of code between the release and debug mode. I don't really know what to do, this is probably the strangest bug I've ever seen.
put FileName.txt in the Unable to find file 'C:\Users...\(here) directory
The first thing I'd try is to verify the file exists at runtime and go from there.
if (!File.Exists(fileName))
{
// do something
}
If the file doesn't exist (I believe you when you say it's missing) then consider the alternatives. Has the file been deleted already? I notice in the stacktrace there's RemoveLocalFiles, so perhaps it's already been run. Maybe a user pressed a button twice? race condition. Separate thread? User is logged in on two machines and has roaming profiles. Or something like that.
Regardless of whether it's a bug or not, it's better to be defensive and include a check to make sure the file exists (or catch the exception if that's your preference).
I'm using WebSync in a .NET application where a client is making calls to connect, subscribe, etc to WebSync. Somewhere along the execution of the code (It's a big app), I get the gray box popup saying the above error message. Because this is a big app, how can I find where in the application this is occurring? The problem is that this application has a lot of threads.
Does this message mean there is a problem in FM.dll (WebSync) or does it mean that I'm missing something in my code that should catch this exception. If the latter, how do I find where in my code this may occur?
Thanks!
Here is the Call Stack to my error. How can I tell if this is an error on my part or if the problem is inside FM.dll (WebSync)?
FM.dll!FM.AsyncException.AsyncThrow.AnonymousMethod__0(object unused) + 0x47 bytes
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x285 bytes
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x9 bytes
mscorlib.dll!System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() + 0x6f bytes
mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() + 0x1ea bytes
[Native to Managed Transition]
[Appdomain Transition]
[Native to Managed Transition]
If you have 'Break on All Exceptions' turned on then once you start the debugger, when the exception is thrown, you'll be able to see and navigate the stack trace. This should give you an idea of the path the code is on leading up to the exception. You can also interrogate the exception to check to see if the InnerException property has been set. From that information you should be able to determine what is causing the issue. If not post more details from the information you gather and you can get more help.
Instruction for setting up Visual Studio to break on all exceptions: http://msdn.microsoft.com/en-us/library/d14azbfh.aspx
In FM libraries, AsyncException.AsyncThrow is used when an exception is thrown in an async callback. Try wrapping your FM callback code in try/catch blocks to catch exceptions, e.g.:
client.Connect(new ConnectArgs
{
OnSuccess = (e) =>
{
try
{
// your code
}
catch (Exception ex)
{
// handle exception
}
}
});
If you don't wrap your callback code in a try/catch block, then the FM library will push the exception to a thread where it will be fail loudly rather than swallow/hide it.
I keep getting this exception which happens every other time. For some reason I do not think its my code as it happens on different pages as well. It also happens on pages where I do not have the DateTime object.
In addition the exception window that comes up is different when there is an application exception which goes to a line of code. When this exception happens this is not the case. At the top it says the code stack only contains external code.
The added or subtracted value results in an un-representable DateTime.
at System.DateTime.op_Addition(DateTime d, TimeSpan t)
at System.Web.HttpContext.MustTimeout(DateTime utcNow)
at System.Web.RequestTimeoutManager.RequestTimeoutEntry.TimeoutIfNeeded(DateTime now)
at System.Web.RequestTimeoutManager.CancelTimedOutRequests(DateTime now)
at System.Web.RequestTimeoutManager.TimerCompletionCallback(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.TimerQueueTimer.CallCallback()
at System.Threading.TimerQueueTimer.Fire()
at System.Threading.TimerQueue.FireNextTimers()
System.Web.HttpContext.MustTimeout seems to be involved in coordinating request timeouts. To this end, I imagine that...
System.DateTime.op_Addition(DateTime d, TimeSpan t)
...is MustTimeout calculating the instant that a request should timeout. It could do this by adding some timeout value to the request's start time.
Check that you don't have any timeouts (in web.config or otherwise) that are artificially high or invalid. For example:
<system.web>
<httpRuntime executionTimeout="999999999999" />
</system.web>
Various timeouts are documented in this Stack Overflow answer.
I got the same when i was trying to expires cookies, but now its worked for me :)
HttpCookie cookie = new HttpCookie("appts");
cookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie);
Max Value 23:59:59.9999999, December 31, 9999,
Min Value 00:00:00.0000000, January 1, 0001.
If your DateTime + TimeSpan< MinValue Or DateTime + TimeSpan>MaxValue
You will get the exception, make sure you remain in bounds.
I have a thread named fetchImage that runs startFetch() method, which is
for (int i = 0; !stopFetching && i < 2000; i++) {
control.fetchImage().Save("Fetch_Image\\fetchedFile" + fileName + ".JPG", System.Drawing.Imaging.ImageFormat.Jpeg);
fileName++;
//Thread.Sleep(800);
Console.WriteLine("Filename :" + fileName);
control is another class that has fetchImage() method:
return (System.Drawing.Bitmap)mainForm.imageTemp.Clone();
mainForm is a form that has Image variable named imageTemp. Now startFetch() runs fine when I have Thread.Sleep(800) but it gives me that error without the sleep. Here is the stack trace of the error
System.InvalidOperationException was unhandled
Message=Object is currently in use elsewhere.
Source=System.Drawing
StackTrace:
at System.Drawing.Image.Clone()
at KiPNi.Control.fetchImage() in F:\CMPS285\285-fall10-5\Final working code\WindowsFormsApplication7\Control.cs:line 65
at KiPNi.Form4.startFetch() in F:\CMPS285\285-fall10-5\Final working code\WindowsFormsApplication7\Form4.cs:line 80
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
I do not know much about threads (although I tried after encountering this problem).
How do I get access to the image from the fetchImage thread?
Instead of pulling data from the processing thread, see if it's possible to push data from the UI thread when there's a frame update - that way, you can possibly avoid locking; if you can create a clone of the image data, you avoid sharing the object between threads.
You really only should be invoking methods on UI controls from the main thread anyway (Control.BeginInvoke() exists, but it's better trying to modify your design to avoid it, if possible).
I have a vs2010 c# solution that was working fine yesterday.
When I try and run a debug instance today I keep getting an SEHException was unhandled.
This error is being thrown in the InitializeComponent method of the startup form.
Any Ideas?
Here's the stacktrace:
System.Runtime.InteropServices.SEHException was unhandled
Message=External component has thrown an exception.
Source=System.Drawing
ErrorCode=-2147467259
StackTrace:
at System.Drawing.SafeNativeMethods.Gdip.GdipCreateFontFromLogfontW(HandleRef hdc, Object lf, IntPtr& font)
at System.Drawing.Font.FromLogFont(Object lf, IntPtr hdc)
at System.Drawing.Font.FromHfont(IntPtr hfont)
at System.Drawing.SystemFonts.get_DefaultFont()
at System.Windows.Forms.Control.get_DefaultFont()
at System.Windows.Forms.Control.GetDefaultFontHandleWrapper()
at System.Windows.Forms.Control.get_FontHandle()
at System.Windows.Forms.ContainerControl.GetFontAutoScaleDimensions()
at System.Windows.Forms.ContainerControl.get_CurrentAutoScaleDimensions()
at System.Windows.Forms.ContainerControl.get_AutoScaleFactor()
at System.Windows.Forms.ContainerControl.PerformAutoScale(Boolean includedBounds, Boolean excludedBounds)
at System.Windows.Forms.ContainerControl.PerformNeededAutoScaleOnLayout()
at System.Windows.Forms.Form.OnLayout(LayoutEventArgs levent)
at System.Windows.Forms.Control.PerformLayout(LayoutEventArgs args)
at System.Windows.Forms.Control.System.Windows.Forms.Layout.IArrangedElement.PerformLayout(IArrangedElement affectedElement, String affectedProperty)
at System.Windows.Forms.ContainerControl.LayoutScalingNeeded()
at System.Windows.Forms.ContainerControl.set_AutoScaleMode(AutoScaleMode value)
at FirstWindow.Form1.InitializeComponent() in C:\Users\Ash\Documents\Visual Studio 2010\Projects\FrameworkClientV2 - No Security\FirstWindow\Form1.designer.cs:line 32
at FirstWindow.Form1..ctor() in C:\Users\Ash\Documents\Visual Studio 2010\Projects\FrameworkClientV2 - No Security\FirstWindow\Form1.cs:line 27
at FirstWindow.Program.Main() in C:\Users\Ash\Documents\Visual Studio 2010\Projects\FrameworkClientV2 - No Security\FirstWindow\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
On a random note my gf broke my laptop screen last night so Im running on an external monitor... could this have anything to do with it?
Here's the code and the erroneous line..
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
///////////////////The line below throws the exception
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
///////////////////////////////
this.Text = "Form1";
}
This might be the same as the widely reported issue that started occurring yesterday. See
http://forums.asp.net/t/1704958.aspx/9/10?Re+SEHException+thrown+when+I+run+the+application
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0f78401b-77b2-4052-a26a-e98d2ec0afa9
Try uninstalling "Trusteer Rapport" if you have it on your machine
To be honest, the answer by zeroid did not fix my problem. So for the sake of completeness, I'd like to add that avira also caused such problems
http://forum.avira.com/wbb/index.php?page=Thread&threadID=123791
This problem can occurs when you load unmanaged functions (from DLL) in the main thread.
I fixed this problem by loading these unmanaged functions in a different thread than the main thread, you can for example use a BackgroundWorker.
I stumbled on this because I suddenly experienced the same problem. It's years after the OP and I'm using VS2015. My solution worked fine at work yesterday, with my laptop hooked up to an an external monitor. Today I'm working from home, and there is no extra monitor. I wouldn't have thought it relevant except for OP's comment about switching screen setup.