C# - System.OutOfMemoryException in Visual Studio - c#

I have a problem, when I right click my main form in Visual Studio and go to 'View Designer' I get an error. It says: 'Exception of type 'System.OutOfMemoryException' was thrown.'
Stacktrace:
at System.Reflection.AssemblyName.nGetFileInformation(String s)
at System.Reflection.AssemblyName.GetAssemblyName(String assemblyFile)
at Microsoft.VisualStudio.Design.VSTypeResolutionService.AssemblyEntry.get_AssemblyName()
at Microsoft.VisualStudio.Design.VSTypeResolutionService.AssemblyEntry.get_FullName()
at Microsoft.VisualStudio.Design.VSTypeResolutionService.AssemblyEntry.get_AssemblySpec()
at Microsoft.VisualStudio.Design.VSTypeResolutionService.SearchProjectEntries(String fullName, Boolean correctThread)
at Microsoft.VisualStudio.Design.VSTypeResolutionService.System.ComponentModel.Design.IDesignTimeAssemblyLoader.GetTargetAssemblyPath(AssemblyName runtimeOrTargetAssemblyName, String suggestedAssemblyPath, FrameworkName targetFramework)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkUniverse.ResolveAssembly(AssemblyName assemblyName, Assembly runtimeAssembly)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkUniverse.GetTypeFromTargetLocation(Type type, Boolean validateBase)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkUniverse.GetType(Type type)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkUtil.GetCustomAttributes(Type type, Type filter, Boolean inherit, CustomAttributesCache cache)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkType.GetCustomAttributes(Type filter, Boolean inherit)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkAttributeCollection.GetAttributes(Type type, Type filter)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkAttributeCollection.GetAttributes(MemberInfo member, Type filter)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkAttributeCollection.get_Attributes()
at System.ComponentModel.AttributeCollection.get_Count()
at Microsoft.VisualStudio.Design.VSDesignSurface.EnsureExtensions(IComponent component)
at Microsoft.VisualStudio.Design.VSDesignSurface.CreateInstance(Type type)
at System.ComponentModel.Design.DesignerHost.System.ComponentModel.Design.IDesignerHost.CreateComponent(Type componentType, String name)
at System.ComponentModel.Design.Serialization.DesignerSerializationManager.CreateInstance(Type type, ICollection arguments, String name, Boolean addToContainer)
at System.ComponentModel.Design.Serialization.DesignerSerializationManager.System.ComponentModel.Design.Serialization.IDesignerSerializationManager.CreateInstance(Type type, ICollection arguments, String name, Boolean addToContainer)
at System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager manager)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager)
at System.ComponentModel.Design.Serialization.BasicDesignerLoader.BeginLoad(IDesignerLoaderHost host)
Designer:
http://pastebin.com/hdRB5DAj
I got this error this morning, but I still haven't resolved it. If anyone could help me I would really appreciate it!
I'm only using ~55% of all my RAM, so that can't be it.

As Dr Hebie points out, it's doubtful that it's VS itself throwing the OOM exception, but something in your form constructor.
A Technique I've used to great success with this is opening the form code and inserting Throw new Exception("Message describing position") at the start of the constructor. Hopefully, now instead of getting an OOM exception, you'll get the exception you just specified. Now move this exception around until you get the OOM exception. This will show you the line of code that is causing the OOM.
Good luck!

There are multiple things that this can be caused by, and the problem gets worse with older version of Visual Studio (2005 was particularly bad in my experience).
As this is happening when you view the designer of a form, there is a chance that this is due to objects being created in your form's constructor or event handlers. When VS loads your form into the designer it will actually compile and create an instance of the form class. Any objects you create within the form are likely to get created at this time as well. All this happens within Visual Studio's memory allocation so if you are allocating a large amount of memory this can hinder Visual Studio's memory handling.
I would suggest you perform a check on the DesignMode property of the form and only load/create instances of data classes (like Views) when that property is false. You should also be prepared to do this in event handlers throughout the form as these can be fired by the Visual Studio designer.
Alternatively, if you're feeling brave, you can actually debug Visual Studio with itself! Open your project in VS and then open another instance of VS. In the second instance use the Debug -> Attach to Process option and attach to the first VS instance. Now open the designer for your form and see if you can identify where the error occurs. You may have to switch on the 'break on thrown exceptions' settings under Debug -> Exceptions in the second VS instance to ensure your debugging session sees all exceptions.
Good Luck.

