Monday 20 March 2017

State loss proof storage

So just perusing the type libraries on my computer found using previous post.  I can see I made a C# assembly that allows the storing of VBA variables that would survive a state loss.  Then cross checking against SO I posted the code but then Florent B. posted a better version that needs no assembly.

It uses the default .Net application domain as a storage container. The code is a gem and worth repeating here



    Sub Usage()
        Dim dict As Object
        Set dict = GetPersistentDictionary()
    End Sub


    
    Public Function GetPersistentDictionary() As Object
        ' References:
        '  mscorlib.dll
        '  Common Language Runtime Execution Engine
        
        Const name = "weak-data"
        Static dict As Object
        
        If dict Is Nothing Then
          Dim host As New mscoree.CorRuntimeHost
          Dim domain As mscorlib.AppDomain
          host.Start
          host.GetDefaultDomain domain
          
          If IsObject(domain.GetData(name)) Then
            Set dict = domain.GetData(name)
          Else
            Set dict = CreateObject("Scripting.Dictionary")
            domain.SetData name, dict
          End If
        End If
        
        Set GetPersistentDictionary = dict
    End Function


1 comment: