System.IO.FileLoadException loading Facebook assembly - c#

I'm having the following code that does not compile:
{
private static FacebookWrapper.FacebookService m_FacebookService;
User m_LoggedInUser;
public void LoginToFBApp(FacebookWrapper.FacebookService i_FacebookService)
{
LoginResult result = FacebookWrapper.FacebookService.Login("192940970765612",
new string[]
{
"user_about_me", "friends_about_me", "publish_stream"
//,
//"user_activities", "friends_activities",
//"user_birthday", "friends_birthday",
//"user_checkins", "friends_checkins",
//"user_education_history", "friends_education_history",
//"user_events", "friends_events",
//"user_groups" , "friends_groups",
//"user_hometown", "friends_hometown",
//"user_interests", "friends_interests",
//"user_likes", "friends_likes",
//"user_location", "friends_location",
//"user_notes", "friends_notes",
//"user_online_presence", "friends_online_presence",
//"user_photo_video_tags", "friends_photo_video_tags",
//"user_photos", "friends_photos",
//"user_photos", "friends_photos",
//"user_relationships", "friends_relationships",
//"user_relationship_details","friends_relationship_details",
//"user_religion_politics","friends_religion_politics",
//"user_status", "friends_status",
//"user_videos", "friends_videos",
//"user_website", "friends_website",
//"user_work_history", "friends_work_history",
//"email",
//"read_friendlists",
//"read_insights",
//"read_mailbox",
//"read_requests",
//"read_stream",
//"xmpp_login",
//"create_event",
//"rsvp_event",
//"sms",
//"publish_checkins",
//"manage_friendlists",
//"manage_pages",
//"offline_access"
},
false);
}
}
I'm using an DLL that I was given,in wich is helping to perform Login to facebook account. When activating my program,the program is trying to connect to facebook,but I'm getting the exeption with the text that is shown in the headline of this message.
Extra information appears in the exeption:
Could not load file or assembly 'Facebook, Version=5.0.50.0, Culture=neutral, PublicKeyToken=58cb4f2111d1e6de' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
I don't understand where exactly is the problem....

Related

Assembly.LoadFile is non-compliant?

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?

Load a com DLL in c#

I want to load a COM dll dynamically in c# console application.
Till now I have tried the following code:
// load exe with args as EXE DllName classNameTobeLoaded
try
{
// load assembly
Assembly Dll = Assembly.LoadFile(#"C:\My_Dir\TestComDll.dll");
// get the type names
foreach(Type t in Dll.GetExportedTypes())
{
dynamic vClassLoaded = Activator.CreateInstance(t,"Test");
Console.WriteLine("Type Loaded");
}
Console.WriteLine("DLL is loaded");
}
catch (Exception ex)
{
Console.WriteLine("Unable to load a DLL because \n" + ex.Message);
}
But while loading the dll I am getting error as:
{System.BadImageFormatException: The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)
at System.Reflection.RuntimeAssembly.nLoadFile(String path, Evidence evidence)
at System.Reflection.Assembly.LoadFile(String path)
at ThirdPartyDLLLoader.Program.Main(String[] args) in h:\Test Exe\ThirdPartyDLLLoader\ThirdPartyDLLLoader\Program.cs:line 18}
The same code is working fine for .NET DLL.
Can any one tell me why the code is not able to load a COM dll dynamically?
and if it is not can you please tell me how I can do the same.
Thanks for any suggestion and help.
This cannot be done. The Assembly.LoadFrom method is for loading .NET assemblies. COM library must be registered and then you can instantiate classes using Activator.CreateInstance method.
This is how I access MS Word:
Type type = Type.GetTypeFromProgID("Word.Application");
object obj = Activator.CreateInstance(type);
I have a function load a class library dll
public ICollection<Assembly> GetAssemblies(string pathOfDLL)
{
List<Assembly> baseAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
var controllersAssembly = Assembly.LoadFrom(pathOfDLL);
baseAssemblies.Add(controllersAssembly);
return baseAssemblies;
}
Hope it helps!

Trying to fake a Strong Named Assembly, but "manifest definition does not match"