Related

Error in accessing Windows Forms Designer Editor - Requires license for the plugin

As above stated, I'm unable editing from the Designer mode a particular form.
Message:
Instances of this error (1)
1. Show Call Stack
at MapInfo.Licensing.MapInfoLicenseProvider.GetLicense(LicenseContext context, Type type, Object instance, Boolean allowExceptions)
at System.ComponentModel.LicenseManager.ValidateInternalRecursive(LicenseContext context, Type type, Object instance, Boolean allowExceptions, License& license, String& licenseKey)
at System.ComponentModel.LicenseManager.Validate(Type type, Object instance)
at MapInfo.Engine.Session.SessionInternal..ctor()
at MapInfo.Engine.Session.Create()
at MapInfo.Engine.Session.GetCurrent(Boolean bCreate)
at MapInfo.Windows.Controls.MapControl.InitMapControl(Map map)
at MapInfo.Windows.Controls.MapControl..ctor(Map map)
at MapInfo.Windows.Controls.MapControl..ctor()
Help with this error
Could not find an associated help topic for this error. Check Windows Forms Design-Time error list
Forum posts about this error
Search the MSDN Forums for posts related to this error
Screenshot:
How would I be able to add that license and where ?
Any useful hints appreciated.

Executable fails with weird exception

I am using ILMerge and Quartz.NET in a C# .NET 4.0 Windows Service application. The app runs fine without using ILMerge, but now that we're nearing shipping release, I wanted to combine all DLLs into a single executable.
Problem is, that ILMerge seems to work fine, but when I run the combined executable, it throws this exception:
Unhandled Exception: Quartz.SchedulerException: ThreadPool type 'Quartz.Simpl.SimpleThreadPool' could not be instantiated. ---> System.InvalidCastException: Unable to cast object of type 'Quartz.Simpl.SimpleThreadPool' to type 'Quartz.Spi.IThreadPool'.
at Quartz.Util.ObjectUtils.InstantiateType[T](Type type) in :line 0
at Quartz.Impl.StdSchedulerFactory.Instantiate() in :line 0
--- End of inner exception stack trace ---
at Quartz.Impl.StdSchedulerFactory.Instantiate() in :line 0
at Quartz.Impl.StdSchedulerFactory.GetScheduler() in :line 0
Does anyone have any idea why this is? I have been wasting over 4 hours already and I can't figure it out. If I don't combine with ILMerge, then everything runs fine (with the Quartz.dll and Common.Logging.dll in the same directory).
I'm sure someone must have tried packaging Quartz.net up like this before, any ideas?
Disclaimer: I don't know Quartz.NET at all, although I spent some time struggling with ILMerge. When I finally understood its limitations... I stopped using it.
ILMerge'd application tends to have problems with everything which contains the word "reflection".
I can guess (I've never used Quartz.NET) that some classes are resolved using reflection and driven by configuration files.
Class is not only identified by its name (with namespace) but also by assembly it is coming from (unfortunatelly it doesn't get displayed in exception message).
So, let's assume you had (before ILMerging) two assemblies A (for you Application) and Q (for Quartz.NET).
Assembly 'A' was referencing assembly 'Q' and was using a class 'Q:QClass' which was implementing 'Q:QIntf'.
After merging, those classes became 'A:QClass' and 'A:QIntf' (they were moved from assembly Q to A) and all the references in code has been replaced to use those (completely) new classes/interfaces, so "A:QClass" is implementing "A:QIntf" now.
But, it did not change any config files/embedded strings which may still reference "Q:QClass".
So when application is reading those not-updated config files it still loads "Q:QClass" (why it CAN find it is a different question, maybe you left assembly 'Q' in current folder or maybe it is in GAC - see 1).
Anyway, "Q:QClass" DOES NOT implement "A:QIntf", it still implements "Q:QIntf" even if they are binary identical - so you can't cast 'Q:QClass' to 'A:QIntf'.
The not-ideal-but-working solution is to "embed" assemblies instead of "merging" them. I wrote a open-source tool which does it (embedding instead of merging) but it is not related to this question. So if you decide to embed just ask me.
You can test it by removing (hiding, whatever works for you) every single instance of Q.dll on your PC. If I'm right, the exception should say now 'FileNotFound'.
You could try creating your own ISchedulerFactory and avoid using reflection to load all of your types.
The StdSchedulerFactory uses this code to creat a threadpool. It's where your error is happening and would be the place to start looking at making changes:
Type tpType = loadHelper.LoadType(cfg.GetStringProperty(PropertyThreadPoolType)) ?? typeof(SimpleThreadPool);
try
{
tp = ObjectUtils.InstantiateType<IThreadPool>(tpType);
}
catch (Exception e)
{
initException = new SchedulerException("ThreadPool type '{0}' could not be instantiated.".FormatInvariant(tpType), e);
throw initException;
}
The ObjectUtils.InstantiateType method that is called is this one, and the last line is the one throwing your exception:
public static T InstantiateType<T>(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type", "Cannot instantiate null");
}
ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes);
if (ci == null)
{
throw new ArgumentException("Cannot instantiate type which has no empty constructor", type.Name);
}
return (T) ci.Invoke(new object[0]);
}
Right after this section in the factory, datasources are loaded using the same pattern and then the jobs themselves are also loaded dynamically which means you'd also have to write your own JobFactory. Since Quartz.Net loads a bunch of bits and pieces dynamically at runtime going down this road means you might end up rewriting a fair amount of things.

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

