modStartup.bas v2

' ============================================================
' Copyright (c) 2025-2026 Peter Bryant (Corylus Business Systems)
'                    and  Andrew Richards (The IT Service Ltd)
' Part of VBAuth - https://vbauth.com
' Licensed under the MIT Licence - see LICENCE.txt
' This copyright notice must not be removed or altered.
' Module version 2, for VBAuth 1.0.0.3
' ============================================================

Option Compare Database
Option Explicit

' ============================================================
' install location
' the invariant part of the path is held here once, and the drive
' comes from the environment, so a machine with Windows on a drive
' other than C is named correctly in every message
' ============================================================
Private Const VBAUTH_FOLDER_SUBPATH As String = "\VBAuth\Graph Authenticator"
Private Const VBAUTH_DLL_NAME       As String = "VBAuth.dll"

Private mstrDLLPath As String   ' worked out on first use and kept for the session

' ============================================================
' VBAuthDLLPath
' gives the full path the installer puts VBAuth.dll at, worked
' out from the environment rather than assumed
' returns the path whether or not the file is actually there, so
' the caller can quote it in a message as well as test for it
' ============================================================
Public Function VBAuthDLLPath() As String

    'read the environment once and keep the answer - the install location cannot change
    'while Access is running, and this is called from several places
    If mstrDLLPath = "" Then
        'ProgramW6432 rather than ProgramFiles, because from 32-bit Office on 64-bit
        'Windows ProgramFiles returns the (x86) folder while the DLL installs to the real
        'one - the case this does not cover is 32-bit Windows, where ProgramW6432 is
        'undefined, and which Windows 11 no longer offers
        mstrDLLPath = Environ$("ProgramW6432") & VBAUTH_FOLDER_SUBPATH & "\" & VBAUTH_DLL_NAME
    End If

    VBAuthDLLPath = mstrDLLPath

End Function

' ============================================================
' VBAuthDLLIsInstalled
' reports whether the DLL is on disk where the installer puts it,
' which is what separates "VBAuth was never installed" from
' "VBAuth is installed but was never COM-registered" - two faults
' that look identical to the user and have different cures
' returns True when the file is found, False when it is not
'
' one Dir is enough, and a folder-first test is not needed
' Dir given a literal file name returns an empty string when the
' file is absent AND when the folder holding it is absent, so the
' single call covers both - tested 11/09/2026
' error 76, path not found, is the wildcard case - Dir("...\*.dll")
' against a folder that does not exist - which is not what is
' being done here
' ============================================================
Public Function VBAuthDLLIsInstalled() As Boolean

    VBAuthDLLIsInstalled = (Len(Dir(VBAuthDLLPath())) > 0)

End Function

' ============================================================
' CheckVBAuthInstallation
' proves VBAuth is referenced, resolvable and able to instantiate,
' so that a later Graph call fails on data rather than on plumbing
' returns False as soon as any one of the checks fails, having
' first told the user which one it was and how to correct it
'
' the whole function is a series of gates - each stage asks "are
' we still all right", and bails out with a message if not, so the
' Exit Function calls below are the shape of the procedure rather
' than shortcuts out of it
' the two Exit For calls are a deliberate exception to the usual
' rule about loops running to completion: there is only ever one
' VBAuth reference, and stopping at it reads more plainly than a
' guarded assignment would
'
' when each check can actually fire
' check 4 is a live guard - a DLL that is present and referenced but
' never COM-registered is caught here at startup, as intended
' checks 1 and 2 cannot fire at startup and are not meant to.  a
' broken reference stops the whole VBA project compiling, so
' frmStartup never runs, this form never opens and nothing here is
' called - Access shows its own missing-reference dialog instead
' they earn their place as a manual diagnostic: run
' CheckVBAuthInstallation from the Immediate Window once Access has
' reported a broken reference, and it names the referenced path and
' the path to re-add
' the reference exists at all because AcquireBearerToken binds early,
' which is deliberate - IntelliSense and compile-time checking are
' worth more in a demo than immunity from the compile cascade
'
' WARNING - if that early binding is ever removed and the database
' goes fully late bound, checks 1 and 2 must be deleted along with
' it.  with no reference present check 1 finds nothing and reports
' "VBAuth is not referenced in this database" on a perfectly healthy
' installation, every time
' check 4, the CreateObject probe, is the only one that still means
' anything in a late-bound database, and on its own it is enough
' ============================================================
Public Function CheckVBAuthInstallation() As Boolean
Dim objTest         As Object       ' probe instance proving COM registration, released before exit
Dim strExpectedPath As String       ' where the installer puts the DLL, quoted back in every message
Dim strActualPath   As String       ' path this database's reference points at, empty when there is none
Dim ref             As Reference    ' loop cursor over the project's references, nothing to release

    'assume failure, so every gate below only has to bail out rather than restate it
    CheckVBAuthInstallation = False

    'worked out from the environment rather than hardcoded, so the messages below name the
    'drive this machine actually uses
    strExpectedPath = VBAuthDLLPath()

    ' --- Check 1: Is the reference present in this database? ---
    'stop at the first VBAuth reference, since there is only ever one
    For Each ref In Application.References
        If InStr(1, ref.Name, "VBAuth", vbTextCompare) > 0 Then
            strActualPath = ref.FullPath
            Exit For
        End If
    Next ref

    If strActualPath = "" Then
        'no reference at all, so nothing further can be tested until the user adds one
        MsgBox "VBAuth is not referenced in this database." & vbCrLf & vbCrLf & _
               "Go to VBE > Tools > References and add:" & vbCrLf & _
               strExpectedPath, _
               vbCritical, "VBAuth Not Referenced"
        Exit Function
    End If

    ' --- Check 2: Is the reference broken? ---
    'we have a path, broken or not - now to check the path and whether the reference
    'still resolves to a type library on disk
    For Each ref In Application.References
        If InStr(1, ref.Name, "VBAuth", vbTextCompare) > 0 Then
            'the reference survives but the type library behind it does not, so re-adding
            'it is the fix rather than reinstalling
            If ref.IsBroken Then
                MsgBox "The VBAuth reference is broken." & vbCrLf & vbCrLf & _
                       "Referenced path:" & vbCrLf & strActualPath & vbCrLf & vbCrLf & _
                       "Ensure VBAuth is installed and re-add the reference to:" & vbCrLf & _
                       strExpectedPath, _
                       vbCritical, "VBAuth Reference Broken"
                Exit Function
            End If
            Exit For
        End If
    Next ref

