Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a missing .NET reference at runtime?

My application contains references to an external library (the SQL Server Management Objects). Apparently, if the library is not present on the run-time system, the application still works as long as no methods are called that use classes from this library.

Question 1: Is this specified behaviour or just a (lucky) side effect of the way the CLR loads libraries?

To detect whether the reference is accessible, I currently use code like this:

Function IsLibraryAvailable() As Boolean
    Try
        TestMethod()
    Catch ex As FileNotFoundException
        Return False
    End Try
    Return True
End Function

Sub TestMethod()
    Dim srv As New Smo.Server()  ' Try to create an object in the library
End Sub

It works, but it seems to be quite ugly. Note that it only works if TestMethod is a separate method, otherwise the exception will be thrown at the beginning of IsLibraryAvailable (before the try-catch, even if the object instantiation occurrs within the try-catch block).

Question 2: Is there a better alternative?

In particular, I'm afraid that optimizations like function inlining could stop my code from working.

like image 458
Heinzi Avatar asked Jul 27 '11 16:07

Heinzi


People also ask

How do I find missing references in Visual Studio?

In Solution Explorer, right-click your project node, and then select Properties. The Project Designer appears. If you're using Visual Basic, select the References page, and then click the Reference Paths button.

How do I find references in Visual Studio?

You can use the Find All References command to find where particular code elements are referenced throughout your codebase. The Find All References command is available on the context (right-click) menu of the element you want to find references to. Or, if you are a keyboard user, press Shift + F12.

Which of the following helps in finding the methods of an assembly file at runtime?

The term probing is often used when describing how the runtime locates assemblies; it refers to the set of heuristics used to locate the assembly based on its name and culture. You can view binding information in the log file using the Assembly Binding Log Viewer (Fuslogvw.exe), which is included in the Windows SDK.


1 Answers

That is expected, since the JIT is lazy at the per-method level. Note that inlining isn't an issue here, since that is also a JIT concern, not a compiler concern.

Better options:

  • make sure the app is installed with everything it needs
  • using ilmerge or similar to create a single assembly (if possible)

Personally, I'd just use the first option.

like image 112
Marc Gravell Avatar answered Oct 18 '22 18:10

Marc Gravell