Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions mcp-server/AccUnit.McpServer/AccessInstanceOwnership.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Collections.Generic;

namespace AccessCodeLib.AccUnit.McpServer
{
/// <summary>
/// Decides whether the Access instance returned by COM was started by this server.
/// While another automation (e.g. another MCP server) uses Access, COM may hand out that running instance
/// instead of starting a new one; the server must neither use nor quit it.
/// </summary>
public static class AccessInstanceOwnership
{
public const string ExistingInstanceMessage =
"Access returned an instance that was already running (probably used by another automation), " +
"so the database was not opened. Try again when the other Access automation has finished.";

/// <param name="processId">Process of the instance returned by COM.</param>
/// <param name="processIdsBeforeStart">Access processes that were running before the instance was requested.</param>
public static bool IsStartedByServer(int processId, ICollection<int> processIdsBeforeStart)
{
return !processIdsBeforeStart.Contains(processId);
}
}
}
60 changes: 58 additions & 2 deletions mcp-server/AccUnit.McpServer/AccessSession.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Access = Microsoft.Office.Interop.Access;
Expand All @@ -17,6 +18,10 @@ public sealed class AccessSession : IDisposable
private const bool OpenExclusive = true;
private const string AllowBypassKeyPropertyName = "AllowBypassKey";
private const int DaoPropertyNotFoundHResult = unchecked((int)0x800A0CC6); // DAO error 3270
private const string AccessProcessName = "MSACCESS";
private const string DatabaseNotOpenedMessage =
"Access did not open the database, although it reported no error. This can happen while another Access automation " +
"is running; the Access instance of this server was closed. Try again.";

private readonly StaComDispatcher _dispatcher;
private Access.Application _application;
Expand Down Expand Up @@ -90,6 +95,14 @@ private SessionStatus OpenOnStaThread(string fullPath, bool bypassStartup)
QuitAccess();
throw new DatabaseSessionException("Access could not open the database: " + ex.Message, ex);
}

// Seen while another Access automation was running: OpenCurrentDatabase returned without error,
// but no database was open (CurrentProject "closed or doesn't exist").
if (!HasOpenDatabase())
{
QuitAccess();
throw new DatabaseSessionException(DatabaseNotOpenedMessage);
}
_databasePath = fullPath;
_bypassStartup = bypassStartup;

Expand All @@ -99,6 +112,24 @@ private SessionStatus OpenOnStaThread(string fullPath, bool bypassStartup)
return status;
}

private bool HasOpenDatabase()
{
Access._CurrentProject currentProject = null;
try
{
currentProject = _application.CurrentProject;
return !string.IsNullOrEmpty(currentProject.FullName);
}
catch (COMException)
{
return false;
}
finally
{
ReleaseComObject(currentProject);
}
}

private void OpenCurrentDatabase(string fullPath, bool pressShiftKey)
{
using (pressShiftKey ? new ShiftKeyScope() : null)
Expand Down Expand Up @@ -152,10 +183,35 @@ private static void ReleaseComObject(object comObject)

private void StartAccess()
{
_application = new Access.Application();
var processIdsBeforeStart = GetAccessProcessIds();
var application = new Access.Application();
var process = GetProcess(application);

if (!AccessInstanceOwnership.IsStartedByServer(process.Id, processIdsBeforeStart))
{
// COM handed out a running instance (e.g. of another automation): release it, never quit or kill it.
process.Dispose();
Marshal.FinalReleaseComObject(application);
throw new DatabaseSessionException(AccessInstanceOwnership.ExistingInstanceMessage);
}

_application = application;
_accessProcess = process;
// Visible, so the user can see what happens and dialogs do not block unnoticed.
_application.Visible = true;
_accessProcess = GetProcess(_application);
}

private static HashSet<int> GetAccessProcessIds()
{
var processIds = new HashSet<int>();
foreach (var process in Process.GetProcessesByName(AccessProcessName))
{
using (process)
{
processIds.Add(process.Id);
}
}
return processIds;
}

private CloseResult CloseOnStaThread()
Expand Down
4 changes: 3 additions & 1 deletion mcp-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@ The finished test class is added through the source files (e.g. msaccess-vcs imp
## Behavior and changes to the database

- **One database at a time**, opened exclusively in an Access instance started by the server; the server never uses
an Access instance it did not start. The instance is visible.
an Access instance it did not start. The instance is visible. If COM hands out an Access instance that was already
running (e.g. while another Access automation runs), `accunit_open` fails and leaves that instance untouched.
If Access reports no error but has no database open afterwards, the server quits its own instance and reports it.
- **Startup code** (AutoExec, startup form) is skipped by default like opening with the Shift key held down.
This does not work if the database sets `AllowBypassKey = False`; the result then contains a warning.
- **`accunit_run_tests`** inserts the module `AccUnit_Factory` if it is missing (test classes use `Assert`/`Iz` from it)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using NUnit.Framework;

namespace AccessCodeLib.AccUnit.McpServer.Tests
{
public class AccessInstanceOwnershipTests
{
[Test]
public void IsStartedByServer_NewProcess_IsTrue()
{
Assert.That(AccessInstanceOwnership.IsStartedByServer(300, new[] { 100, 200 }), Is.True);
}

[Test]
public void IsStartedByServer_NoAccessRunningBefore_IsTrue()
{
Assert.That(AccessInstanceOwnership.IsStartedByServer(300, new int[0]), Is.True);
}

[Test]
public void IsStartedByServer_ProcessRunningBefore_IsFalse()
{
Assert.That(AccessInstanceOwnership.IsStartedByServer(200, new[] { 100, 200 }), Is.False);
}
}
}