'    ' --- Check 3: Is the referenced DLL the right bitness? ---
'    NB removed to action earlier

    ' --- Check 4: Can we actually instantiate it via COM? ---
    'a reference that resolves still proves nothing until the class actually loads, and
    'failing to load is expected here, so the error is swallowed and tested for instead
    On Error Resume Next
    Set objTest = CreateObject("VBAuth.GraphAuthenticator")
    On Error GoTo 0

    If objTest Is Nothing Then
        'the DLL is on disk and referenced but not COM-registered - the RegAsm that has to
        'be run depends on the bitness of the Office install, not on where the DLL sits,
        'which is why this is the only place bitness still matters
        #If Win64 Then
            MsgBox "VBAuth reference and path look correct but the DLL could not be loaded." & vbCrLf & vbCrLf & _
                   "The DLL may not be registered. Run the following from an admin command prompt:" & vbCrLf & vbCrLf & _
                   "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe " & """" & strExpectedPath & """" & " /codebase /tlb", _
                   vbCritical, "VBAuth COM Registration Missing"
        #Else
            MsgBox "VBAuth reference and path look correct but the DLL could not be loaded." & vbCrLf & vbCrLf & _
                   "The DLL may not be registered. Run the following from an admin command prompt:" & vbCrLf & vbCrLf & _
                   "C:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe " & """" & strExpectedPath & """" & " /codebase /tlb", _
                   vbCritical, "VBAuth COM Registration Missing"
        #End If
        Exit Function
    End If

    'release the probe instance before reporting success
    Set objTest = Nothing
    CheckVBAuthInstallation = True

End Function

' ============================================================
' IsSetupRequired
' reports whether first-run setup still has to be completed, by
' testing whether AppID 1 has been given its ClientID and TenantID
' returns True when setup is outstanding, and also True on any
' database error, so that a failure to read sends the user to the
' wizard rather than into a feature that cannot authenticate
' ============================================================
Public Function IsSetupRequired() As Boolean
Dim db  As DAO.Database     ' current database, closed and released in the cleanup block
Dim rs  As DAO.Recordset    ' AppID 1 credentials, closed and released in the cleanup block

    'assume setup is complete and let the tests below overturn it
    IsSetupRequired = False

    On Error GoTo ErrHandler

    Set db = CurrentDb
    Set rs = db.OpenRecordset( _
        "SELECT ClientID, TenantID FROM lclVBAuthAdmin WHERE AppID = 1", _
        dbOpenSnapshot)

    If rs.EOF Then
        'the AppID 1 row is missing entirely, so there is nothing to have configured
        IsSetupRequired = True
        GoTo CloseOut
    End If

    'a row that exists but has either credential blank is a part-finished setup
    If Trim(Nz(rs!ClientID, "")) = "" Or Trim(Nz(rs!TenantID, "")) = "" Then
        IsSetupRequired = True
    End If

CloseOut:
    'close the recordset before releasing it
    If Not rs Is Nothing Then
        rs.Close
    End If
    'release the recordset
    Set rs = Nothing
    'close the database handle before releasing it
    If Not db Is Nothing Then
        db.Close
    End If
    'release the database handle
    Set db = Nothing
    Exit Function

ErrHandler:
    'any read failure is treated as setup outstanding, then falls through to the same cleanup
    IsSetupRequired = True
    Resume CloseOut

End Function
Updated on September 11, 2026