CRM 4.0 Unhandled exception upon trying to export labels for translation

I'm having a strange issue with our Dynamics CRM 4.0 (we use it to develop customizations).
When trying to export labels (Settings -> Customization -> Export Labels for Translation) the system shows this error (Tracing + DevErrors are enabled, all show the same, aswell as the Event Viewer on the server itself):
Error Description:
An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Error Details:
Exception of type 'System.Web.HttpUnhandledException' was thrown.
Full Stack:
[ArgumentException: An item with the same key has already been added.]
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
at Microsoft.Crm.Metadata.LabelCollection.Add(Label label)
at Microsoft.Crm.ObjectModel.OrganizationUIService.GetSectionTabAndFieldLabels(IBusinessEntity entity, ILabelLoader labelLoader, ExecutionContext context, Dictionary`2 labels)
at Microsoft.Crm.ObjectModel.OrganizationUIService.RetrieveAllFormLabelsWithAllLanguages(Int32 objectTypeCode, ExecutionContext context)
at Microsoft.Crm.Metadata.OrganizationUIHelper.RetrieveAllFormLabelsWithAllLanguages(Int32 objectTypeCode, ExecutionContext context)
at Microsoft.Crm.Tools.ImportExportPublish.FormXmlHandler.GetLocalizedLabelStringsCollection(Int32 baseLanguageCode, List`1 provisionedLanguages, Dictionary`2 locLabelCollection)
at Microsoft.Crm.Tools.ImportExportPublish.RootTranslationExportHandler.ExportLocalizedLabelStrings(Int32 baseLanguageCode, List`1 provisionedLanguages)
at Microsoft.Crm.Tools.ImportExportPublish.RootTranslationExportHandler.RunExportTranslations(Int32 baseLanguageCode, List`1 provisionedLanguages)
Apparently, no one in the world has ever had this issue (I've been googling around for 2 days)...
What I've tried:
I checked MetadataSchema.LocalizedLabels for any oddity, I tried joining it to Attribute and Entity to check for duped entries (Exception complains about a duplicate key, so ...), almost made LinqPad explode from the massive amount of queries I tried and ditched...
If it's worth anything, the latest Rollup should be on the server.
A single customized label for a "notes" tab in a custom entity main form was causing the issue. I still have no clue about Why it happened (it's been created via the stock form designer) but now my issue is resolved.
If anyone needs to follow my steps, you want to look this set of data:
USE <Organization_DB>
GO
SELECT * FROM Metadataschema.LocalizedLabel WHERE InProduction=1 AND CustomizationLevel=1
GO

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