AntiForgery error when calling AssemblyResolve function - c#

I'm adding my own custom loader to AssemblyResolve to load some embedded resources in a .net library;
AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => { return Domain.Assemblies.LoadResource(e.Name, System.Reflection.Assembly.GetExecutingAssembly()); };
public static System.Reflection.Assembly LoadResource(string fileName, System.Reflection.Assembly assembly)
{
fileName = assembly.GetName().Name + "." + fileName.Split(',')[0] + ".dll";
var resFilestream = assembly.GetManifestResourceStream(fileName);
byte[] ba = new byte[resFilestream.Length];
resFilestream.Read(ba, 0, ba.Length);
var byteArray = ba;
resFilestream.Close();
resFilestream.Dispose();
return System.Reflection.Assembly.Load(byteArray);
}
This works fine in many different environments(Winforms, Azure apps/webjobs/functions), but when I try to execute this code within an asp.net(4.7.2) MVC site, it breaks the anti-forgery? The issue seems to be related a DLL not being loaded correctly, and causes three seperate errors
TypeInitializationException: The type initializer for 'System.Web.Helpers.Claims.ClaimsIdentityConverter' threw an exception.
FileLoadException: Could not load file or assembly 'Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. Invalid pointer (Exception from HRESULT: 0x80004003 (E_POINTER))
NullReferenceException: Object reference not set to an instance of an object.
If I remove the object initialising the class within the assembly loading dll, the site works with no error. If I put it back in it breaks. I also tried moving the code from the global.asax to in-line c#, but as soon as you run it, the next load of a page with a forgery token will error in the same way.
UPDATE
Having run Fusion++ to check the DLL loading, I can see that the DLL that is erroring actually has the exact same load failure in both situations(A fairly generic "Could not find assembly"). But only when I load my DLL does it present itself as an exception.

The problem is not with your code, but this dependecy Microsoft.IdentityModel: to exist this dependency and possibilty to consume into Windows client environment, probally the dll and dependecies needs to be installed at GAC (Global Assembly Cache); if Microsoft.IdentityModel not exists into GAC Folder, the code returns the error.
It's possible to install the Windows Identity Foundation 3.5 with Visual Studio or from Windows Features install the Windows Identity Foundation 3.5.

Related

"Could not load file or assembly" using COM Interop (DLL HELL?)

I'm building a COM Visible Object that needs to get called from a software written in Sybase Powerbuilder 11.5.
I'm using C# and .Net Framework 4.7.2.
I ususally build this kind of objects with no problem and register them using regasm /codebase because that's the way Powerbuilder likes them.
Now I'm trying to build an object that references the latest version of these nuget packages:
Microsoft.Graph
Microsoft.Graph.Auth
Microsoft.IdentityModel.Clients.ActiveDirectory
Graph.Community
I have my class library project with a com visible class.
I built a console application that references that library (it does not use COM server) to test the code and everything works fine on my development machine from the command line.
I can also run the console application from my target machin with no issues.
When I try to run the Powerbuilder application that uses the COM object, it throws an error:
Could not load file or assembly 'Microsoft.Graph.Core, Version=1.23.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies.
I have that dll in assembly's folder, but it is version 1.24.0.0.
I have two questions:
Why does the console application work while the COM object doesn't, given that they are using the same assemblies?
How I solve this versioning problem in the COM version of the object?
I found the solution to the problem but did not fully understand it.
It was a cross reference problem, where packages A and B were both dependent on package C, but required different versions.
I don't understand why this error shows up only when using COM Interface and not with the console application.
Here is what I did to solve:
// Define the AssemblyResolve event in the constructor of the COM Object.
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
// Get the path where COM Object's dll is
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
_dllPath = System.IO.Path.GetDirectoryName(path);
Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
// Get the name of the assembly that failed loading
var name = new AssemblyName(args.Name);
// Manage the assembly that I know will cause problems
string bindingAssembly = "Microsoft.Graph.Core";
if (name.Name == bindingAssembly)
{
// Load the assembly from the COM Object's folder, and use whatever version there is
return Assembly.LoadFrom(System.IO.Path.Combine(_dllPath, bindingAssembly + ".dll"));
}
// I should not get here. If I do I need to add another manual assembly load for the dll that failed loading
return null;
}

JSON.net functions no longer working in VS2012 [duplicate]

