Extend Your Apps with External Add-ins: VB.NET: Create a Helper Class: Listing 1
A helper class can simplify and isolate hosting add-ins. Making this class generic allows a single helper class for use with all add-ins. This version improves performance by ensuring the store is built exaclty once during the application run and caching the loaded add-ins. The Shutdown method unloads an add-in by unloading its containing AppDomain.
Imports System.AddIn.Hosting
Public Class AddInSupport(Of T)
Private Shared mHaveCheckedStore _
As Boolean
Private Shared mLoadedAddIns _
As New Dictionary(Of String, T)
Public Shared Function GetAddInList( _
ByVal addInRoot As String) _
As IEnumerable(Of AddInToken)
UpdateStore(addInRoot)
Return AddInStore.FindAddIns( _
GetType(T), addInRoot)
End Function
Public Shared Function GetAddIn( _
ByVal addInRoot As String, _
ByVal addInName As String) _
As T
Dim addIn As T = Nothing
If mLoadedAddIns.TryGetValue( _
addInName, addIn) Then
Return addIn
End If
Dim addIns = GetAddInList(addInRoot)
If addIns.Count = 0 Then
' Log for user
Return Nothing
End If
Dim selectedAddToken _
As AddInToken = Nothing
If String.IsNullOrEmpty( _
addInName) Then
selectedAddToken = addIns(0)
Else
selectedAddToken = ( _
From x In addIns _
Where x.Name.Equals( _
addInName, _
StringComparison. _
OrdinalIgnoreCase) _
Select x).FirstOrDefault
End If
If selectedAddToken Is Nothing Then
Return Nothing
End If
Try
addIn = _
selectedAddToken. _
Activate( Of T)( _
AddInSecurityLevel. _
Internet)
mLoadedAddIns.Add( _
addInName, addIn)
Return addIn
Catch ex As Exception
Console.WriteLine(ex)
End Try
Return Nothing
End Function
Private Shared Sub UpdateStore( _
ByVal addInRoot As String)
If Not mHaveCheckedStore Then
Try
If Not IO.Directory.Exists( _
addInRoot) Then
Throw New _
ArgumentException( _
"Directory not available")
End If
Dim warnings() As String = _
AddInStore.Update( _
addInRoot)
If (warnings.Length > 0) Then
Console.WriteLine( _
"WARNINGS *****")
Dim warning As String
For Each warning _
In warnings
Console.WriteLine( _
warning)
Next
Console.WriteLine( _
"END WARNINGS *****")
End If
Catch ex As Exception
Console.WriteLine(ex)
Throw
End Try
mHaveCheckedStore _
= True
End If
End Sub
Public Shared Sub ShutDownAddIn( _
ByVal addIn As T)
Try
For Each pair In _
mLoadedAddIns
If pair.Value.Equals( _
addIn) Then
mLoadedAddIns.Remove( _
pair.Key)
End If
Next
Dim controller = _
AddInController. _
GetAddInController( _
addIn)
controller.Shutdown()
Catch ex As Exception
Throw New _
ArgumentException( _
"Can't shutdown AddIn", _
ex)
End Try
End Sub
End Class