I am still getting System.IO.FileNotFound Exception when I even try to use NRefactory.
I tried many ways to get it working:
- Used NuGet package, which istalled Mono.Cecil automatically
- downloaded NRefactory and Mono.Cecil, and compiled all DLL's from VS2010.
What am I doing wrong?
Here is error dump:
[System.IO.FileNotFoundException]
{"Could not load file or assembly 'ICSharpCode.NRefactory, Version=4.2.0.8783,
Culture=neutral, PublicKeyToken=efe927acf176eea2' or one of its dependencies.
The system cannot find the file specified.":"ICSharpCode.NRefactory,
Version=4.2.0.8783, Culture=neutral, PublicKeyToken=efe927acf176eea2"}
System.IO.FileNotFoundException
EDIT:
This is code which causes problems:
List<CodeElement> methodsInvokedByGivenMethod = GetInvokedMethods(methodName, fileName);
And this is a body of method:
private List<CodeElement> GetInvokedMethods(string methodName, string itemWhereMethodIs)
{
MessageBox.Show("I am here");
try
{
using (var fs = File.OpenRead(itemWhereMethodIs))
{
using (var parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StreamReader(fs)))
{
parser.Parse();
}
}
}
catch (System.IO.FileNotFoundException fnf)
{
// This exception arises in Nrefactory...WTF? 0_0
SetToolStripText("There is exception :(");
return null;
}
}
What is more important, Exception is not being catched by try-catch block within this method, but occurs outside this method -> when it is called, but before any line of code within it.
Related
I have a Framework 4.8 C# app that uses ClearScript to allow JavaScript to be used as an extension language. I am able to write plugins as DLLs and attach them at runtime, viz
JSE.Script.attach = (Func<string, bool>)Attach;
...
private static bool Attach(string dllPath, string name = "")
{
var status = false;
var htc = new HostTypeCollection();
try
{
var assem = Assembly.Load(AssemblyName.GetAssemblyName(dllPath));
htc.AddAssembly(assem);
if (name.Length == 0)
{
name = assem.FullName.Split(',')[0];
}
JSE.AddHostObject(name, htc); //FIXME checkout the hosttypes
Console.Error.WriteLine($"Attached {dllPath} as {name}");
status = true;
}
catch (ReflectionTypeLoadException rtle)
{
foreach (var item in rtle.LoaderExceptions)
{
Console.Error.WriteLine(item.Message);
T.Fail(item.Message);
}
}
catch (FileNotFoundException fnfe)
{
Console.Error.WriteLine(fnfe.Message);
T.Fail(fnfe.Message);
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
T.Fail(e.Message);
}
return status;
}
This permits my scripts to have lines like
attach(".\\Plugin_GoogleAds_Metrics.dll");
H = Plugin_GoogleAds_Metrics.GoogleAds_Metrics.Historical;
H.EnableTrace("GAM");
...
I've made a public repo of the plugin for those interested.
What's not working in this situation is that when I try to execute the plugin's GetAccountInformation method, and execution reaches the GoogleAdsServiceClient googleAdsService = client.GetService(Services.V11.GoogleAdsService); line, an error is thrown complaining about Google.Protobuf, viz
Exception has been thrown by the target of an invocation.
at JScript global code (Script [23] [temp]:5:0) -> acc = H.GetAccountInformation(auths.Item1, 7273576109, true)
at Microsoft.ClearScript.ScriptEngine.ThrowScriptError(IScriptEngineException scriptError)
at Microsoft.ClearScript.Windows.WindowsScriptEngine.ThrowScriptError(Exception exception)
at Microsoft.ClearScript.Windows.WindowsScriptEngine.<>c__DisplayClass57_0`1.<ScriptInvoke>b__0()
at Microsoft.ClearScript.ScriptEngine.ScriptInvokeInternal[T](Func`1 func)
at Microsoft.ClearScript.ScriptEngine.ScriptInvoke[T](Func`1 func)
at Microsoft.ClearScript.Windows.WindowsScriptEngine.ScriptInvoke[T](Func`1 func)
at Microsoft.ClearScript.Windows.WindowsScriptEngine.Execute(UniqueDocumentInfo documentInfo, String code, Boolean evaluate)
at Microsoft.ClearScript.Windows.JScriptEngine.Execute(UniqueDocumentInfo documentInfo, String code, Boolean evaluate)
at Microsoft.ClearScript.ScriptEngine.Evaluate(UniqueDocumentInfo documentInfo, String code, Boolean marshalResult)
at Microsoft.ClearScript.ScriptEngine.Evaluate(DocumentInfo documentInfo, String code)
at Microsoft.ClearScript.ScriptEngine.Evaluate(String documentName, Boolean discard, String code)
at Microsoft.ClearScript.ScriptEngine.Evaluate(String documentName, String code)
at Microsoft.ClearScript.ScriptEngine.Evaluate(String code)
at RulesetRunner.Program.Run(JScriptEngine& jSE, String scriptText, Config cfg, Dictionary`2 settings) in C:\Users\bugma\Source\Repos\Present\BORR\RulesetRunner\RunManagementPartials.cs:line 72
Exception has been thrown by the target of an invocation.
Exception has been thrown by the target of an invocation.
Could not load file or assembly 'Google.Protobuf, Version=3.15.8.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604' or one of its dependencies. The system cannot find the file specified.
So
I am using the latest Google.Ads.GoogleAds library
AutoGenerateBindingRedirects has been set to true in the csproj file
Add-BindingRedirect has been executed in the context of the Plugin's project
The Plugin_GoogleAds_Metrics.dll is in the same folder as the Google.Protobuf.dll
Where to from here?
What fixed this was including Google.Ads.GoogleAds in the calling app. I didn't have to explicitly mention the symbols in the main binary, just have the library in the build. What I expect this did was to include all the relevant DLLs next to the main EXE.
This is definitely not what I wanted. I wanted to be able to hive off all the DLLs into a separate plugin folder and only have them connected when I attached the plugin. Sadly, this does not seem to be achievable at this point. And now I'm wondering about the other plugins I've written that use Google technologies.
I'm having problems with a System.MissingMethodException "Method not found", although immediately before the line causing the exception I look at the currently loaded assemblies using reflection and can see that the method exists.
This is the text from the exception:
System.MissingMethodException
HResult=0x80131513
Message=Methode nicht gefunden: "Void ConstraintSolverExpressions.CSEObjectFactory..ctor(Google.OrTools.ConstraintSolver.Solver, Int32)".
Source=CSP_E04B_8_0_2021-06-24_11_00initial_temp
StackTrace:
at CSP_E04B_8_0.CConstraintSolverExpressions.createCSEIntVars() in c:\Users\hamkchr\AppData\Local\Temp\GoogleORModelBuilder_1117304b-283d-41c2-a432-6bb39575937f\CSP_E04B_8_0_2021-06-24_11_00.cs:line 45155
at CSP_E04B_8_0.CConstraintSolverExpressions..ctor(Solver s_, CSolverIntVars fc_) in c:\Users\hamkchr\AppData\Local\Temp\GoogleORModelBuilder_1117304b-283d-41c2-a432-6bb39575937f\CSP_E04B_8_0_2021-06-24_11_00.cs:line 44708
The code line causing the exception:
cseFactory = new ConstraintSolverExpressions.CSEObjectFactory(solver, logLevel);
To investigate the problem, I made a method to retrieve information about the loaded assemblies
public static string getAssemblyInfo(string name)
{
var sb = new StringBuilder();
Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assem in loadedAssemblies)
{
if (assem.FullName.Contains(name))
{
sb.AppendLine(assem.FullName);
sb.AppendLine(string.Format("Dynamic: {0}", assem.IsDynamic));
if (!assem.IsDynamic) sb.AppendLine(string.Format("Location: {0}", assem.Location));
foreach (TypeInfo typeInfo in assem.DefinedTypes)
{
sb.Append("Type: ");
sb.AppendLine(typeInfo.FullName);
foreach (ConstructorInfo constructorInfo in typeInfo.GetConstructors())
{
sb.Append("Constructor ");
sb.AppendLine(constructorInfo.ToString());
}
}
}
}
return sb.ToString();
}
As a test, I call the method just before the exception occurs and output the information to a log.
There I can see
ConstraintSolverExpressions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
Dynamic: False
Location: C:\Users\hamkchr\AppData\Local\Temp\51dd0c11-cb06-4f45-8baf-8ca462e47b2b\51dd0c11-cb06-4f45-8baf-8ca462e47b2b\assembly\dl3\04dc249d\bbfb2faa_3268d701\ConstraintSolverExpressions.dll
... some types omitted here ...
Type: ConstraintSolverExpressions.CSEObjectFactory
Constructor Void .ctor(Google.OrTools.ConstraintSolver.Solver, Int32)
So I can see that the loaded assembly ConstraintSolverExpressions has a constructor for the type with the exact signature needed, ConstraintSolverExpressions.CSEObjectFactory Constructor Void .ctor(Google.OrTools.ConstraintSolver.Solver, Int32), but the exception is still being thrown.
Does anyone have an idea why the constructor isn't being found and an exception is thrown?
Perhaps relevant here:
The exception is thrown in a method that was dynamically generated using Code DOM, saved as c# source code, compiled to a dll, then explicitly loaded and executed. In the CompilerParameters.ReferencedAssemblies for the compilation, the exact same ConstraintSolverExpressions.dll (same file location) was specified as for the currently loaded assembly.
I recently followed an example for pre-loading several DLLs from the bin folder as described here:
https://stackoverflow.com/a/5599581/1099519
This actually did work as expected, but I am using SonarLint for VisualStudio and in the following line of code is underlinded and marked as a "Code Smell":
Assembly.LoadFile(dll);
Stating the following S3885 (https://rules.sonarsource.com/csharp/RSPEC-3885):
The parameter to Assembly.Load includes the full specification of the
dll to be loaded. Use another method, and you might end up with a dll
other than the one you expected.
This rule raises an issue when Assembly.LoadFrom, Assembly.LoadFile,
or Assembly.LoadWithPartialName is called.
So I gave it a try and changed it into Assembly.Load(dll); as recommended:
private const string BinFolderName = "bin";
public static void LoadAllBinDirectoryAssemblies(string fileMask)
{
string binPath = System.AppDomain.CurrentDomain.BaseDirectory;
if(Directory.Exists(Path.Combine(binPath, BinFolderName)))
{
binPath = Path.Combine(binPath, BinFolderName);
}
foreach (string dll in Directory.GetFiles(binPath, fileMask, SearchOption.AllDirectories))
{
try
{
Assembly.Load(dll); // Before: Assembly.LoadFile
}
catch (FileLoadException ex)
{
// The Assembly has already been loaded.
}
catch (BadImageFormatException)
{
// If a BadImageFormatException exception is thrown, the file is not an assembly.
}
}
}
But using the recommended method an FileLoadException is thrown:
Could not load file or assembly 'C:\SomePath\SomeDll.dll' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
The reason: The string of Assembly.Load is not a file path, it is actually a class name such as "SampleAssembly, Version=1.0.2004.0, Culture=neutral, PublicKeyToken=8744b20f8da049e3".
Is this simply a false-positive from SonarLint or does a "compliant" way exist?
I am trying to use two different windows UWP project in a Windows 10 cordova app. Both projects produce the same error. The code in one of the projects is as follows:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;
namespace DiskSpaceLibrary
{
public sealed class DiskSpace
{
internal static readonly StorageFolder[] APP_FOLDERS = {
ApplicationData.Current.LocalFolder,
ApplicationData.Current.RoamingFolder,
ApplicationData.Current.TemporaryFolder
};
[DataContract]
internal class Result
{
[DataMember]
internal ulong app = 0;
[DataMember]
internal ulong total = 0;
[DataMember]
internal ulong free = 0;
}
// Manually compute total size of the given StorageFolder
private static ulong sizeFolder(StorageFolder folder)
{
ulong folderSize = 0;
try
{
DirectoryInfo dirInfo = new DirectoryInfo(folder.Path);
// Get back a prefilled (with size) list of files contained in given folder
foreach (var fileInfo in dirInfo.EnumerateFiles("*", SearchOption.AllDirectories))
{
folderSize += (ulong)fileInfo.Length;
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
return 0;
}
return folderSize;
}
// Return the system FreeSpace and Capacity properties
private async static Task<IDictionary<string, object>> getExtraProperties()
{
var basicProperties = await Windows.Storage.ApplicationData.Current.LocalFolder.GetBasicPropertiesAsync();
return await basicProperties.RetrievePropertiesAsync(new string[] { "System.FreeSpace", "System.Capacity" });
}
// Class Entry point
public static IAsyncOperation<string> info(string args)
{
// Entry point in WinRT can not return Task<T> - so here is a trick to convert IAsyncOperation (WinRT) into classic C# async
return infoTask().AsAsyncOperation();
}
// The real disk space work is done here within some asynchronous stuff
private async static Task<string> infoTask()
{
Result result = new Result();
// Run folder discovery into another Thread to not block UI Thread
await Task.Run(() => {
foreach (var folder in APP_FOLDERS)
{
result.app += sizeFolder(folder);
}
});
await getExtraProperties().ContinueWith(propertiesTask =>
{
result.free = (ulong)propertiesTask.Result["System.FreeSpace"];
result.total = (ulong)propertiesTask.Result["System.Capacity"];
});
// Return JSON Result
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Result));
MemoryStream outputMs = new MemoryStream();
serializer.WriteObject(outputMs, result);
outputMs.Position = 0;
StreamReader sr = new StreamReader(outputMs);
return sr.ReadToEnd();
}
}
}
This project is from https://github.com/sqli/sqli-cordova-disk-space-plugin
It simply looks for used disk space and reports the used and available space using the System.IO.DirectoryInfo and the async methods to get the free space and capacity.
When I build this is it generates the winmd files no problems, I have correctly registered and loaded these in my cordova (Visual Studio 2017) project, Build for Windows 10 and run - when I run this code in the main cordova project
DiskSpacePlugin.info({}, function (ok) { console.log(ok); }, function (err) { console.log(err); });
I get this result in the console
WinRTError: The system cannot find the file specified.
System.IO.FileNotFoundException: Could not load file or assembly 'System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
at DiskSpaceLibrary.DiskSpace.sizeFolder(StorageFolder folder)
at DiskSpaceLibrary.DiskSpace.<>c__DisplayClass5_0.<infoTask>b__0()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.Ex
console-via-logger.js (173,15)
{
[functions]: ,
__proto__: { },
asyncOpCausalityId: 461,
asyncOpSource: { },
asyncOpType: "Windows.Foundation.IAsyncOperation`1<String>",
description: "The system cannot find the file specified.
System.IO.FileNotFoundException: Could not load file or assembly 'System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
at DiskSpaceLibrary.DiskSpace.sizeFolder(StorageFolder folder)
at DiskSpaceLibrary.DiskSpace.<>c__DisplayClass5_0.<infoTask>b__0()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.Ex",
message: "The system cannot find the file specified.
System.IO.FileNotFoundException: Could not load file or assembly 'System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
at DiskSpaceLibrary.DiskSpace.sizeFolder(StorageFolder folder)
at DiskSpaceLibrary.DiskSpace.<>c__DisplayClass5_0.<infoTask>b__0()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.Ex",
name: "WinRTError",
number: -2147024894
}
I have also tried another module for unzipping files in a cordova windows 10 project (I do not have the source for this one however it comes from https://github.com/Culture22/cordova-windows10-zip) and it comes up with exactly the same error messages when I try to run it within the app.
I have googled and looked for this issue for the last 4 days and I am unable to progress, the methods being used are all support by the framework apparently looking at (msdn.microsoft.com/en-us/library/windows/apps/mt185496.aspx) - does anyone have any insight?
It seems like the library you're referencing references the System.IO.FileSystem.dll, however for whatever reason its not getting deployed with your application. I suggest try adding a nuget reference to System.IO.FileSystem.dll to your application.
I am initializing log as below.
protected void InitializeLogging (string logFolderStoragePath)
{
if (string.IsNullOrEmpty (logFolderStoragePath)) {
logFolderStoragePath = _externalStorageFolderPath;
}
string settingsIniFilePath = Path.Combine (logFolderStoragePath, _settingsFileName);
if (_fileSystem.FileExists(settingsIniFilePath))
{
FileIniDataParser iniFile = new FileIniDataParser();
IniData data = iniFile.ReadFile(settingsIniFilePath);
}
}
I am calling function as:
InitializeLogging (logFolderStoragePath);
While executing above line, I am getting exception as:
An exception of type 'System.TypeLoadException' occurred in
App.Forms.WindowsPhoneShared.DLL but was not handled in user code
Additional information: Could not load type 'System.ICloneable' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e'.
Even though I have set break-point in InitializeLogging function, its not even entering that function, its throwing exception before that. To find exactly where its breaking I commented one by one and found because of below line.
IniData data = iniFile.ReadFile(settingsIniFilePath);
If you see, I am reading iniFile only if settingsIniFilePath exist, but the file itself doesn't exist, still it throws exception.