FileNotFoundException - no file missing - c#

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

Related

Invalid URI with UNC path

I have a path that uses some unc paths in the background such as:
\\crfile2\..some folders..\myFile.lbp
and needs to check if the file exists (won't exist in many cases). I have a simple check that reads the file if it exists. It works fine on almost all cases, but I have one customer that is getting an error:
Unhandled Error: Invalid URI: The format of the URI could not be determined.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at RDES.Common.RDLicenseCommon.LicenseBypassData.<GetBypassData>b__0(String x)
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
This seems like a valid UNC path correct? I'm not sure where the error is here, and even more so I find it confusing that my machine and hundreds of others use the same path string with no issues but this one user is getting this issue. I know it's very limited because for him it's cause a crash on startup and the program is used by enough people that when I post something with a critical issue like that I know it from many people in very short order (not that I ever have posted anything like that...). Anyway any help would be appreciated.
Here is the code line where the exception is being thrown:
string myPath = AllValidPaths.Where(x => VerifyFileExists(new Uri(x),500)).FirstOrDefault();
You can see by the stack that the exception is being thrown by the constructor of the URI inside of the lambda expression.

C# - System.OutOfMemoryException in Visual Studio

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.

CS-Script persistent cache for better performance when loading scripts

Is there a way to persist CS-Script internal assembly cache between subsequent application's runs?
Used component: http://www.csscript.net/
The desired behavior is:
when I compile an assembly form a script string and I close the application, the next time I run the application the compiled assembly with matching script string is found and no recompilation is needed.
This question is follow-up of another question:
Is there a way to call C# script files with better performance results?
Here is my code, but every script string requires recompilation with every restart of parent .NET application.
public interface ICalculateScript
{
Exception Calculate(QSift qsift, QSExamParams exam);
}
...
void Calculate(string script)
{
CSScript.CacheEnabled = true;
//Can following command use built-in cache to load assembly, compiled by this line of code, but by another instance of this app which run in the past and has been meanwhile closed?
Assembly assembly = = CSScript.LoadCode(script, null);
AsmHelper asmHelper = new AsmHelper(assembly);
ICalculateScript calcScript = (ICalculateScript)asmHelper.CreateObject("Script");
calcScript.Calculate(this, exam);
}
Related problem:
The folder of temp scripts created by Cache in CS Script C:\Users\vdohnal\AppData\Local\Temp\CSSCRIPT\Cache\2015108000 has 41 MB and growing with files few months old.
In the output window of WPF App there are first chance exceptions:
A first chance exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll
A first chance exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll
A first chance exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll
A first chance exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll
A first chance exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll
'ESClient.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Users\vdohnal\AppData\Local\Temp\CSSCRIPT\Cache\2015108000\af621e10-d711-40d7-9b77-0a8e7de28831.tmp.compiled'
C:\Users\vdohnal\AppData\Local\Temp\CSSCRIPT\Cache\2015108000
I got an answer fom Oleg Shilo which pointed me in the right direction:
The cache folder indeed grows as new scripts are compiled/loaded. This
is the nature of the caching. It seems that it "grows without control"
though it is not. Once cache is created for a given script file it is
never duplicated and the new cache update is always written over the
existing one.
The problem in your case is that every time you load the file you give
it a unique name thus you are creating a new unique cache. To fix it
you need to start using the same name for the script file every time
you load/execute it.
Alternatively you can completely take over the caching location and
specify what ever cache name you want. It is that second parameter
that you pass null for:
Assembly assembly = CSScript.LoadCode(script, null);
I used following code:
if (assemblyFileName == null)
assembly = CSScript.LoadCode(script, null); //In case there is no name specified - when my custom temp folder cannot be created etc.
else
assembly = CSScript.LoadCode(script, assemblyFileName, false, null); //Specify full path and file name with extension
Thanks to this I have complete control over cached assembly name and location.
If cached assembly with appropriate script already exists, I can simply load it instead of compiling a new one:
Assembly assembly = Assembly.LoadFrom(assemblyFileName);
AsmHelper asmHelper = new AsmHelper(assembly)
The speed of initial loading is better and there is no uncontrollably growing cache.

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.

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