.net load latest version of assembly - c#

I have a .net application that references the Microsoft.SqlServer.Smo assembly.
The assembly is not distributed with the application. Instead the sql sdk is installed in the system and the dll is registered in the GAC so that the application can load.
There is no problem with this except that on some target machines I have the v12 of the SDK, while on others I have the v13 of the SDK (that usually comes installed with SSMS).
I would like the application to load the latest version of whatever is available on the system, so v13 or, if not available, v12.
Is it possible to achieve this in code or through the application config?

The short answer to the question is to set SpecificVersion to false as correctly suggested by #sevzas.
Anyway, if on the system is installed SSMS 2016 update 13.0.16000.28, the 13.100.0.0 of the dll will be registered in the GAC and with the above change, this is the version that it will be loaded. Unfortunately this version is not meant to be used by 3rd party developers but only by Microsoft products, so trying to load it will generate an exception (see here). Someone could wonder at this point why they register it in the GAC if they don't want people to use it.
Anyway, I found a way to load the v13.0 (or previous, or future 14) with the below code by using the assembly resolve event.
static int Main(string[] args)
{
//we set an event handler at the begging of our program
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
//your stuff
}
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
//if the dll is a sqlserver dll, we do our trick
if(args.Name.StartsWith("Microsoft.SqlServer"))
return LoadSqlAssembly(args.Name);
return null;
}
private static readonly int[] SqlVersions = new int[] {14, 13, 12, 11};
private static bool _reEntry = false;
private static Assembly LoadSqlAssembly(string name)
{
if (_reEntry)
return null;
name = name.Split(',')[0];
foreach (var version in SqlVersions)
{
try
{
_reEntry = true;
var ret = Assembly.Load($"{name}, Version={version}.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL");
//Logger.InfoFormat("Loaded {0} version {1}", name, version);
return ret;
}
catch (Exception)
{
//ignore exception
}
finally
{
_reEntry = false;
}
}
return null;
}
```

Related

How to load / unload an assembly using the lastest .NET 5.0 from previous .NetCore 3.1

I'm in the process of upgrading my code to .Net 5.0 from .Net Framework 4.8.
One of the useful upgrades deals with the possibility of loading and unloading assemblies on the fly without restarting the application. So far I've managed to code the following function in c# for loading an assembly.
However information on google on how to do it systematically, for instance as a plugin mod, enabling management of assemblies loaded / unloaded during the execution of the application is scarce or even non existent!!! So any help is greatly appreciated .
private static FormCustomized loadLayout(global::System.String layoutFilename, global::System.String layoutNameSpace)
{
FormCustomized mainForm = default;
Type typeMainLayout = default;
FileInfo layoutFile;
layoutFile = new FileInfo(layoutFilename);
layoutFile.Refresh();
if (!layoutFile.Exists)
{
MessageBox.Show("Layout file not found. You need to reinstall the program");
return default;
}
try
{
Assembly assemblyRaw = Assembly.LoadFrom(layoutFilename);
AssemblyLoadContext context = AssemblyLoadContext.Default;
Assembly assembly = context.LoadFromAssemblyPath(layoutFilename);
Type typeMainLayoutIni = assembly.GetType(layoutNameSpace + ".initializeLayoutClass");
Object iniClass = Activator.CreateInstance(typeMainLayoutIni, true);
MethodInfo methodInfo = typeMainLayoutIni.GetMethod("AssembliesToLoadAtStart");
enVars.assemblies = (Dictionary<string, Environment.environmentAssembliesClass>)methodInfo.Invoke(iniClass, default);
typeMainLayout = assembly.GetType(layoutNameSpace + ".mainAppLayoutForm");
mainForm = Activator.CreateInstance(typeMainLayout, enVars) as FormCustomized;
}
catch (Exception ex)
{
return default;
}
return default;
}

Inno Setup - External .NET DLL with dependencies

I am trying to use a custom DLL in a Inno Setup script during installation. I wrote a very simple function that basically checks a connection string for a MySQL database using MySQL .NET connector (there is no MySQL client on the target server). The code of this exported function is:
public class DbChecker
{
[DllExport("CheckConnexion", CallingConvention.StdCall)]
public static int CheckConnexion([MarshalAs(UnmanagedType.LPStr)] string connexionString)
{
int success;
try
{
MySqlConnection connection = new MySqlConnection(connexionString);
connection.Open();
connection.Close();
success = 0;
}
catch (Exception)
{
success = 1;
}
return success;
}
}
The function is imported this way in Inno Setup :
[Files]
Source: "..\..\MyDll\bin\x86\Release\*"; Flags: dontcopy;
and
[Code]
function CheckConnexion(connexionString: AnsiString): Integer;
external 'CheckConnexion#files:MyDll.dll,MySql.Data.dll stdcall setuponly loadwithalteredsearchpath';`
The problem is that the setup throws an exception at runtime:
Runtime Error (at 53:207):
External exception E0434352.
I think I have to use the files prefix because the function is called in the NextButtonClick event handler, before files are copied to the {app} directory.
Both MyDll.dll and MySql.Data.dll are correctly extracted to the {tmp} directory at runtime.
I tried both with and without the loadwithalteredsearchpath flag with the same result.
What I found is that this error code is a generic .NET runtime error code.
If I remove the part using MySql.Data it works perfectly fine (except that it does nothing...)
As advised on other threads I've been trying to log the error in my .NET code using EventLog and UnhandledException but I have the same exception no matter what (and no log source is created), even without the MySQL part. I checked EventLog permissions on my computer.
It seems that the exception is thrown as soon as I use anything else that "basic" C# code (whenever I try to load another DLL).
There is probably a better way, but this will do.
Implement an initialization function (Init here) that sets up AppDomain.AssemblyResolve handler that looks for an assembly in the path of the main (executing) assembly:
[DllExport("Init", CallingConvention.StdCall)]
public static void Init()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
}
private static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
{
string location = Assembly.GetExecutingAssembly().Location;
AssemblyName name = new AssemblyName(args.Name);
string path = Path.Combine(Path.GetDirectoryName(location), name.Name + ".dll");
if (File.Exists(path))
{
return Assembly.LoadFrom(path);
}
return null;
}
Import it to the Inno Setup:
procedure Init(); external 'Init#files:MyDll.dll stdcall setuponly';
And call it before calling the function that needs the dependency (CheckConnexion).
Another solution might be this:
Embedding DLLs in a compiled executable
Btw, no need for the loadwithalteredsearchpath flag. It has no effect on .NET assemblies imo. They are needed for native DLL dependencies: Loading DLL with dependencies in Inno Setup fails in uninstaller with "Cannot import DLL", but works in the installer.
I found something else that might be helpful for anyone stumbling upon this page.
In my scenario, I have several C# methods that I call from InnoSetup using DllExport. In one of those methods, I call another of the methods. This caused Inno to throw "External exception E0434352".
If I moved the code to a method not called by InnoSetup, everything worked fine.
So...
[DllExport("Fu", CallingConvention = CallingConvention.StdCall)]
public static int Fu()
{
// Stuff
}
[DllExport("Bar", CallingConvention = CallingConvention.StdCall)]
public static int Bar()
{
Fu();
}
...causes InnoSetup to cry, but:
[DllExport("Fu", CallingConvention = CallingConvention.StdCall)]
public static int Fu()
{
LocalFu();
}
private static int LocalFu()
{
// Stuff
}
[DllExport("Bar", CallingConvention = CallingConvention.StdCall)]
public static int Bar()
{
// Stuff
LocalFu();
// Other stuff
}
...is fine.
I don't know if this is caused by Inno or DllExport, so I'll forgo direct derision and blame society as a whole for my lost morning. (Or myself for being a new to this thing.)
I would like to expand upon Martin's answer. There is a way to resolve the assemblies without having to call an Init method first and that is by including a static constructor in your .NET class:
public class MyClass
{
static MyClass()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += MyResolveEventHandler;
}
private static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
{
var location = Assembly.GetExecutingAssembly().Location;
var assemblyName = new AssemblyName(args.Name);
var path = Path.Combine(Path.GetDirectoryName(location), assemblyName.Name + ".dll");
if (File.Exists(path))
{
return Assembly.LoadFrom(path);
}
return null;
}
}

