Solving XNA Content Loader InvalidOperationException? - c#

I've found StackOverflow quite a helpful reference in the past, and now that I've come up against an obstacle of my own, thought I'd try posting here.
My issue is that whenever my game attempts to load a SoundEffect file, it crashes with an InvalidOperationException (detail message: an unexpected error has occurred). This game is being written on the XNA 4.0 framework, in C# with Visual Studio 2010 express as my IDE. The sound effects being loaded are all .wav files, and are added into the game's Content project.
I've checked the board and tried the following suggestions:
Confirm content.rootDirectory it set - it is set to "Content"
Confirm content.load<> is accessing the resource via the correct path. Using reflection, I got the current directory for the application, and then used the rootdirectory + the path it was trying to access. The file definitely exists, is accessible, and is in that location.
Ensure ContentManager content is not null - confirmed using debugging, and that would throw a different exception anyway.
Confirm WAV is in 8 or 16 bit PCM. Confirmed.
Possible header corruption? This error occurs on any and all sound effects I attempt to load, so it is not a header issue pertaining to one file.
Oddly enough, this error seems to have come out of nowhere. It was working without problem for the past week, today its freaking out - and I haven't made any changes that would affect the content load process.
Here's the code throwing the error:
public void LoadSoundEffect(ContentManager content, String assetPath)
{
if (content != null && String.IsNullOrEmpty(assetPath) == false)
{
// This next line throws the exception.
SoundEffect effectLoader = content.Load<SoundEffect>(assetPath);
soundLibrary.Add(assetPath, effectLoader);
}
}
Here's the stacktrace:
at Microsoft.Xna.Framework.Helpers.ThrowExceptionFromErrorCode(Int32 error)
at Microsoft.Xna.Framework.Audio.SoundEffect.AllocateFormatAndData(Byte[] format, Byte[] > data, Int32 offset, Int32 count)
at Microsoft.Xna.Framework.Audio.SoundEffect.Create(Byte[] format, Byte[] data, Int32
offset, Int32 count, Int32 loopStart, Int32 loopLength, TimeSpan duration)
at Microsoft.Xna.Framework.Audio.SoundEffect..ctor(Byte[] format, Byte[] data, Int32
loopStart, Int32 loopLength, TimeSpan duration)
at Microsoft.Xna.Framework.Content.SoundEffectReader.Read(ContentReader input,
SoundEffect existingInstance)
at Microsoft.Xna.Framework.Content.ContentReader.InvokeReader[T](ContentTypeReader
reader, Object existingInstance)
at Microsoft.Xna.Framework.Content.ContentReader.ReadObjectInternal[T](Object
existingInstance)
at Microsoft.Xna.Framework.Content.ContentReader.ReadObjectT
at Microsoft.Xna.Framework.Content.ContentReader.ReadAssetT
at Microsoft.Xna.Framework.Content.ContentManager.ReadAsset[T](String assetName,
Action`1 recordDisposableObject)
at Microsoft.Xna.Framework.Content.ContentManager.Load[T](String assetName)
at SerializableDataTypes.AudioManager.LoadSoundEffect(ContentManager content, String
assetPath) in C:\Users\Mike\Documents\Visual Studio 2010\Projects\Res Judicata
Chapter1\SerializableDataTypes\Script Elements\AudioManager.cs:line 78
Thanks in advance for any help you can offer - I'm completely stumped on this, and it's a really frustrating error.

Just for curiosities sake, can you attempt loading your sound effect slightly differently.
SoundEffect effect = content.Load<SoundEffect>(String.Format(#"{0}", soundEffectPath))
I have had issues in the past loading certain content types when not using a string literal.

Related

Attempted to read or write protected memory exception occurs w/o debugging but not w/debugging

Derivatives of this question have surely been asked, however I have yet to find one that matches my case.
I created a library that is wrapping up a third party C++ library and supplying it to some in-house systems. The created library uses C++/CLI to allows users to access it via C#. The library builds and can be launched using our internal continuous integration NuGet server, therefore it's available for use.
There is no problem using this library within some other application/system when running a program with "Start Debugging" (F5), but whenever it's run with "Start Without Debugging" (Ctrl+F5) or via an executable the following exception is raised:
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at TheirLib.func(Int32 , Int32 , Double* , Int32 , Int32* , Int32* , Double* , Int32 , TheirLibError* )
at MyLib.Func(Int32 n, Int32 m, Double[] x, Int32 tdx, Int32[] svar, Int32[] sobs, Double[] corr, Int32 tdc)
at SomeApplication.Program.Main(String[] args) in d:\SomeApplication\SomeApplication\Program.cs:line 67
I read here (https://connect.microsoft.com/VisualStudio/feedback/details/819552/visual-studio-debugger-throws-accessviolationexception) that it could be that one needs .NET 4.5.2, but this didn't change anything. I also thought that there might be some setting in my C++/CLI library that would allow me to circumvent this issue, but I haven't been able to find anything and I feel like I've looked everywhere. I also looked at the C++/CLI code preparing the pin_ptr objects that are used when calling the third party library, but everything looks fine (see below).
void MyLib::Func(int n, int m, array<double>^ x, int tdx, array<int>^ svar, array<int>^ sobs,
array<double>^ corr, int tdc)
{
// Setup input parameters
pin_ptr<double> xPtr = &(x[0]);
pin_ptr<int> svarPtr = &(svar[0]);
pin_ptr<int> sobsPtr = &(sobs[0]);
pin_ptr<double> corrPtr = &(corr[0]);
TheirLibError fail;
// Call their library's function
func(n, m, xPtr, tdx, svarPtr, sobsPtr, corrPtr, tdc, &fail);
}
Again, the library works exactly as expected with "Start Debugging" and passes an exhaustive set of tests, but I just cannot understand why this wouldn't work standalone... I will literally try anything at this point to get it working. Help me SO, you're my only hope...
After contacting the library owner, the issue was that TheirLibError was not being initialized properly, and the pointers contained within this structure were not being handled properly within the library. After properly initializing it, everything worked as expected.
Moral of the story, inquire with the library owner regarding whether or not their library holds onto pointers or any other pointer behavior when approached with an AccessViolationException.

'Expected Global Line.' exception while loading solution using Roslyn

I'm learning Roslyn and trying it out for the first time. I've written a small code snippet to load a solution and get a reference to a workspace.
IWorkspace workspace = Workspace.LoadSolution(solutionPath);
foreach (IProject project in workspace.CurrentSolution.Projects)
{
CommonCompilation objCompilation = project.GetCompilation();
}
return workspace;
But I'm getting an exception in the first line. The exception details are given below.
Message : Expected Global Line.
stack trace : at
Roslyn.Services.Host.SolutionFile.ParseGlobal(TextReader reader)
at Roslyn.Services.Host.SolutionFile.Parse(TextReader reader) at
Roslyn.Services.Host.LoadedWorkspace.LoadSolution(SolutionId
solutionId, String filePath) at
Roslyn.Services.Host.LoadedWorkspace.OpenSolution(String fileName)
at Roslyn.Services.Host.LoadedWorkspace.LoadSolution(String
solutionFileName, String configuration, String platform, Boolean
enableFileTracking) at
Roslyn.Services.Workspace.LoadSolution(String solutionFileName, String
configuration, String platform, Boolean enableFileTracking) at
Ros2.Program.GetWorkspace(String solutionPath) in
c:\users\amnatu\documents\visual studio
2015\Projects\Ros2\Ros2\Program.cs:line 30
I referred to this link which shows the same issue that I faced. However, the solution of removing the space between EndProject and Global isn't really applicable in my case as my solution file doesn't have any space between them.
Am I missing anything here?Any suggestions on how to resolve this issue?
Apologies for the delayed response. The comment by #JoshVarty helped me understand the issue.
I was indeed using the out dated version and had to use the latest Microsoft.CodeAnalysis library. After I made these changes and updated all classes accordingly, everything worked perfectly.
Thanks JoshVarty.!

Error showing Icon in picturebox

I've been using this code to show an icon in a picturebox.
Image FromIcon(Icon ico)
{
try
{
this.toolTip1.SetToolTip(pictureBox1, "The icon of the Executable");
return ico.ToBitmap();
}
catch (Exception e)
{
this.toolTip1.SetToolTip(pictureBox1, "Don't worry, it looks perfectly fine on the executable!");
MessageBox.Show(e.Message + "\r\n" + e.StackTrace);
Clipboard.SetText(e.Message + "\r\n" + e.StackTrace);
// Alternate method
return Bitmap.FromHicon(ico.Handle);
}
}
However it is showing this error.
Requested range extends past the end of the array.
at System.Runtime.InteropServices.Marshal.CopyToNative(Object source, Int32 startIndex, IntPtr destination, Int32 length)
at System.Runtime.InteropServices.Marshal.Copy(Byte[] source, Int32 startIndex, IntPtr destination, Int32 length)
at System.Drawing.Icon.ToBitmap()
Also the icon is shown in a nasty way,
That's the same icon I use for my application. What can go wrong?
That icon is 32 bit as well as the other.
If I use another icon, it works fine and no error pops up.
I know this is an old question but I recently came across the same issue so thought I would post the resolution for anyone else facing the same problem.
For me, the issue was that I was creating the ICO files from PNG image formats but the application that the files were used in targeted a .NET framework that was earlier than 4.6 (i.e. the version in which support was added for PNG frames in .ico files). See note from the Icon.ToBitmap() documentation below:
Beginning with framework version 4.6 support was added for PNG frames in .ico files. Applications that target earlier versions of the framework but are running on the 4.6 bits can opt in into the new behavior by adding the following line to the <runtime> section of the app.config file:<AppContextSwitchOverrides value="Switch.System.Drawing.DontSupportPngFramesInIcons=false" />
So once I added the above line to the app.config file it resolved the issue.

FileNotFoundException - no file missing

When entering a view for the first time, this exception is raised:
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
First of all - why would it just happen the first time I enter that specific view? Even IF the issue was in the constructor (which it could not be), it would be called (and the exception thrown) every time I enter the view.
Second of all - how would I find the source of such an exception? It doesn't break into the debugger, and there are no resource files (like background images, app bar icons) missing.
Lastly - what (except directly referencing files in the code) would throw such an exception?
I would show you the code in question, but the file is a bit too big to post all of it.
UPDATE:
After debugging, I have noticed that the error happens after the constructor and OnNavigatedTo() and before Loaded(). There is a thread being launched in the OnNavigatedTo method, but I have tried to try-catch every single element of that part (and every internal part of it), and no error was found.
UPDATE 2:
After debugging some more, I found the error message:
File or assembly name 'System.Windows.debug.resources, Version=2.0.5.0, Culture=en-US, PublicKeyToken=xxxxxxxxxxxxx', or one of its dependencies, was not found.
Also the stack trace:
at System.ThrowHelper.throwVersion37CompatException(ExceptionType newEType,
String newString, ExceptionType oldEType, String oldString)
at System.Reflection.Assembly.Load(String assemblyString)
at System.Windows.Resx..ctor()
at System.Windows.Resx.GetLoader()
at System.Windows.Resx.GetStringHelper(String name)
at System.Windows.Resx.GetString(String name)
at System.Windows.Controls.Primitives.ToggleButton.ToString()
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj,
IntPtr unmanagedObjArgs, Int32 argsTypeIndex,
Int32 actualArgsTypeIndex, String eventName)
you can set break for the first chance exception visual studio, debug in to see the detail about the FileNotFound exception, which file is missing.
sometime, clr try to find some extension dll, which is normally too magic to us. for example, if you use XmlSerialize in your project, if you don't use sgen.exe to generate the dynamic xml serialize dll for your serializble type, CLR will generate one during runtime, but before this, clr will try to load the assemble, which will cause FileNotFoundException, but catched

InvalidCastException casting object to its own type

I'm currently completely baffled by the problem I'm having. I'm writing a plug-in for another application that provides a public .NET API. I've created a class named Room and I am using a PropertyGrid to allow users to see and edit the properties of the Room instances. A few properties are restricted to a set of standard values. Thus I am using custom TypeDescriptors with GetStandardValues() overrides to get the property grid to show a drop down for those properties.
This was all working just fine. I was getting drop downs, and I could edit values no problem. Yet now for some reason when I select an Room the PropertyGrid shows the properties with the type descriptors as a black box.
If I click on the box it turns white and I get a blinking cursor, yet I can't type anything. If I then select another Room my program crashes with the following exception:
System.InvalidCastException was caught
Message=Unable to cast object of type 'DVAMC.Room' to type 'DVAMC.Room'.
Source=DVAMC
StackTrace:
at DVAMC.BuildingTypeConverter.GetStandardValuesSupported(ITypeDescriptorContext context) in C:\Documents and Settings\eric.anastas\My Documents\_SVN WC\DVAMC Working\BuildingTypeConverter.cs:line 14
at System.Windows.Forms.PropertyGridInternal.GridEntry.get_Flags()
at System.Windows.Forms.PropertyGridInternal.GridEntry.get_NeedsDropDownButton()
at System.Windows.Forms.PropertyGridInternal.PropertyDescriptorGridEntry.get_NeedsDropDownButton()
at System.Windows.Forms.PropertyGridInternal.PropertyGridView.SelectRow(Int32 row)
at System.Windows.Forms.PropertyGridInternal.PropertyGridView.SelectGridEntry(GridEntry gridEntry, Boolean fPageIn)
at System.Windows.Forms.PropertyGridInternal.PropertyGridView.GridPositionData.Restore(PropertyGridView gridView)
at System.Windows.Forms.PropertyGridInternal.PropertyGridView.Refresh(Boolean fullRefresh, Int32 rowStart, Int32 rowEnd)
at System.Windows.Forms.PropertyGridInternal.PropertyGridView.Refresh()
at System.Windows.Forms.PropertyGrid.Refresh(Boolean clearCached)
at System.Windows.Forms.PropertyGrid.set_SelectedObjects(Object[] value)
at System.Windows.Forms.PropertyGrid.set_SelectedObject(Object value)
at DVAMC.RoomDetailsForm.set_RoomDetailsSelectedRoom(Room value) in C:\Documents and Settings\eric.anastas\My Documents\_SVN WC\DVAMC Working\RoomDetailsForm.cs:line 115
at DVAMC.RoomDetailsForm.roomListTreeView_SelectionChanged(Object sender, EventArgs e) in C:\Documents and Settings\eric.anastas\My Documents\_SVN WC\DVAMC Working\RoomDetailsForm.cs:line 159
at BrightIdeasSoftware.ObjectListView.OnSelectionChanged(EventArgs e)
at BrightIdeasSoftware.ObjectListView.HandleApplicationIdle(Object sender, EventArgs e)
at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FDoIdle(Int32 grfidlef)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.RunDialog(Form form)
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
at System.Windows.Forms.Form.ShowDialog()
at DVAMC.RoomDetailsCmd.Execute(ExternalCommandData commandData, String& message, ElementSet elements) in C:\Documents and Settings\eric.anastas\My Documents\_SVN WC\DVAMC Working\RoomDetailsCmd.cs:line 44
InnerException:
The last item in the stack trace points to my BuildingTypeConverter.GetStandardValuesSupported() method which is shown below.
GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context)
{
Room r = (Room)context.Instance; //this is line 14 referenced by the InvalidCastException's stack trace
if (r.IsLinked)
{
return true;
}
else
{
return false;
}
}
Now if I set a breakpoint at line 14 above and try to debug the debugger does not break at the breakpoint. In addition, if I add arbitrary code before the cast the stack trace from the InvalidCastException always seems to reference to first line of GetStandardValues() regardless of what it is. For example I tried the following.
public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context)
{
string s = "hello world"; //FIRST LINE
int i = 0;
Room r = (Room)context.Instance;
.....
I still got the same InvalidCastException. Yet it's stack trace reference the first line above where I initialize string s. In addtion, if I tried to set a breakpoint on this first line it was also not triggered.
Like I said before this was working just fine a day or so ago. I've even tried rolling back to previous revisions in my SVN repository. I've gone as far back as the first revision were I created the custom Type Descriptor class but still run into the problem with the InvalidCastExceptions. Does anyone have any idea what's going on?
If the stack trace always shows the same line even after you have changed the code that would indicate to me that the ProperyGrid is not running the same version of the assembly. This is further confirmed when you say you put a breakpoint but the breakpoint is never hit. If you are running inside of the debugger for Visual Studio I suggest that you look at the output window (Ctrl+W, O), which will list all of the assemblies (with their path) that are loaded in the run. I have seen assembly version confusion particularly when the assembly is in the GAC, where it insist upon loading an older version of the assembly.
It may be that the two types are actually different - for example if one of them is loaded from another version of some assembly than the other type. I'm not quite sure if this could happen in your case, but it could be a problem.
The easiest way to check this is to place breakpoint at the place where the exception is thrown. Then you can look at the two types in watches or immediate window and look at o1.GetType().Assembly. FullName (and similarly for the other object).

Categories