I have added third party reference (Json newtonsoft) dll in my script component (using edit script option), but when i run the package, I am getting an error
Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.
Any suggestions?
I will not be able to add the dll in GAC.
I am using SQL Server 2008.
By "Running," I assume running from agent/command-line is failing? It should work from within BIDS/SSDT. The short answer is the DLL must be registered with the GAC or you can download the source code and add that project into the script task and then reference said project.
Looking at the project, it should be a strongly signed DLL (based on presences of Dynamic.snk) and thus capable of being added to the GAC. Oh, but you state you will not be able to add it into the GAC, implying it's a permission not a capability issue.
If that's the case, either compile the project in with the source or surround it with a web service wrapper and then reference the service.
I also saw this answer, seems you can try loading the references dynamically.
Automated deployment of mixed SSIS / DLL solution
You can using Reflection to load dll at runtime from file system without needing to install in GAC . This is helpful if permission to install in GAC is not availaible .
//Add a Static Constructor which is guaranteed to be called exactly once
// “before the first instance is created or any static members are referenced.”,
// so therefore before the dependent assemblies are loaded.
static ScriptMain()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
//Provide path to dll stored in folder on file system
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string path = #"D:\DLL\";
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "Newtonsoft.dll"));
}
Ofcourse you need to also Add Reference to dll in script task .

Add third party dll reference in ssis script component

I have added third party reference (Json newtonsoft) dll in my script component (using edit script option), but when i run the package, I am getting an error
Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.
Any suggestions?
I will not be able to add the dll in GAC.
I am using SQL Server 2008.
By "Running," I assume running from agent/command-line is failing? It should work from within BIDS/SSDT. The short answer is the DLL must be registered with the GAC or you can download the source code and add that project into the script task and then reference said project.
Looking at the project, it should be a strongly signed DLL (based on presences of Dynamic.snk) and thus capable of being added to the GAC. Oh, but you state you will not be able to add it into the GAC, implying it's a permission not a capability issue.
If that's the case, either compile the project in with the source or surround it with a web service wrapper and then reference the service.
I also saw this answer, seems you can try loading the references dynamically.
Automated deployment of mixed SSIS / DLL solution
You can using Reflection to load dll at runtime from file system without needing to install in GAC . This is helpful if permission to install in GAC is not availaible .
//Add a Static Constructor which is guaranteed to be called exactly once
// “before the first instance is created or any static members are referenced.”,
// so therefore before the dependent assemblies are loaded.
static ScriptMain()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
//Provide path to dll stored in folder on file system
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string path = #"D:\DLL\";
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "Newtonsoft.dll"));
}
Ofcourse you need to also Add Reference to dll in script task .

Assembly.GetExportedTypes() does not work in .NET 4.0 (same code runs in 3.5)

Hey guys (and gals) I'm having a problem using Assembly GetExportedTypes() in .NET 4.0. The same code is working perfectly in a project targeted at an older .NET version.
NOTE: *The code works for local assemblies but when trying to open them off a network drive it does not work, that is my problem... It looks to be loading the assembly, but it claims it can't find it when using GetExportedTypes(). Again if I open a dll off my machine it works, this error only occurs with dlls located on network drives *
EDIT: The error is thrown on GetExportedTypes
The Code:
Assembly assembly;
Type[] t;
assembly = Assembly.LoadFrom(dllPathOpenFileDialog.FileName.ToString());
t = assembly.GetExportedTypes();
The Error:
Could not load file or assembly '*..***.***.****, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
(I used asterisks to hide personal information - the file name)
The way certain security policies are handled was changed in .NET 4.0. This article should provide some background.

Unable to load assembly with windows service

I have created a windows service in C# VS2008 that uses a reference to an external class library to wrote. I have added the reference to it in VS2008. When I run start the service it throws an exception when trying to access the external DLL:
Could not load file or assembly 'vcribAPI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
The DLL is in the same directory as the service.exe file. Is there something special that I need to do for windows services like putting the DLL in another directory?
It could be that vcribAPI.dll relies on other assemblies as well. I suggest using Reflector and open up the dll to see what other dll's it might reference.
I encountered exactly the same error.
The working directory of services is different from the application directory (typically C:\Windows\System32).
For example, the method AssemblyName.GetAssemblyName throws a FileNotFoundException if you try to locate an assembly deployed in the application directory.
In this case, the solution is to define Environment.CurrentDirectory with the application directory before assembly loading.
Sample code :
const string SCHEMA_FILE = #"file:\";
var appAssembly = Assembly.GetExecutingAssembly();
var path = Path.GetDirectoryName(appAssembly.CodeBase);
if (path.StartsWith(SCHEMA_FILE))
path = path.Remove(0, SCHEMA_FILE.Length);
Environment.CurrentDirectory = path;
Does you service have rights to read in the folder?
Does the assembly have other dlls or assemblies it depends on?
If so, they also need to be in this directory.
To be certain, start up the Assembly Loader Log (fusion log). See this howto (Debugging Assembly Loading Failures).

Categories