Load NuGet dependencies at runtime

I'm looking for a way to run code by executing the following steps:
Receiving a list of NuGet packages (a list of tuples ("package name", "package version", "path to main class").
Retrieving them in a local directory (cf code sample #1)
Loading them in my program at run-time
Running the main classes by introspection (cf code sample #2)
By now I am struggling with the third step. I can't find out how to load my package at run-time.
My main question are:
How can I find out in which folders were stored the retrieved packages?
How can I load the content of those directories into my program?
Code Sample #1:
private static void getPackageByNameAndVersion(string packageID, string version)
{
IPackageRepository repo =
PackageRepositoryFactory.Default
.CreateRepository("https://packages.nuget.org/api/v2");
string path = "C:/tmp_repo";
PackageManager packageManager = new PackageManager(repo, path);
Console.WriteLine("before dl pkg");
packageManager.InstallPackage(packageID, SemanticVersion.Parse(version));
}
Code sample #2:
private static void loadByAssemblyNameAndTypeName(string assemblyName, string typeName)
{
AppDomain isolationAppDomain = AppDomain.CreateDomain("tmp");
object a = isolationAppDomain.CreateInstanceAndUnwrap(assemblyName, typeName);
Type x = a.GetType();
MethodInfo m = x.GetMethod("Main");
m.Invoke(a, new object[] { });
}
Grab a cup of coffee :)
Downloading the nuget package?
Nuget.Core (nuget package) is a good choice, and here is a snippet of code that I have that should be able to download a nuget package by id and version
var repo = PackageRepositoryFactory.Default
.CreateRepository("https://packages.nuget.org/api/v2");
string path = "c:\\temp";
var packageManager = new PackageManager(repo, path);
packageManager.PackageInstalled += PackageManager_PackageInstalled;
var package = repo.FindPackage("packageName", SemanticVersion.Parse("1.0.0"));
if (package != null)
{
packageManager.InstallPackage(package, false, true);
}
Notice that I plugged an event handler to the PackageInstalled event of the PackageManager class.
How do we load an assembly in an isolated app domain?
Since reflection API does not provide a way to load an assembly in a specific domain, We will create a proxy class that act as a loader in our isolated domain:
public class TypeProxy : MarshalByRefObject
{
public Type LoadFromAssembly(string assemblyPath, string typeName)
{
try
{
var asm = Assembly.LoadFile(assemblyPath);
return asm.GetType(typeName);
}
catch (Exception) { return null; }
}
}
And now, is how to put it all together?
Here comes the complex part:
private static void PackageManager_PackageInstalled(object sender,
PackageOperationEventArgs e)
{
var files = e.FileSystem.GetFiles(e.InstallPath, "*.dll", true);
foreach (var file in files)
{
try
{
AppDomain domain = AppDomain.CreateDomain("tmp");
Type typeProxyType = typeof(TypeProxy);
var typeProxyInstance = (TypeProxy)domain.CreateInstanceAndUnwrap(
typeProxyType.Assembly.FullName,
typeProxyType.FullName);
var type = typeProxyInstance.LoadFromAssembly(file, "<KnownTypeName>");
object instance =
domain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);
}
catch (Exception ex)
{
Console.WriteLine("failed to load {0}", file);
Console.WriteLine(ex.ToString());
}
}
}
Notice that this method is the event handler that gets executed after downloading the nuget package
Also
Note that you will need to replace <KnownTypeName> with the expected type name coming from the assembly (or maybe run a discovery of all public types in the assembly)
Worth noting that I haven't executed this code myself and cannot guarantee that it will work out of the box, and still might need some tweaking. but Hopefully it is the concept that allows you to solve the problem.
Don't do that! You are probably trying to load NuGet content at a customers computer to save some space on distribution of your software. Isn't it that?
The common recommended approach is to download the NuGet content as the second step of an automated build (after downloading the source code), build the software and run the automated tests with the NuGet content you have downloaded. And then distribute the build with the NuGet content you have tested as the complex whole unit.

Checking if Oracle.DataAccess Exists

I want to check whether the correct version of the Oracle driver is installed and can be found before an application runs so I can display an error message and fail gracefully. This is a C# windows forms application.
When I run the application on a machine that doesn't have the correct version of Oracle, I get the following message and the application is left in a hung state:
Could not load file or assembly 'Oracle.DataAccess, Version=2.112.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies. The system cannot find the file specified.
How can I reliably check if this assembly is available?
In addition yo your own answer, you could also do it in a general way (for all assembly loading issues) using the AssemblyResolve event. Here's an example:
AppDomain.CurrentDomain.AssemblyResolve += (sender, prms) => {
Console.WriteLine("Could not load assembly \"{0}\".", prms.Name);
Console.ReadLine();
Environment.Exit(1);
return null;
};
Assembly.Load("this asembly does not exist");
You can use System.Data.Common.DbProviderFactories to achieve the same.
The sample code below can check it for you.
private bool checkSpecifiedProviderExists()
{
var connectionStringSettings = ConfigurationManager.ConnectionStrings["YourConnectionString"];
var factory = DbProviderFactories.GetFactory(connectionStringSettings.ProviderName);
try
{
var dbConnection = factory.CreateConnection();
if(dbConnection !=null) return true;
return false;
}
catch
{
return false;
}
}

C# Autonomous Update

in my new project (windows-C#-vs2008)I want the executable to be able to autonomously update itself- perhaps from a network server
Here What I do is download any updated dlls to "isolated storage" (each as separate dlls) then modify the CurrentDomain_AssemblyResolve() method
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
such that it first checks for the presence of library in its isolated storage before loading it from executable .
But what if I want to change something in the main exe.
[I tried creating a loader project(console ap) from which, it calls my main program(changed output as dll) ,however this time the assembly resolve event is not getting trigger because the reference dlls are geting generated under bin folder of new loader project during compilation ]
Any help would be highly appreciated..
public static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
try
{
string assemName = new AssemblyName(args.Name).Name;
object i_StoreRootDir = i_StorageFile.GetType().GetField
("m_RootDir", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(i_StorageFile);
string i_StorePath = CombinePaths(i_StoreRootDir.ToString(), I_STOREDIR, assemName, DLL_EXT);
if (File.Exists(i_StorePath))
{
return Assembly.LoadFrom(i_StorePath);
}
else
{
//load it from resource.
return null;
}
}
catch (Exception)
{
throw;
}
You may take a look at ClickOnce deployment as part of the framework. You may also checkout wyUpdate. There's also BitsUpdater.

Categories

Resources