I'd like to intercept the communication between a plug-in and a host assembly.
I've tried to load ThirdPartyPlugin.dll into an AppDomain sandbox (code below), to intercept its attempts at loading of HostLibrary.dll assembly (I'm using trick with handling the AssemblyResolve event). Instead of the original HostLibrary.dll, I'm then trying to inject a fake one, with some different functionalities.
Unfortunately, the original HostLibrary.dll is a Strong Named Assembly, and I think because of that I'm getting an exception like below in my program:
Unhandled Exception: System.IO.FileLoadException: Could not load file or assembly 'HostLibrary, Version=7.0.0.0, Culture=neutral, PublicKeyToken=1a2b3c4d5e6f7890' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) ---> System.IO.FileLoadException: The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
The fake assembly I created does match the name ("HostLibrary"), and the version ("7.0.0.0") of the original assembly; at one time I think I even made it apparently match the PublicKeyToken (when I printed Assembly.FullName, it was identical), but the exception still occurs.
Do you have any ideas as to how I could resolve this problem? Is it possible to resolve at all? Does it happen because of digital signature, or something else? If signature, then is it possible to disable the check? Actually, from reading an article by Ian Picknell, I'd think I should not really be having this problem... so what's wrong?
The code is:
static void Main(string[] args)
{
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationName = "WrapperBuddy";
setup.ApplicationBase = System.Environment.CurrentDirectory;
AppDomain sandbox = AppDomain.CreateDomain("SandboxBuddy", null, setup);
sandbox.AssemblyResolve += delegate(object sender, ResolveEventArgs args)
{
String name = new AssemblyName(args.Name).Name;
return BuildFakeAssembly(name);
};
sandbox.DoCallBack(delegate()
{
Assembly plugin = LoadAssembly(PLUGIN_DIR, "ThirdPartyPlugin");
System.Console.WriteLine(plugin.GetExportedTypes()); // (1)
});
}
with helper functions defined as:
static Assembly LoadAssembly(String dir, String name)
{
string path = Path.Combine(dir, name) + ".dll";
return Assembly.Load(File.ReadAllBytes(path));
}
static Assembly BuildFakeAssembly(String name)
{
AssemblyName aName = new AssemblyName(name);
// see: http://msdn.microsoft.com/en-us/library/w58ww7se%28v=vs.85%29.aspx
// http://msdn.microsoft.com/en-us/library/w58ww7se%28v=vs.100%29.aspx
aName.KeyPair = new StrongNameKeyPair(new FileStream(#"MyKey.snk", FileMode.Open));
// MyKey.snk is a random key generated using sn.exe
aName.Version = new Version("7.0.0.0");
//aName.SetPublicKeyToken(new byte[] { 0x11, 0x22, ... }); // didn't help
AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(
aName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");
return ab;
}
I'd be grateful for any help.

Under what circumstanses will AppDomain.DoCallback() fail?

I'm trying to use AppDomain to load and unload assemblies run-time. I'm trying to get the example on MSDN working in my application before implementing assembly loading, but I'm running into issues - the DoCallback-invokation fails with exception
Could not load file or assembly '[MyPluginAssembly], Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null' or one of its dependencies. The
system cannot find the file specified.
My assembly ([MyPluginAssembly]) is running loaded by a host application (i.e. it is a plugin). The plugins AppDomain seem to be the application-domain (i.e. it is not sandboxed in a separate domain). I've tried loading the entry/calling/executing-assembly in the new domain to ensure [MyPluginAssembly] is loaded, but even though these calls return non-null I still get the exception above.
The code I use (as in the example on MSDN + the code to load the "parent"-assemblies):
public class PingPong : MarshalByRefObject
{
private string greetings = "PING!";
public static void Main()
{
AppDomain otherDomain = AppDomain.CreateDomain("otherDomain");
// All of these Load()-calls returns non-null
Assembly entryAssembly = otherDomain.Load(Assembly.GetEntryAssembly().GetName());
Assembly callingAssembly = otherDomain.Load(Assembly.GetCallingAssembly().GetName());
Assembly executingAssembly = otherDomain.Load(Assembly.GetExecutingAssembly().GetName());
PingPong pp = new PingPong();
pp.MyCallBack();
pp.greetings = "PONG!";
otherDomain.DoCallBack(new CrossAppDomainDelegate(pp.MyCallBack));
// Output:
// PING! from defaultDomain
// PONG! from defaultDomain
}
// Callback will always execute within defaultDomain due to inheritance from
// MarshalByRefObject
public void MyCallBack()
{
string name = AppDomain.CurrentDomain.FriendlyName;
if (name == AppDomain.CurrentDomain.SetupInformation.ApplicationName)
{
name = "defaultDomain";
}
Console.WriteLine(greetings + " from " + name);
}
}
What circumstances can cause the exception I get?
You should look at the CreateInstanceFromAndUnwrap method. It is the one to use for sandboxed add-in scenarios like yours. System.AddIn (MAF) is using this method to load the add-in pipeline segments.

NRefactory - missing file

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.

Categories

Resources