Browse Source

Refactor for AxonASP: SQLite/G3DB data layer, generators, JSON API, pristine starter

Run on AxonASP (Go-based Classic ASP runtime) in Docker instead of IIS/Access.

Framework
- DAL/Database_Class on native G3DB (SQLite); parameterized queries, paging, transactions
- Plain-ASP Router_Class replaces the WSC; rewrite rule + __route front controller
- CSRF helper fixed; G3CRYPTO for bcrypt and UUIDs
- Removed code replaced by natives: lib.json, lib.Upload, lib.CDOEmail,
  lib.ad.auth, databaseConnection (Access)
- core/lib.JsonLite.asp: pure-VBScript JSON reader/encoder (G3JSON.Parse and G3DB
  interfere under the HTTP server)

Tooling (run via axonasp-cli in the container)
- scripts/gen.cmd: migration, repo, controller, api generators (api writes the
  controller, routes, whitelist, includes, OpenAPI spec and .http file)
- scripts/migrate.cmd + migrator that reports real errors and rolls back
- Swagger UI at /api/docs, one dropdown entry per public/api/*.openapi.json

Cleanup
- Removed sample modules, legacy IIS/Access/aspunit files and generated docs;
  db/migrations starts empty, app.sqlite is git-ignored
- README rewritten for AxonASP/Docker

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
tags/v2.0^0
Daniel Covington 1 day ago
parent
commit
541a20f8e0
100 changed files with 2509 additions and 10305 deletions
  1. +4
    -1
      .gitignore
  2. +38
    -74
      README.md
  3. +0
    -185
      TESTING.md
  4. +29
    -0
      app/controllers/DocsController.asp
  5. +1
    -1
      app/controllers/ErrorController.asp
  6. +2
    -1
      app/controllers/autoload_controllers.asp
  7. +1
    -0
      app/models/autoload_models.asp
  8. +39
    -0
      app/views/Docs/index.asp
  9. +5
    -7
      app/views/shared/header.asp
  10. +0
    -1030
      applicationhost.config
  11. +19
    -23
      core/autoload_core.asp
  12. +0
    -127
      core/databaseConnection.asp
  13. +36
    -20
      core/helpers.asp
  14. +0
    -155
      core/lib.CDOEmail.asp
  15. +3
    -3
      core/lib.Collections.asp
  16. +1
    -0
      core/lib.ControllerRegistry.asp
  17. +188
    -87
      core/lib.Data.asp
  18. +3
    -3
      core/lib.Flash.asp
  19. +15
    -7
      core/lib.HTML.Security.asp
  20. +321
    -0
      core/lib.JsonLite.asp
  21. +78
    -81
      core/lib.Migrations.asp
  22. +144
    -0
      core/lib.Router.asp
  23. +0
    -405
      core/lib.Upload.asp
  24. +0
    -52
      core/lib.ad.auth.asp
  25. +25
    -37
      core/lib.crypto.helper.asp
  26. +0
    -284
      core/lib.json.asp
  27. +6
    -5
      core/mvc.asp
  28. +0
    -0
      db/migrations/.gitkeep
  29. +0
    -23
      db/migrations/20260324110000_add_do_not_call_fields_to_households.asp
  30. BIN
      db/webdata.accdb
  31. +0
    -1543
      docs/AGENTS.md
  32. +0
    -994
      docs/CLAUDE.md
  33. BIN
      docs/Windows scripting secrets.pdf
  34. +0
    -63
      docs/api-contracts-mvc-starter.md
  35. +0
    -34
      docs/architecture-patterns.md
  36. +0
    -81
      docs/architecture.md
  37. +0
    -63
      docs/component-inventory.md
  38. +0
    -46
      docs/comprehensive-analysis-mvc-starter.md
  39. +0
    -11
      docs/critical-folders-summary.md
  40. +0
    -42
      docs/data-models-mvc-starter.md
  41. +0
    -82
      docs/deployment-configuration.md
  42. +0
    -134
      docs/deployment-guide.md
  43. +0
    -55
      docs/development-guide.md
  44. +0
    -59
      docs/development-instructions.md
  45. +0
    -46
      docs/existing-documentation-inventory.md
  46. +0
    -12
      docs/ideas.md
  47. +0
    -71
      docs/index.md
  48. +0
    -70
      docs/project-overview.md
  49. +0
    -26
      docs/project-parts.json
  50. +0
    -1
      docs/project-scan-report.json
  51. +0
    -38
      docs/project-structure.md
  52. +0
    -100
      docs/source-tree-analysis.md
  53. +0
    -26
      docs/state-management-patterns-mvc-starter.md
  54. +0
    -28
      docs/technology-stack.md
  55. +0
    -50
      docs/ui-component-inventory-mvc-starter.md
  56. +0
    -13
      docs/user-provided-context.md
  57. +7
    -4
      public/Default.asp
  58. +7
    -8
      public/web.config
  59. +0
    -4
      run_site.cmd
  60. +611
    -0
      scripts/GenerateApi.vbs
  61. +215
    -509
      scripts/GenerateRepo.vbs
  62. +33
    -0
      scripts/_cli.vbs
  63. +0
    -320
      scripts/deploy-iis-git.ps1
  64. +43
    -0
      scripts/gen.cmd
  65. BIN
      scripts/generateController.vbs
  66. +13
    -9
      scripts/generateMigration.vbs
  67. +0
    -476
      scripts/install-iis-release.ps1
  68. +27
    -0
      scripts/migrate.asp
  69. +6
    -0
      scripts/migrate.cmd
  70. +0
    -90
      scripts/migrate_isbusiness_to_households.vbs
  71. +0
    -614
      scripts/runMigrations.vbs
  72. +352
    -0
      scripts/templates/Api.tpl.asp
  73. +26
    -0
      scripts/templates/POBO.tpl.asp
  74. +211
    -0
      scripts/templates/Repository.tpl.asp
  75. +0
    -190
      tests/PlainRunnerTheme.asp
  76. +0
    -21
      tests/aspunit/LICENSE-MIT
  77. +0
    -12
      tests/aspunit/Lib/ASPUnit.asp
  78. +0
    -123
      tests/aspunit/Lib/classes/ASPUnitJSONResponder.asp
  79. +0
    -104
      tests/aspunit/Lib/classes/ASPUnitLibrary.asp
  80. +0
    -174
      tests/aspunit/Lib/classes/ASPUnitRunner.asp
  81. +0
    -258
      tests/aspunit/Lib/classes/ASPUnitTester.asp
  82. +0
    -395
      tests/aspunit/Lib/classes/ASPUnitUIModern.asp
  83. +0
    -49
      tests/bootstrap.asp
  84. +0
    -43
      tests/component/TestHomeController.asp
  85. +0
    -20
      tests/component/web.config
  86. +0
    -41
      tests/integration/TestConfigSettings.asp
  87. +0
    -80
      tests/integration/TestMvcDispatch.asp
  88. +0
    -52
      tests/integration/TestRenderedOutput.asp
  89. +0
    -51
      tests/integration/TestRoutes.asp
  90. +0
    -69
      tests/integration/TestSharedLayout.asp
  91. +0
    -20
      tests/integration/web.config
  92. +0
    -9
      tests/run-all.asp
  93. +0
    -21
      tests/run-tests.cmd
  94. +0
    -48
      tests/support/HttpCaptureHelpers.asp
  95. +0
    -25
      tests/sync-webconfigs.vbs
  96. +0
    -14
      tests/test-manifest.asp
  97. +0
    -48
      tests/unit/TestControllerRegistry.asp
  98. +0
    -65
      tests/unit/TestHelpers.asp
  99. +0
    -20
      tests/unit/web.config
  100. +0
    -20
      tests/web.config

+ 4
- 1
.gitignore View File

@@ -1,4 +1,7 @@
/_bmad
/_bmad*
/.agents
/.github
/.github
# SQLite database (created by the first migration run; never commit data)
/db/*.sqlite
/db/*.sqlite-*

+ 38
- 74
README.md View File

@@ -1,96 +1,60 @@
# RouteKit Classic ASP - MVC Starter
# RouteKit Classic ASP - MVC Starter (AxonASP)

A clean starting point for building Classic ASP applications with the RouteKit MVC framework.
A clean starting point for Classic ASP applications on **[AxonASP](https://github.com/guimaraeslucas/axonasp)**, a Go-based Classic ASP / VBScript 5.8 runtime. It ships a small MVC framework (router, controllers, views, flash messages, CSRF helper), a SQLite data layer on the native `G3DB` library, migrations, and code generators for tables, repositories, HTML controllers and JSON APIs.

## Quick Setup
No sample modules are included: the first table you add is yours.

1. Copy this folder to your IIS server
2. Point your IIS site root to the `public/` folder
3. Update `public/web.config`:
- Set `ConnectionString` to your database path
- Set `ErrorLogPath` if you want file logging
4. Ensure the IIS URL Rewrite module is installed
5. Browse to `http://localhost/` — you should see the welcome page
## Quick start

## Project Structure
Requires Docker.

```
MVC-Starter/
public/ # IIS ROOT - point your IIS site here
Default.asp # Front controller (entry point)
web.config # IIS config, routes, connection strings
core/ # Framework core (do not modify)
autoload_core.asp # Loads all core libraries
router.wsc # Route matching engine
mvc.asp # MVC dispatcher
lib.*.asp # Core libraries
app/
controllers/ # Your controllers go here
views/ # Your views go here
shared/ # Shared layout (header, footer)
models/ # POBOs go here
repositories/ # Repository classes go here
db/
migrations/ # Database migrations
webdata.accdb # Access database
scripts/ # Code generators
generateController.vbs
generateMigration.vbs
GenerateRepo.vbs
runMigrations.vbs
cd deploy
docker compose up -d --build
```

## Adding a New Feature
Open http://localhost:8801. The compose file mounts this folder into the container and serves `public/`.

### 1. Generate a migration
```bash
cscript //nologo scripts\generateMigration.vbs create_my_table
```
After editing ASP code, restart the container so cached scripts are recompiled: `docker restart axonasp`.

### 2. Generate POBO and Repository
```bash
cscript //nologo scripts\GenerateRepo.vbs /table:my_table /pk:id
```
Move generated files to `app/models/` and `app/repositories/`.
## Project structure

### 3. Generate a controller
```bash
cscript //nologo scripts\generateController.vbs MyController "Index;Show(id);Create;Store"
```
Move generated file to `app/controllers/`.

### 4. Wire it up
- Register in `core/lib.ControllerRegistry.asp`
- Include in `app/controllers/autoload_controllers.asp`
- Add routes in `public/Default.asp`
- Create views in `app/views/MyController/`

## Included Controllers
public/ web root: Default.asp (front controller + routes), web.config (rewrite, settings)
core/ framework: mvc.asp, router, DAL (G3DB), migrations, JsonLite, helpers, lib.*.asp
app/
controllers/ <Name>Controller.asp (HTML), Api<Name>Controller.asp (JSON), autoload_controllers.asp
models/ POBO_<Table>.asp, <Table>Repository.asp (generated), autoload_models.asp
views/ <Name>/ views; shared/ layout (header, footer); Home, Error, Docs
db/
migrations/ YYYYMMDDHHMMSS_name.asp (Migration_Up / Migration_Down)
app.sqlite created by the first migration run (git-ignored)
scripts/ gen.cmd (generators), migrate.cmd, templates/
(deploy/ with the Dockerfile and docker-compose.yml currently sits next to this folder, outside this git repo)
```

- **HomeController** - Welcome page at `/`
- **ErrorController** - 404 handler at `/404`
## Adding a feature

## Requirements
All commands run from this folder on Windows and execute inside the container through the AxonASP CLI. Run `gen.cmd controller` from PowerShell or cmd (not Git Bash).

- Windows Server with IIS
- Classic ASP enabled
- IIS URL Rewrite module
- Microsoft Access Database Engine (for .accdb support)
1. **Migration**: `scripts\gen.cmd migration create_things_table`, edit `Migration_Up` / `Migration_Down`, then `scripts\migrate.cmd up` (also `status`, `down`).
2. **JSON API** for the table: `scripts\gen.cmd api /table:Things /pk:Id`. This writes the model and repository, `ApiThingsController.asp`, wires the includes, controller whitelist and routes (`/api/things`), and creates `public/api/things.openapi.json` and `api-tests/things.http`.
3. **HTML pages**: `scripts\gen.cmd controller Things Index "Show(id)" NewForm Create "Edit(id)" "Update(id)" "Delete(id)"` creates a stub controller and wires it; fill in the actions and add views under `app/views/Things/`.
4. `docker restart axonasp`, then try it.

## Deployment
The Swagger UI at http://localhost:8801/api/docs lists every generated API spec and lets you call the endpoints.

Production deployment owns an isolated IIS site and app pool; it never targets, adopts, or copies configuration from another site. Defaults are `SiteName=AspClassicUnifiedFramework`, `AppPoolName=AspClassicUnifiedFramework`, `DeployRoot=D:\Deployments\AspClassicUnifiedFramework`, and HTTP binding `100.97.39.23:8085` with an empty host header. Every value is explicitly overridable, while mismatched existing target state fails closed.
## Included

The complete repository is retained in immutable release directories and IIS serves only each release's `public/` directory. First deployment initializes shared configuration from packaged `public/web.config` unless `-InitialWebConfigPath` is supplied. The target site/app pool is created only after the staged release validates; Classic ASP parent paths are enabled only at that site's location. Failure cleanup is limited to target resources created by the current invocation, or restoration of the prior valid target state. Migrations remain disabled by default.
- **HomeController**: welcome page at `/`
- **ErrorController**: 404 page
- **DocsController**: Swagger UI at `/api/docs`

Run `scripts/deploy-iis-git.ps1 -LocalPreflightOnly` for local source/XML/package/safety validation with no network access. When host access is permitted, run `-PreflightOnly` for the complete check: it streams the installer without writing remote files and validates IIS features/modules, binding and shared-pool conflicts, drive/path, names, and target state without requiring the target to exist or making IIS/deployment changes. `-HostPreflightOnly` and `-RemotePreflightOnly` remain aliases. Gitea 1.11.4 has no Gitea Actions, so use a trusted external worker or operator workstation. See [docs/deployment-guide.md](docs/deployment-guide.md) and [docs/deployment-configuration.md](docs/deployment-configuration.md).
## Configuration

## Testing
- `public/web.config`: `ConnectionString` (`sqlite:/opt/axonasp/site/db/app.sqlite`), environment and UI settings.
- `deploy/app/config/axonasp.toml`: server settings; any key can be overridden with an environment variable (see `deploy/docker-compose.yml`).

This repo now includes a dev-only `aspunit` harness under `tests/`. It is intentionally separate from the production app rooted at `public/`.
## Rules for developers and AI agents

- Configure a separate IIS application rooted at `tests/`
- Ensure Classic ASP parent paths are enabled for that IIS app
- If you change `tests/web.config`, refresh the nested test-folder copies with `cscript //nologo tests\sync-webconfigs.vbs`
- Open `run-all.asp` inside that IIS app to execute the test suite
- See `TESTING.md` for setup, manifest registration, and extension guidance
See [AGENTS.md](../AGENTS.md) at the repository root: language rules, AxonASP quirks verified in this project, security checklist and working rules.

+ 0
- 185
TESTING.md View File

@@ -1,185 +0,0 @@
# Testing MVC-Starter

This project now supports a dev-only Classic ASP test harness built with `aspunit`.

## Scope

- Production app: `public/`
- Dev-only test app: `tests/`
- Test framework: `tests/aspunit/`

The `tests/` IIS application assumes the repository layout keeps `tests/`, `public/`, `core/`, and `app/` as sibling directories.

## File Inventory

| Type | Path | Purpose |
| ---- | ---- | ------- |
| Create | `tests/web.config` | IIS/default-document config for the isolated test app |
| Create | `tests/unit/web.config` | Mirrored config for nested unit pages that load config-aware code |
| Create | `tests/component/web.config` | Mirrored config for nested component pages that load config-aware code |
| Create | `tests/integration/web.config` | Mirrored config for nested integration pages that load config-aware code |
| Create | `tests/sync-webconfigs.vbs` | Utility script to mirror `tests/web.config` into nested test folders |
| Create | `tests/run-tests.cmd` | Windows helper to sync configs and open the test runner URL |
| Create | `tests/bootstrap.asp` | Shared test bootstrap and runtime reset helpers |
| Create | `tests/PlainRunnerTheme.asp` | Local runner theme that removes CDN dependence from the test UI |
| Create | `tests/support/HttpCaptureHelpers.asp` | Shared HTTP capture helpers for rendered-page assertions |
| Create | `tests/test-manifest.asp` | Single source of truth for registered test pages |
| Create | `tests/run-all.asp` | Browser runner that aggregates all test pages |
| Vendor | `tests/aspunit/Lib/*` | Upstream aspunit framework files |
| Vendor | `tests/aspunit/LICENSE-MIT` | Upstream aspunit license for vendored third-party code |
| Create | `tests/unit/TestHelpers.asp` | Deterministic helper-function unit tests |
| Create | `tests/unit/TestControllerRegistry.asp` | Controller whitelist/format unit tests |
| Create | `tests/component/TestHomeController.asp` | Controlled component-level controller test |
| Create | `tests/integration/TestMvcDispatch.asp` | Narrow router/dispatch smoke test |
| Create | `tests/integration/TestRoutes.asp` | Route-helper/config integration coverage |
| Create | `tests/integration/TestConfigSettings.asp` | Nested config and fallback behavior coverage |
| Create | `tests/integration/TestRenderedOutput.asp` | Production-page output assertions through safe HTTP capture |
| Create | `tests/integration/TestSharedLayout.asp` | Shared header/footer/layout assertions against rendered production pages |
| Reference | `public/web.config` | Source of mirrored config keys for the test app |
| Reference | `core/helpers.asp` | Helper functions and config-loading behavior under test |
| Reference | `core/mvc.asp` | Dispatcher behavior used by the smoke test |
| Reference | `core/lib.ControllerRegistry.asp` | Whitelist behavior under test |
| Verify | `public/` site | Confirm production app exposes no test routes/pages |

## IIS Setup

1. Keep the existing production IIS app rooted at `public/`.
2. Create a separate development-only IIS application rooted at `tests/`.
3. Enable Classic ASP for that IIS app.
4. Ensure parent paths are allowed for the `tests/` app. This repo ships `tests/web.config` with `enableParentPaths="true"` because the bootstrap and integration pages include sibling files from `../core/` and `../app/`.
5. Browse to the `tests/` app root or directly to `run-all.asp`.
6. If you change `tests/web.config`, run `cscript //nologo tests\sync-webconfigs.vbs` to refresh the nested copies used by the unit, component, and integration pages.
7. If your production app is not served from the same host root as the `tests/` app, set `ProductionAppBaseUrl` in `tests/web.config` and re-run the sync script so rendered-output tests know where to send HTTP requests.
Example: `http://localhost/` for a root site, or `http://localhost/MyClassicApp/` for a virtual-directory app.
8. To sync configs and open the suite in one step on Windows, run `tests\run-tests.cmd` with an optional runner URL argument.

Example layout:

- Production: `http://localhost/`
- Tests: `http://localhost/tests-dev/`

## How It Works

- `tests/run-all.asp` includes the aspunit library and the manifest.
- `tests/run-all.asp` also applies `PlainRunnerTheme.asp`, a local runner theme that avoids the upstream CDN dependency in aspunit’s default UI.
- `tests/test-manifest.asp` explicitly registers each test page.
- `tests/bootstrap.asp` provides the shared runtime setup:
- helper/config access
- controller registry access
- router reset
- `tests/support/HttpCaptureHelpers.asp` provides safe HTTP-based page capture for rendered output assertions against the production app.

The integration test page includes `core/mvc.asp` directly because that is the only first-wave test that needs dispatcher behavior.

Because `GetAppSetting()` uses `Server.MapPath("web.config")`, nested test folders also need a mirrored `web.config` alongside the executing test pages that rely on config-aware runtime files. Use `tests/sync-webconfigs.vbs` after changing `tests/web.config`.

The manifest is manual by design. There is no filesystem auto-discovery.

## Running Tests

Open the browser runner:

Browse to `run-all.asp` within the `tests/` IIS application, for example:

```text
http://localhost/tests-dev/run-all.asp
```

aspunit renders a UI in runner mode and loads each registered page with `?task=test` behind the scenes.

On Windows you can also use:

```bat
tests\run-tests.cmd
```

Or with an explicit runner URL:

```bat
tests\run-tests.cmd http://localhost:8085/run-all.asp
```

## Adding a New Test Page

1. Choose the right folder:
- `tests/unit/` for deterministic helper or registry tests
- `tests/component/` for direct controller/object tests with controlled setup
- `tests/integration/` for narrow runtime smoke coverage, config behavior, or rendered-page capture
- shared layout assertions belong here too, because they verify rendered production responses rather than isolated helper behavior
2. Create a new `.asp` file that:
- includes `../aspunit/Lib/ASPUnit.asp`
- includes `../bootstrap.asp`
- registers one or more modules with `ASPUnit.AddModule(...)`
- calls `ASPUnit.Run()`
3. Add the page path to `tests/test-manifest.asp`.
4. Reload `run-all.asp`.

## First-Pass Isolation Policy

- Unit tests should avoid mutating globals.
- Registry tests should inspect current behavior, not expand the production whitelist.
- Component tests should reset touched singleton/controller state in setup/teardown.
- Dispatch smoke tests should initialize fresh route state before each run.

## What Not To Unit Test

- Full rendered page markup for shared-layout pages unless you add reliable output-capture support.
- Production IIS rewrite behavior from `public/`.
- Broad end-to-end request flows through the production site root.
- Config-dependent behavior that requires machine-specific production values unless you first mirror safe test values into `tests/web.config`.
- Internet access as a requirement for the runner UI. The local theme removes the upstream CDN dependency for first-wave execution.

## Validation Checklist

- `run-all.asp` loads in the separate `tests/` IIS app.
- All manifest pages appear in the runner.
- Helper, registry, component, and integration suites all execute.
- Route-helper/config integration assertions execute from the same isolated IIS app.
- Rendered-page capture assertions can verify production HTML and status codes without polluting aspunit JSON responses.
- Shared layout assertions can verify navbar, asset links, titles, and footer script presence across production-rendered pages.
- Re-running the suite produces stable results.
- The production site under `public/` still exposes no test runner pages or test routes.

## Deployment verification gate

Before a production release:

1. Run the full ASPUnit suite in the isolated development IIS application.
2. Parse every repository `web.config` as XML.
3. Parse both deployment scripts with the Windows PowerShell parser on a Windows CI worker.
4. From a clean standalone checkout of the approved `master` branch, run the local/controller preflight:

```powershell
.\scripts\deploy-iis-git.ps1 -LocalPreflightOnly
```

This validates source provenance, required files, `public/web.config` XML, package creation/extraction, release layout, and package safety without SSH/SCP or host changes.
5. When host connectivity is separately permitted, run the complete read-only preflight (the dedicated target need not exist):

```powershell
.\scripts\deploy-iis-git.ps1 -PreflightOnly -RemoteTarget 'webserver-1'
```

It repeats the local/package checks, streams the installer without writing remote files, and validates IIS/Classic ASP and URL Rewrite, binding and shared-pool conflicts, the deployment drive/path, names, and exact existing-target state without changing IIS or the deployment root.
6. For an isolated Windows test deployment, override names/root/port together rather than reusing any existing site:

```powershell
.\scripts\deploy-iis-git.ps1 `
-SiteName 'AspClassicUnifiedFramework-Test' `
-AppPoolName 'AspClassicUnifiedFramework-Test' `
-DeployRoot 'D:\Deployments\AspClassicUnifiedFramework-Test' `
-BindingIpAddress '100.97.39.23' `
-BindingPort 8185 `
-RemoteTarget 'webserver-1'
```

7. Require the installer smoke test. Also induce a smoke-test failure in the isolated test target and verify that only resources created by that invocation are removed, or that an existing valid target's prior path and parent-path value are restored. Verify unrelated sites, pools, and bindings are unchanged.
8. Run production-safe HTTP checks and prove rollback to a prior immutable release. Never expose the `tests/` IIS application in production.

Linux can validate XML and repository safety/source assertions, but cannot prove Windows PowerShell 5.1 parsing, WebAdministration behavior, installed IIS features/modules, binding behavior on the live host, elevation, app-pool identity/ACLs, Access/ACE, SSH transport, cleanup under real IIS failures, or live HTTP responses. Those remain Windows/IIS gates.

## Limitations

- This harness runs only inside IIS/Classic ASP; it is not intended for Linux execution.
- The repo’s production runtime is still configured via `public/web.config`; the test app uses a minimal mirrored config in `tests/web.config`.
- If the narrow bootstrap is not sufficient for future smoke tests, broaden only the test bootstrap first before considering production runtime changes.

+ 29
- 0
app/controllers/DocsController.asp View File

@@ -0,0 +1,29 @@
<%
' DocsController: interactive API docs (Swagger UI) for the JSON API. The spec is public/api/openapi.json.
Class DocsController_Class
Public Property Get useLayout()
useLayout = True
End Property

Public Property Let useLayout(v)
End Property

Public Property Get Title()
Title = "API docs"
End Property

Public Sub Index()
%>
<!--#include file="../views/Docs/index.asp" -->
<%
End Sub
End Class

Dim DocsController_Class__Singleton
Function DocsController()
If IsEmpty(DocsController_Class__Singleton) Then
Set DocsController_Class__Singleton = New DocsController_Class
End If
Set DocsController = DocsController_Class__Singleton
End Function
%>

+ 1
- 1
app/controllers/ErrorController.asp View File

@@ -21,7 +21,7 @@ Class ErrorController_Class
Public Sub NotFound()
Response.Status = "404 Not Found"
%>
<!--#include file="../Views/Error/NotFound.asp" -->
<!--#include file="../views/Error/NotFound.asp" -->
<%
End Sub



+ 2
- 1
app/controllers/autoload_controllers.asp View File

@@ -1,2 +1,3 @@
<!--#include file="HomeController.asp" -->
<!--#include file="ErrorController.asp" -->
<!--#include file="ErrorController.asp" -->
<!--#include file="DocsController.asp" -->

+ 1
- 0
app/models/autoload_models.asp View File

@@ -0,0 +1 @@
<% ' POBO and repository includes are appended here by scripts/gen.cmd (repo | api) %>

+ 39
- 0
app/views/Docs/index.asp View File

@@ -0,0 +1,39 @@
<%
' One Swagger UI dropdown entry per public/api/*.openapi.json (scripts/gen.cmd api writes one per table)
Dim specFso, specFolder, specFile, specUrls, specName
Set specFso = Server.CreateObject("Scripting.FileSystemObject")
specUrls = ""
If specFso.FolderExists(Server.MapPath("/api")) Then
Set specFolder = specFso.GetFolder(Server.MapPath("/api"))
For Each specFile In specFolder.Files
If LCase(Right(specFile.Name, 13)) = ".openapi.json" Then
specName = Left(specFile.Name, Len(specFile.Name) - 13)
If Len(specUrls) > 0 Then
specUrls = specUrls & ","
End If
specUrls = specUrls & "{url:""/api/" & Server.HTMLEncode(specFile.Name) & """,name:""" & Server.HTMLEncode(specName) & """}"
End If
Next
End If
%>
<% If Len(specUrls) = 0 Then %>
<div class="alert alert-info">
No API specs yet. Generate one for a table with <code>scripts\gen.cmd api /table:&lt;Table&gt; /pk:Id</code>
(it writes <code>public/api/&lt;table&gt;.openapi.json</code>), then reload this page.
</div>
<% Else %>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" />
<div id="swagger-ui"></div>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js"></script>
<script>
window.ui = SwaggerUIBundle({
urls: [<%= specUrls %>],
presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
layout: "StandaloneLayout", // the spec dropdown (urls) only works with the standalone layout
dom_id: "#swagger-ui",
deepLinking: true,
tryItOutEnabled: true
});
</script>
<% End If %>

+ 5
- 7
app/views/shared/header.asp View File

@@ -63,15 +63,13 @@ If Len(pageTitle) = 0 Then pageTitle = "Classic ASP Starter Template"
<li class="nav-item">
<a class="nav-link" href="/home">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/api/docs">API</a>
</li>
</ul>

' Right-side area (e.g., user info / login)
' You can wire this up to your auth later.
<ul class="navbar-nav mb-2 mb-lg-0">
' <li class="nav-item">
' <a class="nav-link" href="/login">Login</a>
' </li>
</ul>
<%' Right-side area (e.g., user info / login). Wire this up to your auth later. %>
<ul class="navbar-nav mb-2 mb-lg-0"></ul>
</div>
</div>
</nav>


+ 0
- 1030
applicationhost.config
File diff suppressed because it is too large
View File


+ 19
- 23
core/autoload_core.asp View File

@@ -1,23 +1,19 @@
<!--#include file="../Core/helpers.asp"-->
<!--#include file="../Core/lib.ErrorHandler.asp"-->
<!--#include file="../Core/lib.ControllerRegistry.asp"-->
<!--#include file="../Core/mvc.asp"-->
<!--#include file="../Core/lib.DAL.asp"-->
<!--#include file="../Core/lib.Data.asp"-->
<!--#include file="../Core/lib.Migrations.asp"-->
<% Dim router : Set router = GetObject("script:"& Server.MapPath("../Core/router.wsc") & "") %>
<!--#include file="../Core/lib.collections.asp"-->
<!--#include file="../Core/lib.HTML.asp"-->
<!--#include file="../Core/lib.Routes.asp"-->
<!--#include file="../Core/lib.Flash.asp"-->
<!--#include file="../Core/lib.FormCache.asp"-->
<!--#include file="../Core/lib.HTML.Security.asp"-->
<!--#include file="../Core/lib.AutoMapper.asp"-->
<!--#include file="../Core/lib.CDOEmail.asp"-->
<!--#include file="../Core/lib.Upload.asp"-->
<!--#include file="../Core/lib.json.asp"-->
<!--#include file="../Core/lib.helpers.asp"-->
<!--#include file="../Core/lib.crypto.helper.asp"-->
<!--#include file="../Core/lib.Enumerable.asp"-->
<!--#include file="../Core/lib.ad.auth.asp"-->
<!--#include file="../Core/databaseConnection.asp"-->
<!--#include file="../core/helpers.asp"-->
<!--#include file="../core/lib.ErrorHandler.asp"-->
<!--#include file="../core/lib.ControllerRegistry.asp"-->
<!--#include file="../core/mvc.asp"-->
<!--#include file="../core/lib.DAL.asp"-->
<!--#include file="../core/lib.Data.asp"-->
<!--#include file="../core/lib.Migrations.asp"-->
<!--#include file="../core/lib.Router.asp"-->
<!--#include file="../core/lib.Collections.asp"-->
<!--#include file="../core/lib.HTML.asp"-->
<!--#include file="../core/lib.Routes.asp"-->
<!--#include file="../core/lib.Flash.asp"-->
<!--#include file="../core/lib.FormCache.asp"-->
<!--#include file="../core/lib.HTML.Security.asp"-->
<!--#include file="../core/lib.Automapper.asp"-->
<!--#include file="../core/lib.helpers.asp"-->
<!--#include file="../core/lib.crypto.helper.asp"-->
<!--#include file="../core/lib.Enumerable.asp"-->
<!--#include file="../core/lib.JsonLite.asp"-->

+ 0
- 127
core/databaseConnection.asp View File

@@ -1,127 +0,0 @@
<%
'------------------------------------------------------------------------------
' DatabaseConnection.Class.inc
' A singleton VBScript "factory" for ADODB.Connection to multiple databases
' Enhanced with separate error handling for creation and open operations
'------------------------------------------------------------------------------

' Singleton holder
Dim DatabaseConnection__Singleton
Set DatabaseConnection__Singleton = Nothing

' Factory function
Function DatabaseConnection()
If DatabaseConnection__Singleton Is Nothing Then
Set DatabaseConnection__Singleton = New DatabaseConnection_Class
End If
Set DatabaseConnection = DatabaseConnection__Singleton
End Function

'------------------------------------------------------------------------------
' Class definition
'------------------------------------------------------------------------------
Class DatabaseConnection_Class
Private conn ' holds the ADODB.Connection instance

'----------------------------------------
' Connect to an Access (.mdb/.accdb) file
'----------------------------------------
Public Function ConnectToAccessDatabase(dataSource, provider)
If IsEmpty(provider) Or provider = "" Then
provider = "Microsoft.Jet.OLEDB.4.0"
End If
Dim connStr
connStr = "Provider=" & provider & ";" & _
"Data Source=" & dataSource & ";" & _
"Persist Security Info=False;"
Set ConnectToAccessDatabase = Me.Connect(connStr)
End Function

'----------------------------------------
' Connect to SQL Server
'----------------------------------------
Public Function ConnectToSQLServer(server, database, uid, pwd, useTrusted)
Dim connStr
If useTrusted = True Then
connStr = "Provider=SQLOLEDB;" & _
"Server=" & server & ";" & _
"Database=" & database & ";" & _
"Trusted_Connection=Yes;"
Else
connStr = "Provider=SQLOLEDB;" & _
"Server=" & server & ";" & _
"Database=" & database & ";" & _
"User ID=" & uid & ";" & _
"Password=" & pwd & ";"
End If
Set ConnectToSQLServer = Me.Connect(connStr)
End Function

'----------------------------------------
' Connect via ODBC DSN
'----------------------------------------
Public Function ConnectToODBC(dsnName, uid, pwd)
Dim connStr
connStr = "DSN=" & dsnName & ";"
If Not IsEmpty(uid) Then connStr = connStr & "UID=" & uid & ";"
If Not IsEmpty(pwd) Then connStr = connStr & "PWD=" & pwd & ";"
Set ConnectToODBC = Me.Connect(connStr)
End Function

'----------------------------------------
' Generic Connect: opens and returns an ADODB.Connection
' Includes separate handling for creation and open errors
'----------------------------------------
Public Function Connect(connectionString)
On Error Resume Next

' Dispose previous connection if any
If Not conn Is Nothing Then
conn.Close
Set conn = Nothing
End If

' Create ADO Connection object
Set conn = Server.CreateObject("ADODB.Connection")
If conn Is Nothing Then
Err.Clear
On Error GoTo 0
Err.Raise 50000, _
"DatabaseConnection_Class.Connect", _
"Could not create ADODB.Connection. Ensure ADO is installed and registered."
End If

' Clear any prior errors before opening
Err.Clear

' Open database connection
conn.Open connectionString
If Err.Number <> 0 Then
Dim lastErrNum, lastErrDesc
lastErrNum = Err.Number
lastErrDesc = Err.Description
Err.Clear
On Error GoTo 0
Err.Raise lastErrNum, _
"DatabaseConnection_Class.Connect", _
"Failed to open connection (" & connectionString & _
") - Error " & lastErrNum & ": " & lastErrDesc
End If

On Error GoTo 0
Set Connect = conn
End Function

'----------------------------------------
' Close & clean up
'----------------------------------------
Public Sub Close()
On Error Resume Next
If Not conn Is Nothing Then
conn.Close
Set conn = Nothing
End If
On Error GoTo 0
End Sub
End Class
%>

+ 36
- 20
core/helpers.asp View File

@@ -8,12 +8,9 @@ Function QuoteValue(val)
Case vbString
QuoteValue = "'" & Replace(val, "'", "''") & "'"
Case vbDate
if conn.Provider = "Microsoft.Jet.OLEDB.4.0" or conn.Provider = "Microsoft.ACE.OLEDB.12.0" then
QuoteValue = "#" & FormatDateTime(val, 0) & "#"
else
' SQL Server
QuoteValue = "'" & FormatDateTime(val, 0) & "'"
end if
' SQLite stores dates as ISO-8601 text; other providers get a quoted date string
QuoteValue = "'" & Year(val) & "-" & Right("0" & Month(val), 2) & "-" & Right("0" & Day(val), 2) & _
" " & Right("0" & Hour(val), 2) & ":" & Right("0" & Minute(val), 2) & ":" & Right("0" & Second(val), 2) & "'"
Case vbNull, vbEmpty
QuoteValue = "Null"
Case vbBoolean
@@ -40,7 +37,10 @@ Public Function GetAppSetting(key)

' Load from web.config only if not cached
Set xml = Server.CreateObject("Microsoft.XMLDOM")
xml.Load(Server.MapPath("web.config"))
' web.config is in the web root (public/); the CLI migration runner uses the framework folder as root
Dim cfgPath : cfgPath = Server.MapPath("/web.config")
If Not CreateObject("Scripting.FileSystemObject").FileExists(cfgPath) Then cfgPath = Server.MapPath("/public/web.config")
xml.Load(cfgPath)
Set nodes = xml.selectNodes("//appSettings/add")
For i = 0 To nodes.Length - 1
Set node = nodes.Item(i)
@@ -120,6 +120,7 @@ End Sub
'------------------------------------------------------------------------------
Function TrimQueryParams(rawPath)
Dim posQ, posA, cutPos
rawPath = "" & rawPath

' find the first occurrences of "?" and "&"
posQ = InStr(rawPath, "?")
@@ -127,7 +128,11 @@ Function TrimQueryParams(rawPath)

' determine the earliest cut position (>0)
If posQ > 0 And posA > 0 Then
cutPos = IIf(posQ < posA, posQ, posA)
If posQ < posA Then
cutPos = posQ
Else
cutPos = posA
End If
ElseIf posQ > 0 Then
cutPos = posQ
ElseIf posA > 0 Then
@@ -144,6 +149,21 @@ Function TrimQueryParams(rawPath)
End If
End Function

' Returns the original request path. IIS URL Rewrite supplies HTTP_X_ORIGINAL_URL;
' on other hosts (AxonASP/Linux) fall back to the request URL.
Function GetRequestPath()
Dim p
p = "" & Request.QueryString("__route") ' set by the web.config rewrite rule (AxonASP)
If Len(p) = 0 Then p = "" & Request.ServerVariables("HTTP_X_ORIGINAL_URL")
If Len(p) = 0 Then p = "" & Request.ServerVariables("HTTP_X_REWRITE_URL")
If Len(p) = 0 Then p = "" & Request.ServerVariables("URL")
If Len(p) = 0 Then p = "" & Request.ServerVariables("PATH_INFO")
If Len(p) = 0 Then p = "" & Request.ServerVariables("SCRIPT_NAME")
p = TrimQueryParams(p)
If LCase(p) = "/default.asp" Then p = "/"
GetRequestPath = p
End Function

Sub Destroy(o)
if isobject(o) then
if not o is nothing then
@@ -155,12 +175,7 @@ Sub Destroy(o)
end if
End Sub

'prepends indents
Private Sub puti(v)
put Spaces(m_indent) & v
End Sub

Sub put(v)
Sub puts(v)
Select Case typename(v)
Case "LinkedList_Class" : response.write join(v.TO_Array, ", ")
Case "DynamicArray_Class" : response.write JoinList(v)
@@ -169,13 +184,13 @@ End Sub
End Select
End Sub

Sub put_
put "<br>"
Sub puts_
puts "<br>"
End Sub

Sub putl(v)
put v
put_
puts v
puts_
End Sub
'---------------------------------------------------------------------------------------------------------------------
'Wrapper for Server.HTMLEncode() -- makes it easier on the eyes when reading the HTML code
@@ -233,7 +248,8 @@ Function SurroundStringInArray(arr)
Dim i
For i = LBound(arr) To UBound(arr)
If IsString(arr(i)) Then
arr(i) = """" & arr(i) & """"
' double any embedded quote: the value is spliced into an Execute string, so this prevents code injection
arr(i) = """" & Replace(arr(i), """", """""") & """"
End If
Next
SurroundStringInArray = arr
@@ -497,7 +513,7 @@ End Function

Function Active(controllerName)
On Error Resume Next
If Replace(Lcase(router.Resolve(Request.ServerVariables("REQUEST_METHOD"), TrimQueryParams(Request.ServerVariables("HTTP_X_ORIGINAL_URL")))(0)),"controller","") = LCase(controllerName) Then
If Replace(Lcase(GetRouter().Resolve(Request.ServerVariables("REQUEST_METHOD"), GetRequestPath())(0)),"controller","") = LCase(controllerName) Then
Active = "active"
Else
Active = ""


+ 0
- 155
core/lib.CDOEmail.asp View File

@@ -1,155 +0,0 @@
<%

' Class: CDOEmail
' Handles email creation and sending via CDO in VBScript
Class CDOEmail_Class
' Public properties
Public From
Public Subject
Public Body
Public IsBodyHTML
Public SMTPServer
Public SMTPPort
Public SMTPUsername
Public SMTPPassword
Public SMTPUseSSL

' Private members
Private cfg
Private msg
Private dictRecipients
Private arrAttachments

' Initialize default values and objects
Private Sub Class_Initialize()
' Create CDO configuration and message objects
Set cfg = Server.CreateObject("CDO.Configuration")
Set msg = Server.CreateObject("CDO.Message")

' Default SMTP settings
SMTPServer = "localhost"
SMTPPort = 25
SMTPUsername = ""
SMTPPassword = ""
SMTPUseSSL = False

' Initialize recipient collections
Set dictRecipients = Server.CreateObject("Scripting.Dictionary")
dictRecipients.Add "TO", Array()
dictRecipients.Add "CC", Array()
dictRecipients.Add "BCC", Array()

' Initialize attachments dynamic array
ReDim arrAttachments(-1)

' Default message settings
From = ""
Subject = ""
Body = ""
IsBodyHTML = False
End Sub

' Add a recipient by type: "To", "Cc", or "Bcc"
Public Sub AddRecipient(recipientType, address)
Dim key, tmp
key = UCase(recipientType)
If Not dictRecipients.Exists(key) Then
Err.Raise vbObjectError + 1000, "CDOEmail", "Invalid recipient type: " & recipientType
End If
tmp = dictRecipients(key)
If UBound(tmp) < LBound(tmp) Then
ReDim tmp(0)
Else
ReDim Preserve tmp(UBound(tmp) + 1)
End If
tmp(UBound(tmp)) = address
dictRecipients(key) = tmp
End Sub

' Add a file attachment
Public Sub AddAttachment(filePath)
If UBound(arrAttachments) < LBound(arrAttachments) Then
ReDim arrAttachments(0)
Else
ReDim Preserve arrAttachments(UBound(arrAttachments) + 1)
End If
arrAttachments(UBound(arrAttachments)) = filePath
End Sub

' Send the email, returning True on success, False on failure
Public Function Send()
' Configure SMTP settings
With cfg.Fields
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 ' cdoSendUsingPort
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = SMTPServer
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = SMTPPort
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = Choice(Len(SMTPUsername) > 0, 1, 0) ' cdoBasic or cdoAnonymous
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = SMTPUsername
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = SMTPPassword
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = SMTPUseSSL
.Update
End With

' Apply configuration to message
Set msg.Configuration = cfg

' Populate message fields
msg.From = From
msg.Subject = Subject
If dictRecipients.Exists("TO") And UBound(dictRecipients("TO")) >= LBound(dictRecipients("TO")) Then
msg.To = Join(dictRecipients("TO"), ";")
End If
If dictRecipients.Exists("CC") And UBound(dictRecipients("CC")) >= LBound(dictRecipients("CC")) Then
msg.CC = Join(dictRecipients("CC"), ";")
End If
If dictRecipients.Exists("BCC") And UBound(dictRecipients("BCC")) >= LBound(dictRecipients("BCC")) Then
msg.BCC = Join(dictRecipients("BCC"), ";")
End If

If IsBodyHTML Then
msg.HTMLBody = Body
Else
msg.TextBody = Body
End If

' Add attachments if any
Dim i
For i = LBound(arrAttachments) To UBound(arrAttachments)
msg.AddAttachment arrAttachments(i)
Next

' Send and handle errors
On Error Resume Next
msg.Send
errNum = Err.Number
errDesc = Err.Description
On Error Goto 0
If Err.Number <> 0 Then
Response.Write "CDO Error #" & errNum & ": " & errDesc & "<br/>"
Send = False
Err.Clear
Else
Send = True
End If
End Function

' Clean up objects
Private Sub Class_Terminate()
On Error Resume Next
Set msg = Nothing
Set cfg = Nothing
Set dictRecipients = Nothing
Erase arrAttachments
End Sub
End Class

dim CDOEmail_Class__Singleton
Function CDOEmail()
if IsEmpty(CDOEmail_Class__Singleton) then
set CDOEmail_Class__Singleton = new CDOEmail_Class
end if
set CDOEmail = CDOEmail_Class__Singleton
End Function

%>

+ 3
- 3
core/lib.Collections.asp View File

@@ -67,7 +67,7 @@ Sub DumpKVArray(kv_array)
dim i, key, val
For i = 0 to ubound(kv_array) step 2
KeyVal kv_array, i, key, val
put key & " => " & val & "<br>"
puts key & " => " & val & "<br>"
Next
End Sub

@@ -619,8 +619,8 @@ Class Iterator_Recordset_Class
Public Function HasNext()
HasNext = (m_current_index < m_record_count)
put "m_current_index := " & m_current_index
put "m_record_count := " & m_record_count
puts "m_current_index := " & m_current_index
puts "m_record_count := " & m_record_count
End Function
Public Function PeekNext


+ 1
- 0
core/lib.ControllerRegistry.asp View File

@@ -15,6 +15,7 @@ Class ControllerRegistry_Class
' Format: m_controllers.Add "controllername", True
RegisterController "homecontroller"
RegisterController "errorcontroller"
RegisterController "docscontroller"
End Sub

Private Sub Class_Terminate()


+ 188
- 87
core/lib.Data.asp View File

@@ -1,113 +1,214 @@
<%
'=======================================================================================================================
' DATABASE CLASS (native G3DB)
'=======================================================================================================================
' Thin wrapper over AxonASP's G3DB library. Keeps the original Database_Class API (Query, PagedQuery, Execute,
' Begin/Commit/RollbackTransaction, Connection) so callers such as DAL() and the Migrator are unchanged.
'
' Connection string: "<driver>:<dsn>", e.g.
' sqlite:/opt/axonasp/site/db/app.sqlite
' mysql:user:pass@tcp(127.0.0.1:3306)/app?parseTime=true
' postgres:host=127.0.0.1 port=5432 user=u password=p dbname=app sslmode=disable
' mssql:server=127.0.0.1;port=1433;user id=u;password=p;database=app
'
' Behavior notes (G3DB):
' - Query returns a forward-only result set (EOF, MoveNext, rs("col"), rs(0), Fields.Count, Close).
' - Parameters are positional "?" values. G3DB does not expand an array, so this class does (max MAX_PARAMS).
' - G3DB signals failure with Empty plus LastError; this class turns that into a raised VBScript error that
' includes the SQL, so errors are never silently ignored.
' - Transactions are handle based; while one is open, Query/Execute are routed through it.
Class Database_Class
Private m_connection
Private m_db
Private m_tx
Private m_driver
Private m_dsn
Private m_connection_string
Private m_trace_enabled
Public Sub set_trace(bool) : m_trace_enabled = bool : End Sub
Public Property Get is_trace_enabled : is_trace_enabled = m_trace_enabled : End Property

Public Sub set_trace(bool)
m_trace_enabled = bool
End Sub

Public Property Get is_trace_enabled
is_trace_enabled = m_trace_enabled
End Property

'---------------------------------------------------------------------------------------------------------------------
Public Sub Initialize(connection_string)
m_connection_string = connection_string
Dim p
m_connection_string = "" & connection_string
p = InStr(m_connection_string, ":")
If p < 2 Then
Err.Raise vbObjectError + 100, "Database_Class", "ConnectionString must look like '<driver>:<dsn>' (for example sqlite:/path/app.sqlite). Got: [" & m_connection_string & "]"
End If
m_driver = LCase(Left(m_connection_string, p - 1))
m_dsn = Mid(m_connection_string, p + 1)
If m_driver = "sqlite" Or m_driver = "sqlite3" Then
If InStr(m_dsn, "?") = 0 Then m_dsn = m_dsn & "?_busy_timeout=5000"
End If
End Sub

'---------------------------------------------------------------------------------------------------------------------
Public Function ShapeQuery(sql,params)
dim shapeConn : set shapeConn = server.createobject("adodb.connection")
shapeConn.ConnectionString = "Provider=MSDataShape;Data " & m_connection_string
dim cmd : set cmd = server.createobject("adodb.command")
shapeConn.open
set cmd.ActiveConnection = shapeConn
cmd.CommandText = sql
dim rs
If IsArray(params) then
set rs = cmd.Execute(, params)
ElseIf Not IsEmpty(params) then ' one parameter
set rs = cmd.Execute(, Array(params))
Else
set rs = cmd.Execute()
' The underlying G3DB object (opened on first use)
Public Function Connection()
If Not IsObject(m_db) Then
Set m_db = Server.CreateObject("G3DB")
If Not m_db.Open(m_driver, m_dsn) Then
Dim msg
msg = m_db.LastError
Set m_db = Empty
Err.Raise vbObjectError + 101, "Database_Class", "Could not open " & m_driver & " database: " & msg
End If
End If
set ShapeQuery = rs
Set Connection = m_db
End Function

'---------------------------------------------------------------------------------------------------------------------
' Runs a SELECT. params: Empty/Null (none), a scalar (one value) or an array of values.
Public Function Query(sql, params)
dim cmd : set cmd = server.createobject("adodb.command")
set cmd.ActiveConnection = Connection
cmd.CommandText = sql
dim rs
If IsArray(params) then
set rs = cmd.Execute(, params)
ElseIf Not IsEmpty(params) then ' one parameter
set rs = cmd.Execute(, Array(params))
Else
set rs = cmd.Execute()
End If
set Query = rs
Dim target, rs
Set target = Handle()
Set rs = RunQuery(target, sql, ParamList(params))
If IsEmpty(rs) Then RaiseDbError "Query failed", sql
Set Query = rs
End Function

'---------------------------------------------------------------------------------------------------------------------
Public Function PagedQuery(sql, params, per_page, page_num)
dim cmd : set cmd = server.createobject("adodb.command")
set cmd.ActiveConnection = Connection
cmd.CommandText = sql
cmd.CommandType = 1 'adCmdText
cmd.ActiveConnection.CursorLocation = 3 'adUseClient
dim rs
If IsArray(params) then
set rs = cmd.Execute(, params)
ElseIf Not IsEmpty(params) then ' one parameter
set rs = cmd.Execute(, Array(params))
Else
set rs = cmd.Execute()
End If
If Not rs.EOF then
rs.PageSize = 1
rs.CacheSize = 1
rs.AbsolutePage = 1
End If
set PagedQuery = rs
' Runs INSERT/UPDATE/DELETE/DDL. Returns the G3DBResult (RowsAffected, LastInsertId).
Public Function Exec(sql, params)
Dim target, result
Set target = Handle()
Set result = RunExec(target, sql, ParamList(params))
If IsEmpty(result) Then RaiseDbError "Statement failed", sql
Set Exec = result
End Function
'---------------------------------------------------------------------------------------------------------------------

' Same as Exec but discards the result (kept for the original Execute(sql, params) call style).
Public Sub [Execute](sql, params)
me.query sql, params
Dim result
Set result = Exec(sql, params)
Set result = Nothing
End Sub

'---------------------------------------------------------------------------------------------------------------------
' Returns one page of rows (1-based page_num) using LIMIT/OFFSET (SQLite, MySQL, PostgreSQL).
' sql must not already contain LIMIT/OFFSET.
Public Function PagedQuery(sql, params, per_page, page_num)
Dim size, page
size = CLng(per_page)
page = CLng(page_num)
If size < 1 Then size = 1
If page < 1 Then page = 1
Set PagedQuery = Query(sql & " LIMIT " & size & " OFFSET " & ((page - 1) * size), params)
End Function

'---------------------------------------------------------------------------------------------------------------------
Public Sub BeginTransaction
Connection.BeginTrans
Public Sub BeginTransaction()
If IsObject(m_tx) Then
Err.Raise vbObjectError + 102, "Database_Class", "A transaction is already open"
End If
Dim tx
Set tx = Connection().Begin()
If IsEmpty(tx) Then RaiseDbError "Could not begin transaction", ""
Set m_tx = tx
End Sub
Public Sub RollbackTransaction
Connection.RollbackTrans

Public Sub CommitTransaction()
Dim tx
If Not IsObject(m_tx) Then Exit Sub
Set tx = m_tx
Set m_tx = Empty
tx.Commit
End Sub
Public Sub CommitTransaction
Connection.CommitTrans

Public Sub RollbackTransaction()
Dim tx
If Not IsObject(m_tx) Then Exit Sub
Set tx = m_tx
Set m_tx = Empty
tx.Rollback
End Sub
'---------------------------------------------------------------------------------------------------------------------
' Private Methods
' Private helpers
'---------------------------------------------------------------------------------------------------------------------
Private Sub Class_terminate
Destroy m_connection
' The object to run statements on: the open transaction if there is one, otherwise the connection
Private Function Handle()
If IsObject(m_tx) Then
Set Handle = m_tx
Else
Set Handle = Connection()
End If
End Function

' Normalizes params to a zero-based array (possibly empty)
Private Function ParamList(params)
If IsArray(params) Then
ParamList = params
ElseIf IsEmpty(params) Or IsNull(params) Then
ParamList = Array()
Else
ParamList = Array(params)
End If
End Function

Private Function TxNote()
If IsObject(m_tx) Then
TxNote = " (statement ran inside a transaction; G3DB does not expose the driver error there)"
Else
TxNote = ""
End If
End Function

Private Sub RaiseDbError(prefix, sql)
Dim detail
detail = ""
If IsObject(m_db) Then detail = m_db.LastError
If Len(detail) = 0 Then
' G3DB reports no LastError for statements run inside a transaction handle
detail = "no driver message available" & TxNote()
End If
Err.Raise vbObjectError + 103, "Database_Class", prefix & ": " & detail & " -- SQL: " & sql
End Sub
Public Function Connection
if not isobject(m_connection) then
set m_connection = Server.CreateObject("adodb.connection")
m_connection.open m_connection_string
end if
set Connection = m_connection

' G3DB takes positional arguments, not an array, so expand explicitly
Private Function RunQuery(target, sql, p)
Select Case UBound(p)
Case -1 : Set RunQuery = target.Query(sql)
Case 0 : Set RunQuery = target.Query(sql, p(0))
Case 1 : Set RunQuery = target.Query(sql, p(0), p(1))
Case 2 : Set RunQuery = target.Query(sql, p(0), p(1), p(2))
Case 3 : Set RunQuery = target.Query(sql, p(0), p(1), p(2), p(3))
Case 4 : Set RunQuery = target.Query(sql, p(0), p(1), p(2), p(3), p(4))
Case 5 : Set RunQuery = target.Query(sql, p(0), p(1), p(2), p(3), p(4), p(5))
Case 6 : Set RunQuery = target.Query(sql, p(0), p(1), p(2), p(3), p(4), p(5), p(6))
Case 7 : Set RunQuery = target.Query(sql, p(0), p(1), p(2), p(3), p(4), p(5), p(6), p(7))
Case Else
Err.Raise vbObjectError + 104, "Database_Class", "Too many parameters (" & (UBound(p) + 1) & "); the maximum is 8"
End Select
End Function

Private Function RunExec(target, sql, p)
Select Case UBound(p)
Case -1 : Set RunExec = target.Exec(sql)
Case 0 : Set RunExec = target.Exec(sql, p(0))
Case 1 : Set RunExec = target.Exec(sql, p(0), p(1))
Case 2 : Set RunExec = target.Exec(sql, p(0), p(1), p(2))
Case 3 : Set RunExec = target.Exec(sql, p(0), p(1), p(2), p(3))
Case 4 : Set RunExec = target.Exec(sql, p(0), p(1), p(2), p(3), p(4))
Case 5 : Set RunExec = target.Exec(sql, p(0), p(1), p(2), p(3), p(4), p(5))
Case 6 : Set RunExec = target.Exec(sql, p(0), p(1), p(2), p(3), p(4), p(5), p(6))
Case 7 : Set RunExec = target.Exec(sql, p(0), p(1), p(2), p(3), p(4), p(5), p(6), p(7))
Case Else
Err.Raise vbObjectError + 104, "Database_Class", "Too many parameters (" & (UBound(p) + 1) & "); the maximum is 8"
End Select
End Function
end Class
%>

Private Sub Class_Terminate()
On Error Resume Next
If IsObject(m_tx) Then m_tx.Rollback
If IsObject(m_db) Then m_db.Close
On Error GoTo 0
End Sub
End Class
%>

+ 3
- 3
core/lib.Flash.asp View File

@@ -63,9 +63,9 @@ Class Flash_Class
dim ary, i
ary = Errors
for i = 0 to ubound(ary)
put "<li>"
put H(ary(i))
put "</li>"
puts "<li>"
puts H(ary(i))
puts "</li>"
next
%>
</ul>


+ 15
- 7
core/lib.HTML.Security.asp View File

@@ -5,11 +5,12 @@
Class HTML_Security_Helper_Class

'---------------------------------------------------------------------------------------------------------------------
'Uses Scriptlet.TypeLib to generate a GUID. There may be a better/faster way than this to generate a nonce.
' Returns a random RFC 4122 v4 UUID (native G3CRYPTO; replaces Scriptlet.TypeLib, which does not exist on AxonASP)
Public Function Nonce()
dim TL : set TL = CreateObject("Scriptlet.TypeLib")
Nonce = Left(CStr(TL.Guid), 38) 'avoids issue w/ strings appended after this token not being displayed on screen, MSFT bug
set TL = Nothing
Dim crypto
Set crypto = Server.CreateObject("G3CRYPTO")
Nonce = crypto.UUID()
Set crypto = Nothing
End Function
'---------------------------------------------------------------------------------------------------------------------
@@ -21,9 +22,11 @@ Class HTML_Security_Helper_Class
'---------------------------------------------------------------------------------------------------------------------
'Returns the CSRF token nonce from the session corresponding to the passed name
Public Function GetAntiCSRFToken(name)
dim token : token = Session(name & ".anti_csrf_token")
If Len(token) = 0 or IsEmpty(token) then
Dim token
token = "" & Session(name & ".anti_csrf_token")
If Len(token) = 0 Then
SetAntiCSRFToken name
token = "" & Session(name & ".anti_csrf_token") ' re-read: return the newly created token
End If
GetAntiCSRFToken = token
End Function
@@ -37,7 +40,12 @@ Class HTML_Security_Helper_Class
'---------------------------------------------------------------------------------------------------------------------
'Returns true if passed nonce matches the stored CSRF token nonce for the specified name, false if not
Public Function IsValidAntiCSRFToken(name, nonce)
IsValidAntiCSRFToken = (GetAntiCSRFToken(name) = nonce)
' An empty/missing nonce is never valid, and a token is never created just to be compared
If Len("" & nonce) = 0 Or Len("" & Session(name & ".anti_csrf_token")) = 0 Then
IsValidAntiCSRFToken = False
Else
IsValidAntiCSRFToken = (CStr(Session(name & ".anti_csrf_token")) = CStr(nonce))
End If
End Function
'---------------------------------------------------------------------------------------------------------------------


+ 321
- 0
core/lib.JsonLite.asp View File

@@ -0,0 +1,321 @@
<%
'=======================================================================================================================
' JsonLite: tiny pure-VBScript JSON reader/encoder for flat request bodies.
'
' Why not G3JSON? Under the AxonASP HTTP server, G3JSON.Parse results and G3DB interfered with each other: parsing before the
' first database open made the first INSERT silently do nothing, and opening the database first made Parse return empty
' dictionaries. Plain VBScript classes avoid native objects altogether (see AGENTS.md).
'
' Set obj = JsonLite_Parse(text) ' Nothing when text is not a valid JSON object
' obj.Exists("Name"), obj.Item("Name")
' JsonLite_Quote(s) ' "text" with JSON escaping
' JsonLite_Num(n) ' locale-independent number literal
'
' Values: String, Double (numbers), Boolean, Null. Nested objects/arrays are parsed and stored as Null.
'=======================================================================================================================
Class JsonLite_Object
Private m_keys(), m_vals(), m_count

Private Sub Class_Initialize()
m_count = 0
ReDim m_keys(7)
ReDim m_vals(7)
End Sub

Public Sub Add(k, v)
Dim i
For i = 0 To m_count - 1
If LCase(m_keys(i)) = LCase(k) Then
m_vals(i) = v
Exit Sub
End If
Next
If m_count > UBound(m_keys) Then
ReDim Preserve m_keys(m_count * 2)
ReDim Preserve m_vals(m_count * 2)
End If
m_keys(m_count) = k
m_vals(m_count) = v
m_count = m_count + 1
End Sub

Public Function Exists(k)
Dim i
Exists = False
For i = 0 To m_count - 1
If LCase(m_keys(i)) = LCase(k) Then
Exists = True
Exit Function
End If
Next
End Function

Public Function Item(k)
Dim i
Item = Null
For i = 0 To m_count - 1
If LCase(m_keys(i)) = LCase(k) Then
Item = m_vals(i)
Exit Function
End If
Next
End Function
End Class

Class JsonLite_Parser
Private m_s, m_pos, m_len, m_ok

Public Function Run(text)
Dim obj
m_s = "" & text
m_len = Len(m_s)
m_pos = 1
m_ok = True
Set Run = Nothing
SkipWs
If m_pos > m_len Then Exit Function
If Mid(m_s, m_pos, 1) <> "{" Then Exit Function
Set obj = ReadObject()
If Not m_ok Then Exit Function
SkipWs
If m_pos <= m_len Then Exit Function ' trailing garbage
Set Run = obj
End Function

Private Sub SkipWs()
Dim c
Do While m_pos <= m_len
c = Mid(m_s, m_pos, 1)
If c = " " Or c = vbTab Or c = vbCr Or c = vbLf Then
m_pos = m_pos + 1
Else
Exit Do
End If
Loop
End Sub

Private Function ReadObject()
Dim obj, k, v, c
Set obj = New JsonLite_Object
Set ReadObject = obj
m_pos = m_pos + 1 ' {
SkipWs
If m_pos <= m_len Then
If Mid(m_s, m_pos, 1) = "}" Then
m_pos = m_pos + 1
Exit Function
End If
End If
Do
SkipWs
If m_pos > m_len Then
m_ok = False
Exit Function
End If
If Mid(m_s, m_pos, 1) <> """" Then
m_ok = False
Exit Function
End If
k = ReadString()
If Not m_ok Then Exit Function
SkipWs
If m_pos > m_len Then
m_ok = False
Exit Function
End If
If Mid(m_s, m_pos, 1) <> ":" Then
m_ok = False
Exit Function
End If
m_pos = m_pos + 1
v = ReadValue()
If Not m_ok Then Exit Function
obj.Add k, v
SkipWs
If m_pos > m_len Then
m_ok = False
Exit Function
End If
c = Mid(m_s, m_pos, 1)
m_pos = m_pos + 1
If c = "}" Then Exit Function
If c <> "," Then
m_ok = False
Exit Function
End If
Loop
End Function

' Reads any value; returns String, Double, Boolean or Null (nested containers are consumed and returned as Null)
Private Function ReadValue()
Dim c, t, start, lit, dummy
ReadValue = Null
SkipWs
If m_pos > m_len Then
m_ok = False
Exit Function
End If
c = Mid(m_s, m_pos, 1)
If c = """" Then
ReadValue = ReadString()
ElseIf c = "{" Then
Set dummy = ReadObject()
ElseIf c = "[" Then
SkipArray
ElseIf c = "-" Or (c >= "0" And c <= "9") Then
start = m_pos
Do While m_pos <= m_len
t = Mid(m_s, m_pos, 1)
If (t >= "0" And t <= "9") Or t = "-" Or t = "+" Or t = "." Or t = "e" Or t = "E" Then
m_pos = m_pos + 1
Else
Exit Do
End If
Loop
lit = Mid(m_s, start, m_pos - start)
' CDbl uses the locale's decimal separator, JSON always uses "."
lit = Replace(UCase(lit), ".", Mid(CStr(1.5), 2, 1))
On Error Resume Next
ReadValue = CDbl(lit)
If Err.Number <> 0 Then
Err.Clear
m_ok = False
End If
On Error GoTo 0
Else
If LCase(Mid(m_s, m_pos, 4)) = "true" Then
ReadValue = True
m_pos = m_pos + 4
ElseIf LCase(Mid(m_s, m_pos, 5)) = "false" Then
ReadValue = False
m_pos = m_pos + 5
ElseIf LCase(Mid(m_s, m_pos, 4)) = "null" Then
ReadValue = Null
m_pos = m_pos + 4
Else
m_ok = False
End If
End If
End Function

Private Sub SkipArray()
Dim c, v
m_pos = m_pos + 1 ' [
SkipWs
If m_pos <= m_len Then
If Mid(m_s, m_pos, 1) = "]" Then
m_pos = m_pos + 1
Exit Sub
End If
End If
Do
v = ReadValue()
If Not m_ok Then Exit Sub
SkipWs
If m_pos > m_len Then
m_ok = False
Exit Sub
End If
c = Mid(m_s, m_pos, 1)
m_pos = m_pos + 1
If c = "]" Then Exit Sub
If c <> "," Then
m_ok = False
Exit Sub
End If
Loop
End Sub

Private Function ReadString()
Dim out, c, e, h
out = ""
m_pos = m_pos + 1 ' opening quote
Do While m_pos <= m_len
c = Mid(m_s, m_pos, 1)
m_pos = m_pos + 1
If c = """" Then
ReadString = out
Exit Function
ElseIf c = "\" Then
If m_pos > m_len Then Exit Do
e = Mid(m_s, m_pos, 1)
m_pos = m_pos + 1
Select Case e
Case """": out = out & """"
Case "\": out = out & "\"
Case "/": out = out & "/"
Case "b": out = out & Chr(8)
Case "f": out = out & Chr(12)
Case "n": out = out & vbLf
Case "r": out = out & vbCr
Case "t": out = out & vbTab
Case "u"
h = Mid(m_s, m_pos, 4)
If Len(h) < 4 Or Not IsHex(h) Then
m_ok = False
Exit Function
End If
out = out & ChrW(CLng("&H" & h))
m_pos = m_pos + 4
Case Else
m_ok = False
Exit Function
End Select
Else
out = out & c
End If
Loop
m_ok = False ' unterminated string
End Function

Private Function IsHex(h)
Dim i, c
IsHex = True
For i = 1 To Len(h)
c = LCase(Mid(h, i, 1))
If Not ((c >= "0" And c <= "9") Or (c >= "a" And c <= "f")) Then
IsHex = False
Exit Function
End If
Next
End Function
End Class

Function JsonLite_Parse(text)
Dim p
Set p = New JsonLite_Parser
Set JsonLite_Parse = p.Run(text)
End Function

' "text" with JSON escaping (non-ASCII is left as is; the response is UTF-8)
Function JsonLite_Quote(s)
Dim t, i, c, n, out
t = "" & s
out = ""
For i = 1 To Len(t)
c = Mid(t, i, 1)
n = AscW(c)
If c = """" Then
out = out & "\"""
ElseIf c = "\" Then
out = out & "\\"
ElseIf n = 10 Then
out = out & "\n"
ElseIf n = 13 Then
out = out & "\r"
ElseIf n = 9 Then
out = out & "\t"
ElseIf n < 32 And n >= 0 Then
out = out & "\u" & Right("0000" & Hex(n), 4)
Else
out = out & c
End If
Next
JsonLite_Quote = """" & out & """"
End Function

' Locale-independent number literal (CStr uses the locale's decimal separator)
Function JsonLite_Num(n)
JsonLite_Num = Replace(CStr(CDbl(n)), ",", ".")
End Function
%>

+ 78
- 81
core/lib.Migrations.asp View File

@@ -31,6 +31,11 @@ Class Migrator_Class
m_migrations_path = Server.MapPath("../db/migrations/")
End Sub

' Override the migrations folder (needed when run from the CLI, where relative MapPath is not meaningful)
Public Property Let MigrationsPath(v)
m_migrations_path = v
End Property

'-------------------------------------------------------------------------------------------------------------------
' Ensure the schema_migrations table exists
'-------------------------------------------------------------------------------------------------------------------
@@ -39,7 +44,7 @@ Class Migrator_Class

' Try to query the table - if it doesn't exist, create it
Dim rs
Set rs = m_db.Query("SELECT TOP 1 version FROM " & m_schema_table, empty)
Set rs = m_db.Query("SELECT version FROM " & m_schema_table & " WHERE 1=0", empty)

If Err.Number <> 0 Then
' Table doesn't exist, create it
@@ -159,54 +164,32 @@ Class Migrator_Class
' Apply a migration (run the Up method)
'-------------------------------------------------------------------------------------------------------------------
Public Sub ApplyMigration(filename)
Dim version
Dim version, msg
version = GetVersionFromFilename(filename)

If version = "" Then
Err.Raise vbObjectError + 1, "Migrator", "Invalid migration filename format: " & filename
End If

' Check if already applied
Dim applied
Set applied = GetAppliedMigrations()
If applied.Exists(version) Then
If GetAppliedMigrations().Exists(version) Then
Response.Write "Migration " & version & " already applied. Skipping." & vbCrLf
Exit Sub
End If

Response.Write "Applying migration: " & filename & "..." & vbCrLf

' Begin transaction
m_db.BeginTransaction

On Error Resume Next

' Execute the migration file
ExecuteMigrationFile filename, "Up"

If Err.Number <> 0 Then
Dim errMsg
errMsg = "Migration failed: " & Err.Description
m_db.RollbackTransaction
Err.Raise vbObjectError + 2, "Migrator", errMsg
msg = RunMigrationFile(filename, "Up")
If msg = "" Then
msg = TrySql("INSERT INTO " & m_schema_table & " (version, applied_at) VALUES (?, ?)", Array(version, NowIso()))
If msg <> "" Then msg = "Failed to record migration: " & msg
End If

' Record the migration
m_db.Execute "INSERT INTO " & m_schema_table & " (version, applied_at) VALUES (?, ?)", _
Array(version, Now())

If Err.Number <> 0 Then
Dim recordErr
recordErr = "Failed to record migration: " & Err.Description
If msg <> "" Then
m_db.RollbackTransaction
Err.Raise vbObjectError + 3, "Migrator", recordErr
Err.Raise vbObjectError + 2, "Migrator", "Migration " & version & " FAILED and was rolled back: " & msg
End If

' Commit transaction
m_db.CommitTransaction

On Error GoTo 0

Response.Write "Migration " & version & " applied successfully." & vbCrLf
End Sub

@@ -214,85 +197,90 @@ Class Migrator_Class
' Rollback a migration (run the Down method)
'-------------------------------------------------------------------------------------------------------------------
Public Sub RollbackMigration(filename)
Dim version
Dim version, msg
version = GetVersionFromFilename(filename)

If version = "" Then
Err.Raise vbObjectError + 1, "Migrator", "Invalid migration filename format: " & filename
End If

' Check if applied
Dim applied
Set applied = GetAppliedMigrations()
If Not applied.Exists(version) Then
Response.Write "Migration " & version & " not applied. Skipping." & vbCrLf
If Not GetAppliedMigrations().Exists(version) Then
Response.Write "Migration " & version & " is not applied. Skipping." & vbCrLf
Exit Sub
End If

Response.Write "Rolling back migration: " & filename & "..." & vbCrLf

' Begin transaction
m_db.BeginTransaction

On Error Resume Next

' Execute the migration file
ExecuteMigrationFile filename, "Down"

If Err.Number <> 0 Then
Dim errMsg
errMsg = "Rollback failed: " & Err.Description
m_db.RollbackTransaction
Err.Raise vbObjectError + 4, "Migrator", errMsg
msg = RunMigrationFile(filename, "Down")
If msg = "" Then
msg = TrySql("DELETE FROM " & m_schema_table & " WHERE version = ?", version)
If msg <> "" Then msg = "Failed to remove migration record: " & msg
End If

' Remove the migration record
m_db.Execute "DELETE FROM " & m_schema_table & " WHERE version = ?", version

If Err.Number <> 0 Then
Dim recordErr
recordErr = "Failed to remove migration record: " & Err.Description
If msg <> "" Then
m_db.RollbackTransaction
Err.Raise vbObjectError + 5, "Migrator", recordErr
Err.Raise vbObjectError + 4, "Migrator", "Rollback of " & version & " FAILED: " & msg
End If

' Commit transaction
m_db.CommitTransaction

On Error GoTo 0

Response.Write "Migration " & version & " rolled back successfully." & vbCrLf
End Sub

'-------------------------------------------------------------------------------------------------------------------
' Execute a migration file's Up or Down method
'-------------------------------------------------------------------------------------------------------------------
Private Sub ExecuteMigrationFile(filename, direction)
Dim migrationPath
migrationPath = m_migrations_path & filename
Private Function NowIso()
Dim n : n = Now()
NowIso = Year(n) & "-" & Right("0" & Month(n), 2) & "-" & Right("0" & Day(n), 2) & " " & _
Right("0" & Hour(n), 2) & ":" & Right("0" & Minute(n), 2) & ":" & Right("0" & Second(n), 2)
End Function

Dim fso
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Private Function TrySql(sql, params)
' Runs one statement; returns "" on success or a readable error message (never swallows the error)
On Error Resume Next
m_db.Execute sql, params
If Err.Number <> 0 Then
TrySql = "[" & Err.Number & "] " & Err.Description
Err.Clear
Else
TrySql = ""
End If
End Function

' Loads and runs a migration file's Up/Down. Returns "" on success or a readable error message.
Private Function RunMigrationFile(filename, direction)
On Error Resume Next
Dim migrationPath, fso, ts, code, migration, step
migrationPath = m_migrations_path & "/" & filename
migrationPath = Replace(migrationPath, "//", "/")

step = "locate file " & migrationPath
Set fso = Server.CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(migrationPath) Then
Err.Raise vbObjectError + 6, "Migrator", "Migration file not found: " & migrationPath
RunMigrationFile = "Migration file not found: " & migrationPath
Exit Function
End If

' Create a migration context that the file can use
Dim migration
step = "read file"
Set ts = fso.OpenTextFile(migrationPath, 1)
code = ts.ReadAll
ts.Close
If Err.Number <> 0 Then RunMigrationFile = "[" & Err.Number & "] " & Err.Description & " (while trying to " & step & ")" : Err.Clear : Exit Function

step = "compile file"
code = Replace(Replace(code, "<%", ""), "%>", "")
ExecuteGlobal code
If Err.Number <> 0 Then RunMigrationFile = "[" & Err.Number & "] " & Err.Description & " (while trying to " & step & ")" : Err.Clear : Exit Function

Set migration = New MigrationContext_Class
Set migration.DB = m_db

' Include and execute the migration file
Server.Execute(migrationPath)
step = "run Migration_" & direction
Execute "Call Migration_" & direction & "(migration)"
If Err.Number <> 0 Then RunMigrationFile = "[" & Err.Number & "] " & Err.Description & " (while trying to " & step & ")" : Err.Clear : Exit Function

' Call the appropriate method (Up or Down)
If direction = "Up" Then
Execute "Call Migration_Up(migration)"
ElseIf direction = "Down" Then
Execute "Call Migration_Down(migration)"
End If
End Sub
RunMigrationFile = ""
End Function

'-------------------------------------------------------------------------------------------------------------------
' Apply all pending migrations
@@ -318,7 +306,7 @@ Class Migrator_Class
Dim j, temp
For i = 0 To UBound(versions) - 1
For j = i + 1 To UBound(versions)
If CLng(versions(i)) > CLng(versions(j)) Then
If CDbl(versions(i)) > CDbl(versions(j)) Then
temp = versions(i)
versions(i) = versions(j)
versions(j) = temp
@@ -347,7 +335,10 @@ Class Migrator_Class
' Find the last version
lastVersion = ""
For Each version In applied.Keys
If lastVersion = "" Or CLng(version) > CLng(lastVersion) Then
' VBScript does not short-circuit Or, so CDbl("") must be avoided explicitly
If lastVersion = "" Then
lastVersion = version
ElseIf CDbl(version) > CDbl(lastVersion) Then
lastVersion = version
End If
Next
@@ -377,7 +368,13 @@ Class MigrationContext_Class
' Execute raw SQL
'-------------------------------------------------------------------------------------------------------------------
Public Sub ExecuteSQL(sql)
On Error Resume Next
DB.Execute sql, empty
If Err.Number <> 0 Then
Dim n, d : n = Err.Number : d = Err.Description
On Error GoTo 0
Err.Raise n, "MigrationContext", d
End If
End Sub

'-------------------------------------------------------------------------------------------------------------------
@@ -421,7 +418,7 @@ Class MigrationContext_Class
' Drop an index
'-------------------------------------------------------------------------------------------------------------------
Public Sub DropIndex(indexName, tableName)
ExecuteSQL "DROP INDEX " & indexName & " ON " & tableName
ExecuteSQL "DROP INDEX " & indexName ' SQLite syntax (Access/SQL Server need "ON table")
End Sub
End Class



+ 144
- 0
core/lib.Router.asp View File

@@ -0,0 +1,144 @@
<%
' Router_Class: pure-ASP port of router.wsc (AxonASP/Linux cannot load Windows Script Components)
Class Router_Class



'------------------------------------------------------------
' Private state
'------------------------------------------------------------
Private routes

Private Sub Class_Initialize()
Set routes = CreateObject("Scripting.Dictionary")
End Sub

'------------------------------------------------------------
' METHOD AddRoute(method, path, controller, action)
'------------------------------------------------------------
Public Sub AddRoute(method, path, controller, action)
' Input validation
If IsEmpty(method) Or Len(Trim(method)) = 0 Then
Err.Raise 5, "Router.AddRoute", "HTTP method parameter is required and cannot be empty"
End If

If IsEmpty(path) Then
Err.Raise 5, "Router.AddRoute", "Path parameter is required"
End If

If IsEmpty(controller) Or Len(Trim(controller)) = 0 Then
Err.Raise 5, "Router.AddRoute", "Controller parameter is required and cannot be empty"
End If

If IsEmpty(action) Or Len(Trim(action)) = 0 Then
Err.Raise 5, "Router.AddRoute", "Action parameter is required and cannot be empty"
End If

' Validate HTTP method (allow common methods)
Dim validMethods, methodUpper, i, isValidMethod
validMethods = Array("GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS")
methodUpper = UCase(Trim(method))
isValidMethod = False

For i = 0 To UBound(validMethods)
If validMethods(i) = methodUpper Then
isValidMethod = True
Exit For
End If
Next

If Not isValidMethod Then
Err.Raise 5, "Router.AddRoute", "Invalid HTTP method: " & method & ". Allowed: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS"
End If

Dim routeKey
routeKey = methodUpper & ":" & LCase(Trim(path))

If Not routes.Exists(routeKey) Then
routes.Add routeKey, Array(Trim(controller), Trim(action))
End If
End Sub

'------------------------------------------------------------
' METHOD Resolve(method, path) -> Array(controller, action, params())
'------------------------------------------------------------
Public Function Resolve(method, path)
Dim routeKey, routeValue, values
routeKey = UCase(method) & ":" & LCase(path)

' Always return a params array (empty by default)
Dim emptyParams() : ReDim emptyParams(-1)

' Exact match first
If routes.Exists(routeKey) Then
routeValue = routes(routeKey)
Resolve = Array(routeValue(0), routeValue(1), emptyParams)
Exit Function
End If

' Dynamic routes (e.g. /users/:id)
Dim r, routeMethod, routePattern
For Each r In routes.Keys
routeMethod = Split(r, ":")(0)
routePattern = Mid(r, Len(routeMethod) + 2) ' strip "METHOD:"
If UCase(routeMethod) = UCase(method) Then
If IsMatch(path, routePattern, values) Then
routeValue = routes(r)
Resolve = Array(routeValue(0), routeValue(1), values)
Exit Function
End If
End If
Next

' 404 fallback
Resolve = Array("ErrorController", "NotFound", emptyParams)
End Function

'------------------------------------------------------------
' INTERNAL IsMatch(requestPath, routePattern, values())
' Returns True/False and fills values() with parameters
'------------------------------------------------------------
Private Function IsMatch(requestPath, routePattern, values)
Dim reqParts, routeParts, i, paramCount
reqParts = Split(requestPath, "/")
routeParts = Split(routePattern, "/")

If UBound(reqParts) <> UBound(routeParts) Then
IsMatch = False : Exit Function
End If

paramCount = 0 : ReDim values(-1)

For i = 0 To UBound(reqParts)
If Left(routeParts(i), 1) = ":" Then
ReDim Preserve values(paramCount)
values(paramCount) = reqParts(i)
paramCount = paramCount + 1
ElseIf LCase(routeParts(i)) <> LCase(reqParts(i)) Then
IsMatch = False : Exit Function
End If
Next

If paramCount = 0 Then ReDim values(-1)
IsMatch = True
End Function

'------------------------------------------------------------
' Optional lifecycle hooks
'------------------------------------------------------------
Private Sub Class_Terminate()
Set routes = Nothing
End Sub
End Class
' Singleton accessor (same pattern as MVC()/ControllerRegistry()) so the router is visible
' inside class methods regardless of include order.
Dim Router_Class__Singleton
Function GetRouter()
If IsEmpty(Router_Class__Singleton) Then
Set Router_Class__Singleton = New Router_Class
End If
Set GetRouter = Router_Class__Singleton
End Function
Dim router : Set router = GetRouter()
%>

+ 0
- 405
core/lib.Upload.asp View File

@@ -1,405 +0,0 @@
<!--METADATA
TYPE="TypeLib"
NAME="Microsoft ActiveX Data Objects 2.5 Library"
UUID="{00000205-0000-0010-8000-00AA006D2EA4}"
VERSION="2.5"
-->


<%
' For examples, documentation, and your own free copy, go to:
' http://www.freeaspupload.net
' Note: You can copy and use this script for free and you can make changes
' to the code, but you cannot remove the above comment.

'Changes:
'Aug 2, 2005: Add support for checkboxes and other input elements with multiple values
'Jan 6, 2009: Lars added ASP_CHUNK_SIZE

const DEFAULT_ASP_CHUNK_SIZE = 200000

Class FreeASPUpload
Public UploadedFiles
Public FormElements

Private VarArrayBinRequest
Private StreamRequest
Private uploadedYet
Private internalChunkSize

Private Sub Class_Initialize()
Set UploadedFiles = Server.CreateObject("Scripting.Dictionary")
Set FormElements = Server.CreateObject("Scripting.Dictionary")
Set StreamRequest = Server.CreateObject("ADODB.Stream")
StreamRequest.Type = 2 ' adTypeText
StreamRequest.Open
uploadedYet = false
internalChunkSize = DEFAULT_ASP_CHUNK_SIZE
End Sub
Private Sub Class_Terminate()
If IsObject(UploadedFiles) Then
UploadedFiles.RemoveAll()
Set UploadedFiles = Nothing
End If
If IsObject(FormElements) Then
FormElements.RemoveAll()
Set FormElements = Nothing
End If
StreamRequest.Close
Set StreamRequest = Nothing
End Sub

Public Property Get Form(sIndex)
Form = ""
If FormElements.Exists(LCase(sIndex)) Then Form = FormElements.Item(LCase(sIndex))
End Property

Public Property Get Files()
Files = UploadedFiles.Items
End Property
Public Property Get Exists(sIndex)
Exists = false
If FormElements.Exists(LCase(sIndex)) Then Exists = true
End Property

Public Property Get FileExists(sIndex)
FileExists = false
if UploadedFiles.Exists(LCase(sIndex)) then FileExists = true
End Property

Public Property Get chunkSize()
chunkSize = internalChunkSize
End Property

Public Property Let chunkSize(sz)
internalChunkSize = sz
End Property

'Calls Upload to extract the data from the binary request and then saves the uploaded files
Public Sub Save(path)
Dim streamFile, fileItem

if Right(path, 1) <> "\" then path = path & "\"

if not uploadedYet then Upload

For Each fileItem In UploadedFiles.Items
Set streamFile = Server.CreateObject("ADODB.Stream")
streamFile.Type = 1
streamFile.Open
StreamRequest.Position=fileItem.Start
StreamRequest.CopyTo streamFile, fileItem.Length
streamFile.SaveToFile path & fileItem.FileName, 2
streamFile.close
Set streamFile = Nothing
fileItem.Path = path & fileItem.FileName
Next
End Sub
public sub SaveOne(path, num, byref outFileName, byref outLocalFileName)
Dim streamFile, fileItems, fileItem, fs

set fs = Server.CreateObject("Scripting.FileSystemObject")
if Right(path, 1) <> "\" then path = path & "\"

if not uploadedYet then Upload
if UploadedFiles.Count > 0 then
fileItems = UploadedFiles.Items
set fileItem = fileItems(num)
outFileName = fileItem.FileName
outLocalFileName = GetFileName(path, outFileName)
Set streamFile = Server.CreateObject("ADODB.Stream")
streamFile.Type = 1
streamFile.Open
StreamRequest.Position = fileItem.Start
StreamRequest.CopyTo streamFile, fileItem.Length
streamFile.SaveToFile path & outLocalFileName, 2
streamFile.close
Set streamFile = Nothing
fileItem.Path = path & filename
end if
end sub

Public Function SaveBinRequest(path) ' For debugging purposes
StreamRequest.SaveToFile path & "\debugStream.bin", 2
End Function

Public Sub DumpData() 'only works if files are plain text
Dim i, aKeys, f
response.write "Form Items:<br>"
aKeys = FormElements.Keys
For i = 0 To FormElements.Count -1 ' Iterate the array
response.write aKeys(i) & " = " & FormElements.Item(aKeys(i)) & "<BR>"
Next
response.write "Uploaded Files:<br>"
For Each f In UploadedFiles.Items
response.write "Name: " & f.FileName & "<br>"
response.write "Type: " & f.ContentType & "<br>"
response.write "Start: " & f.Start & "<br>"
response.write "Size: " & f.Length & "<br>"
Next
End Sub

Public Sub Upload()
Dim nCurPos, nDataBoundPos, nLastSepPos
Dim nPosFile, nPosBound
Dim sFieldName, osPathSep, auxStr
Dim readBytes, readLoop, tmpBinRequest
'RFC1867 Tokens
Dim vDataSep
Dim tNewLine, tDoubleQuotes, tTerm, tFilename, tName, tContentDisp, tContentType
tNewLine = String2Byte(Chr(13))
tDoubleQuotes = String2Byte(Chr(34))
tTerm = String2Byte("--")
tFilename = String2Byte("filename=""")
tName = String2Byte("name=""")
tContentDisp = String2Byte("Content-Disposition")
tContentType = String2Byte("Content-Type:")

uploadedYet = true

on error resume next
readBytes = internalChunkSize
VarArrayBinRequest = Request.BinaryRead(readBytes)
VarArrayBinRequest = midb(VarArrayBinRequest, 1, lenb(VarArrayBinRequest))
for readLoop = 0 to 300000
tmpBinRequest = Request.BinaryRead(readBytes)
if readBytes < 1 then exit for
VarArrayBinRequest = VarArrayBinRequest & midb(tmpBinRequest, 1, lenb(tmpBinRequest))
next
if Err.Number <> 0 then
response.write "<br><br><B>System reported this error:</B><p>"
response.write Err.Description & "<p>"
response.write "The most likely cause for this error is the incorrect setup of AspMaxRequestEntityAllowed in IIS MetaBase. Please see instructions in the <A HREF='http://www.freeaspupload.net/freeaspupload/requirements.asp'>requirements page of freeaspupload.net</A>.<p>"
Exit Sub
end if
on error goto 0 'reset error handling

nCurPos = FindToken(tNewLine,1) 'Note: nCurPos is 1-based (and so is InstrB, MidB, etc)

If nCurPos <= 1 Then Exit Sub
'vDataSep is a separator like -----------------------------21763138716045
vDataSep = MidB(VarArrayBinRequest, 1, nCurPos-1)

'Start of current separator
nDataBoundPos = 1

'Beginning of last line
nLastSepPos = FindToken(vDataSep & tTerm, 1)

Do Until nDataBoundPos = nLastSepPos
nCurPos = SkipToken(tContentDisp, nDataBoundPos)
nCurPos = SkipToken(tName, nCurPos)
sFieldName = ExtractField(tDoubleQuotes, nCurPos)

nPosFile = FindToken(tFilename, nCurPos)
nPosBound = FindToken(vDataSep, nCurPos)
If nPosFile <> 0 And nPosFile < nPosBound Then
Dim oUploadFile
Set oUploadFile = New UploadedFile
nCurPos = SkipToken(tFilename, nCurPos)
auxStr = ExtractField(tDoubleQuotes, nCurPos)
' We are interested only in the name of the file, not the whole path
' Path separator is \ in windows, / in UNIX
' While IE seems to put the whole pathname in the stream, Mozilla seem to
' only put the actual file name, so UNIX paths may be rare. But not impossible.
osPathSep = "\"
if InStr(auxStr, osPathSep) = 0 then osPathSep = "/"
oUploadFile.FileName = Right(auxStr, Len(auxStr)-InStrRev(auxStr, osPathSep))

if (Len(oUploadFile.FileName) > 0) then 'File field not left empty
nCurPos = SkipToken(tContentType, nCurPos)
auxStr = ExtractField(tNewLine, nCurPos)
' NN on UNIX puts things like this in the stream:
' ?? python py type=?? python application/x-python
oUploadFile.ContentType = Right(auxStr, Len(auxStr)-InStrRev(auxStr, " "))
nCurPos = FindToken(tNewLine, nCurPos) + 4 'skip empty line
oUploadFile.Start = nCurPos+1
oUploadFile.Length = FindToken(vDataSep, nCurPos) - 2 - nCurPos
If oUploadFile.Length > 0 Then UploadedFiles.Add LCase(sFieldName), oUploadFile
End If
Else
Dim nEndOfData
nCurPos = FindToken(tNewLine, nCurPos) + 4 'skip empty line
nEndOfData = FindToken(vDataSep, nCurPos) - 2
If Not FormElements.Exists(LCase(sFieldName)) Then
FormElements.Add LCase(sFieldName), Byte2String(MidB(VarArrayBinRequest, nCurPos, nEndOfData-nCurPos))
else
FormElements.Item(LCase(sFieldName))= FormElements.Item(LCase(sFieldName)) & ", " & Byte2String(MidB(VarArrayBinRequest, nCurPos, nEndOfData-nCurPos))
end if

End If

'Advance to next separator
nDataBoundPos = FindToken(vDataSep, nCurPos)
Loop
StreamRequest.WriteText(VarArrayBinRequest)
End Sub

Private Function SkipToken(sToken, nStart)
SkipToken = InstrB(nStart, VarArrayBinRequest, sToken)
If SkipToken = 0 then
Response.write "Error in parsing uploaded binary request. The most likely cause for this error is the incorrect setup of AspMaxRequestEntityAllowed in IIS MetaBase. Please see instructions in the <A HREF='http://www.freeaspupload.net/freeaspupload/requirements.asp'>requirements page of freeaspupload.net</A>.<p>"
Response.End
end if
SkipToken = SkipToken + LenB(sToken)
End Function

Private Function FindToken(sToken, nStart)
FindToken = InstrB(nStart, VarArrayBinRequest, sToken)
End Function

Private Function ExtractField(sToken, nStart)
Dim nEnd
nEnd = InstrB(nStart, VarArrayBinRequest, sToken)
If nEnd = 0 then
Response.write "Error in parsing uploaded binary request."
Response.End
end if
ExtractField = Byte2String(MidB(VarArrayBinRequest, nStart, nEnd-nStart))
End Function

'String to byte string conversion
Private Function String2Byte(sString)
Dim i
For i = 1 to Len(sString)
String2Byte = String2Byte & ChrB(AscB(Mid(sString,i,1)))
Next
End Function

'Byte string to string conversion
Private Function Byte2String(bsString)
Dim i
dim b1, b2, b3, b4
Byte2String =""
For i = 1 to LenB(bsString)
if AscB(MidB(bsString,i,1)) < 128 then
' One byte
Byte2String = Byte2String & ChrW(AscB(MidB(bsString,i,1)))
elseif AscB(MidB(bsString,i,1)) < 224 then
' Two bytes
b1 = AscB(MidB(bsString,i,1))
b2 = AscB(MidB(bsString,i+1,1))
Byte2String = Byte2String & ChrW((((b1 AND 28) / 4) * 256 + (b1 AND 3) * 64 + (b2 AND 63)))
i = i + 1
elseif AscB(MidB(bsString,i,1)) < 240 then
' Three bytes
b1 = AscB(MidB(bsString,i,1))
b2 = AscB(MidB(bsString,i+1,1))
b3 = AscB(MidB(bsString,i+2,1))
Byte2String = Byte2String & ChrW(((b1 AND 15) * 16 + (b2 AND 60)) * 256 + (b2 AND 3) * 64 + (b3 AND 63))
i = i + 2
else
' Four bytes
b1 = AscB(MidB(bsString,i,1))
b2 = AscB(MidB(bsString,i+1,1))
b3 = AscB(MidB(bsString,i+2,1))
b4 = AscB(MidB(bsString,i+3,1))
' Don't know how to handle this, I believe Microsoft doesn't support these characters so I replace them with a "^"
'Byte2String = Byte2String & ChrW(((b1 AND 3) * 64 + (b2 AND 63)) & "," & (((b1 AND 28) / 4) * 256 + (b1 AND 3) * 64 + (b2 AND 63)))
Byte2String = Byte2String & "^"
i = i + 3
end if
Next
End Function
End Class

Class UploadedFile
Public ContentType
Public Start
Public Length
Public Path
Private nameOfFile

' Need to remove characters that are valid in UNIX, but not in Windows
Public Property Let FileName(fN)
nameOfFile = fN
nameOfFile = SubstNoReg(nameOfFile, "\", "_")
nameOfFile = SubstNoReg(nameOfFile, "/", "_")
nameOfFile = SubstNoReg(nameOfFile, ":", "_")
nameOfFile = SubstNoReg(nameOfFile, "*", "_")
nameOfFile = SubstNoReg(nameOfFile, "?", "_")
nameOfFile = SubstNoReg(nameOfFile, """", "_")
nameOfFile = SubstNoReg(nameOfFile, "<", "_")
nameOfFile = SubstNoReg(nameOfFile, ">", "_")
nameOfFile = SubstNoReg(nameOfFile, "|", "_")
End Property

Public Property Get FileName()
FileName = nameOfFile
End Property

'Public Property Get FileN()ame
End Class


' Does not depend on RegEx, which is not available on older VBScript
' Is not recursive, which means it will not run out of stack space
Function SubstNoReg(initialStr, oldStr, newStr)
Dim currentPos, oldStrPos, skip
If IsNull(initialStr) Or Len(initialStr) = 0 Then
SubstNoReg = ""
ElseIf IsNull(oldStr) Or Len(oldStr) = 0 Then
SubstNoReg = initialStr
Else
If IsNull(newStr) Then newStr = ""
currentPos = 1
oldStrPos = 0
SubstNoReg = ""
skip = Len(oldStr)
Do While currentPos <= Len(initialStr)
oldStrPos = InStr(currentPos, initialStr, oldStr)
If oldStrPos = 0 Then
SubstNoReg = SubstNoReg & Mid(initialStr, currentPos, Len(initialStr) - currentPos + 1)
currentPos = Len(initialStr) + 1
Else
SubstNoReg = SubstNoReg & Mid(initialStr, currentPos, oldStrPos - currentPos) & newStr
currentPos = oldStrPos + skip
End If
Loop
End If
End Function

Function GetFileName(strSaveToPath, FileName)
'This function is used when saving a file to check there is not already a file with the same name so that you don't overwrite it.
'It adds numbers to the filename e.g. file.gif becomes file1.gif becomes file2.gif and so on.
'It keeps going until it returns a filename that does not exist.
'You could just create a filename from the ID field but that means writing the record - and it still might exist!
'N.B. Requires strSaveToPath variable to be available - and containing the path to save to
Dim Counter
Dim Flag
Dim strTempFileName
Dim FileExt
Dim NewFullPath
dim objFSO, p
Set objFSO = CreateObject("Scripting.FileSystemObject")
Counter = 0
p = instrrev(FileName, ".")
FileExt = mid(FileName, p+1)
strTempFileName = left(FileName, p-1)
NewFullPath = strSaveToPath & "\" & FileName
Flag = False

Do Until Flag = True
If objFSO.FileExists(NewFullPath) = False Then
Flag = True
GetFileName = Mid(NewFullPath, InstrRev(NewFullPath, "\") + 1)
Else
Counter = Counter + 1
NewFullPath = strSaveToPath & "\" & strTempFileName & Counter & "." & FileExt
End If
Loop
End Function
%>

+ 0
- 52
core/lib.ad.auth.asp View File

@@ -1,52 +0,0 @@
<%
'==========================
' AD_Auth_Class.asp
'==========================
Class AD_Auth_Class
Public DomainName ' e.g. yourdomain.local
Public ContainerDN ' e.g. DC=yourdomain,DC=local
Public Username
Public Password
Public ErrorMessage
Public IsAuthenticated
Public UserObject

Private Sub Class_Initialize()
IsAuthenticated = False
ErrorMessage = ""
Set UserObject = Nothing
End Sub

Public Function Authenticate()
On Error Resume Next

Dim ldapPath, userCredential
ldapPath = "LDAP://" & ContainerDN ' Must be DC=yourdomain,DC=local
userCredential = DomainName & "\" & Username

' Try to bind to Active Directory
Dim rootDSE : Set rootDSE = GetObject("LDAP:")
Set UserObject = rootDSE.OpenDSObject(ldapPath, userCredential, Password, 1)

If Err.Number <> 0 Then
ErrorMessage = "Authentication failed: " & Err.Description
IsAuthenticated = False
Set UserObject = Nothing
Else
IsAuthenticated = True
ErrorMessage = ""
End If

Authenticate = IsAuthenticated
On Error GoTo 0
End Function
End Class

dim AD_Auth_Class__Singleton
Function AdAuth()
if IsEmpty(AD_Auth_Class__Singleton) then
set AD_Auth_Class__Singleton = new AD_Auth_Class
end if
set AdAuth = AD_Auth_Class__Singleton
End Function
%>

+ 25
- 37
core/lib.crypto.helper.asp View File

@@ -1,45 +1,33 @@
<%
'=======================================================================================================================
' PASSWORD HELPERS (native G3CRYPTO: bcrypt)
'=======================================================================================================================
' Replaces the old PowerShell/SHA-256 shell-out, which cannot run on AxonASP/Linux and put the password on a
' command line. Stored hashes are bcrypt ("$2a$..."), so previously stored SHA-256 hashes will not verify; reset them.

Function HashPassword(password)
Dim shell, command, execObj, outputLine, result

' Create Shell Object
Set shell = CreateObject("WScript.Shell")

' Construct PowerShell Command

command = "cmd /c powershell -ExecutionPolicy Bypass -NoLogo -NoProfile -File """ & Server.MapPath(".") & "..\Core\hash_sha256.ps1"" -password " & password
' Execute Command
Set execObj = shell.Exec(command)
' Read Output
Do While Not execObj.StdOut.AtEndOfStream
outputLine = Trim(execObj.StdOut.ReadAll())
If outputLine <> "" Then
result = outputLine ' Capture the hash
End If
Loop

' Cleanup
Set shell = Nothing
Set execObj = Nothing

' Return the hash or error message
If result = "" Or Left(result, 5) = "ERROR" Then
HashPassword = result ' "ERROR: Hash not generated"
Else
HashPassword = result
End If
Dim crypto
Set crypto = Server.CreateObject("G3CRYPTO")
HashPassword = crypto.HashPassword(password)
Set crypto = Nothing
End Function

' Returns True when username exists in Users and password matches its stored hash.
Function CheckPassword(username, password)
Dim user,UsersRepository
Set UsersRepository = CreateRepository(conn, "Users", "UserId")
' Find User
Set User = UsersRepository.Find(Array("UserName", user), Empty)
If user Is Nothing Then Exit Function ' Implicitly returns False
Dim crypto, rs, storedHash
CheckPassword = False

Set rs = DAL().Query("SELECT PasswordHash FROM Users WHERE UserName = ?", username)
If rs.EOF Then
rs.Close
Exit Function
End If
storedHash = "" & rs("PasswordHash")
rs.Close
Set rs = Nothing

' Compare Hashed Password
CheckPassword = (HashPassword(password) = user.PasswordHash)
Set crypto = Server.CreateObject("G3CRYPTO")
CheckPassword = crypto.VerifyPassword(password, storedHash)
Set crypto = Nothing
End Function
%>
%>

+ 0
- 284
core/lib.json.asp View File

@@ -1,284 +0,0 @@
<%
'January 2021 - Version 1.1 by Gerrit van Kuipers
Class aspJSON
Public data
Private p_JSONstring
Private aj_in_string, aj_in_escape, aj_i_tmp, aj_char_tmp, aj_s_tmp, aj_line_tmp, aj_line, aj_lines, aj_currentlevel, aj_currentkey, aj_currentvalue, aj_newlabel, aj_XmlHttp, aj_RegExp, aj_colonfound

Private Sub Class_Initialize()
Set data = Collection()

Set aj_RegExp = New regexp
aj_RegExp.Pattern = "\s{0,}(\S{1}[\s,\S]*\S{1})\s{0,}"
aj_RegExp.Global = False
aj_RegExp.IgnoreCase = True
aj_RegExp.Multiline = True
End Sub

Private Sub Class_Terminate()
Set data = Nothing
Set aj_RegExp = Nothing
End Sub

Public Sub loadJSON(inputsource)
inputsource = aj_MultilineTrim(inputsource)
If Len(inputsource) = 0 Then Err.Raise 1, "loadJSON Error", "No data to load."
Select Case Left(inputsource, 1)
Case "{", "["
Case Else
Set aj_XmlHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
aj_XmlHttp.open "POST", inputsource, False
aj_XmlHttp.setRequestHeader "Content-Type", "text/json"
aj_XmlHttp.setRequestHeader "CharSet", "UTF-8"
aj_XmlHttp.Send
inputsource = aj_XmlHttp.responseText
Set aj_XmlHttp = Nothing
End Select

p_JSONstring = CleanUpJSONstring(inputsource)
aj_lines = Split(p_JSONstring, Chr(13) & Chr(10))

Dim level(99)
aj_currentlevel = 1
Set level(aj_currentlevel) = data
For Each aj_line In aj_lines
aj_currentkey = ""
aj_currentvalue = ""
If Instr(aj_line, ":") > 0 Then
aj_in_string = False
aj_in_escape = False
aj_colonfound = False
For aj_i_tmp = 1 To Len(aj_line)
If aj_in_escape Then
aj_in_escape = False
Else
Select Case Mid(aj_line, aj_i_tmp, 1)
Case """"
aj_in_string = Not aj_in_string
Case ":"
If Not aj_in_escape And Not aj_in_string Then
aj_currentkey = Left(aj_line, aj_i_tmp - 1)
aj_currentvalue = Mid(aj_line, aj_i_tmp + 1)
aj_colonfound = True
Exit For
End If
Case "\"
aj_in_escape = True
End Select
End If
Next
if aj_colonfound then
aj_currentkey = aj_Strip(aj_JSONDecode(aj_currentkey), """")
If Not level(aj_currentlevel).exists(aj_currentkey) Then level(aj_currentlevel).Add aj_currentkey, ""
end if
End If
If right(aj_line,1) = "{" Or right(aj_line,1) = "[" Then
If Len(aj_currentkey) = 0 Then aj_currentkey = level(aj_currentlevel).Count
Set level(aj_currentlevel).Item(aj_currentkey) = Collection()
Set level(aj_currentlevel + 1) = level(aj_currentlevel).Item(aj_currentkey)
aj_currentlevel = aj_currentlevel + 1
aj_currentkey = ""
ElseIf right(aj_line,1) = "}" Or right(aj_line,1) = "]" or right(aj_line,2) = "}," Or right(aj_line,2) = "]," Then
aj_currentlevel = aj_currentlevel - 1
ElseIf Len(Trim(aj_line)) > 0 Then
If Len(aj_currentvalue) = 0 Then aj_currentvalue = aj_line
aj_currentvalue = getJSONValue(aj_currentvalue)

If Len(aj_currentkey) = 0 Then aj_currentkey = level(aj_currentlevel).Count
level(aj_currentlevel).Item(aj_currentkey) = aj_currentvalue
End If
Next
End Sub

Public Function Collection()
Set Collection = Server.CreateObject("Scripting.Dictionary")
End Function

Public Function AddToCollection(dictobj)
If TypeName(dictobj) <> "Dictionary" Then Err.Raise 1, "AddToCollection Error", "Not a collection."
aj_newlabel = dictobj.Count
dictobj.Add aj_newlabel, Collection()
Set AddToCollection = dictobj.item(aj_newlabel)
end function

Private Function CleanUpJSONstring(aj_originalstring)
aj_originalstring = Replace(aj_originalstring, Chr(13) & Chr(10), "")
aj_originalstring = Mid(aj_originalstring, 2, Len(aj_originalstring) - 2)
aj_in_string = False : aj_in_escape = False : aj_s_tmp = ""
For aj_i_tmp = 1 To Len(aj_originalstring)
aj_char_tmp = Mid(aj_originalstring, aj_i_tmp, 1)
If aj_in_escape Then
aj_in_escape = False
aj_s_tmp = aj_s_tmp & aj_char_tmp
Else
Select Case aj_char_tmp
Case "\" : aj_s_tmp = aj_s_tmp & aj_char_tmp : aj_in_escape = True
Case """" : aj_s_tmp = aj_s_tmp & aj_char_tmp : aj_in_string = Not aj_in_string
Case "{", "["
aj_s_tmp = aj_s_tmp & aj_char_tmp & aj_InlineIf(aj_in_string, "", Chr(13) & Chr(10))
Case "}", "]"
aj_s_tmp = aj_s_tmp & aj_InlineIf(aj_in_string, "", Chr(13) & Chr(10)) & aj_char_tmp
Case "," : aj_s_tmp = aj_s_tmp & aj_char_tmp & aj_InlineIf(aj_in_string, "", Chr(13) & Chr(10))
Case Else : aj_s_tmp = aj_s_tmp & aj_char_tmp
End Select
End If
Next

CleanUpJSONstring = ""
aj_s_tmp = Split(aj_s_tmp, Chr(13) & Chr(10))
For Each aj_line_tmp In aj_s_tmp
aj_line_tmp = Replace(Replace(aj_line_tmp, Chr(10), ""), Chr(13), "")
CleanUpJSONstring = CleanUpJSONstring & aj_Trim(aj_line_tmp) & Chr(13) & Chr(10)
Next
End Function

Private Function getJSONValue(ByVal val)
val = Trim(val)
If Left(val,1) = ":" Then val = Mid(val, 2)
If Right(val,1) = "," Then val = Left(val, Len(val) - 1)
val = Trim(val)

Select Case val
Case "true" : getJSONValue = True
Case "false" : getJSONValue = False
Case "null" : getJSONValue = Null
Case Else
If (Instr(val, """") = 0) Then
If IsNumeric(val) Then
getJSONValue = aj_ReadNumericValue(val)
Else
getJSONValue = val
End If
Else
If Left(val,1) = """" Then val = Mid(val, 2)
If Right(val,1) = """" Then val = Left(val, Len(val) - 1)
getJSONValue = aj_JSONDecode(Trim(val))
End If
End Select
End Function

Private JSONoutput_level
Public Function JSONoutput()
Dim wrap_dicttype, aj_label
JSONoutput_level = 1
wrap_dicttype = "[]"
For Each aj_label In data
If Not aj_IsInt(aj_label) Then wrap_dicttype = "{}"
Next
JSONoutput = Left(wrap_dicttype, 1) & Chr(13) & Chr(10) & GetDict(data) & Right(wrap_dicttype, 1)
End Function

Private Function GetDict(objDict)
Dim aj_item, aj_keyvals, aj_label, aj_dicttype
For Each aj_item In objDict
Select Case TypeName(objDict.Item(aj_item))
Case "Dictionary"
GetDict = GetDict & Space(JSONoutput_level * 4)
aj_dicttype = "[]"
For Each aj_label In objDict.Item(aj_item).Keys
If Not aj_IsInt(aj_label) Then aj_dicttype = "{}"
Next
If aj_IsInt(aj_item) Then
GetDict = GetDict & (Left(aj_dicttype,1) & Chr(13) & Chr(10))
Else
GetDict = GetDict & ("""" & aj_JSONEncode(aj_item) & """" & ": " & Left(aj_dicttype,1) & Chr(13) & Chr(10))
End If
JSONoutput_level = JSONoutput_level + 1
aj_keyvals = objDict.Keys
GetDict = GetDict & (GetSubDict(objDict.Item(aj_item)) & Space(JSONoutput_level * 4) & Right(aj_dicttype,1) & aj_InlineIf(aj_item = aj_keyvals(objDict.Count - 1),"" , ",") & Chr(13) & Chr(10))
Case Else
aj_keyvals = objDict.Keys
GetDict = GetDict & (Space(JSONoutput_level * 4) & aj_InlineIf(aj_IsInt(aj_item), "", """" & aj_JSONEncode(aj_item) & """: ") & WriteValue(objDict.Item(aj_item)) & aj_InlineIf(aj_item = aj_keyvals(objDict.Count - 1),"" , ",") & Chr(13) & Chr(10))
End Select
Next
End Function

Private Function aj_IsInt(val)
aj_IsInt = (TypeName(val) = "Integer" Or TypeName(val) = "Long")
End Function

Private Function GetSubDict(objSubDict)
GetSubDict = GetDict(objSubDict)
JSONoutput_level= JSONoutput_level -1
End Function

Private Function WriteValue(ByVal val)
Select Case TypeName(val)
Case "Double", "Integer", "Long": WriteValue = replace(val, ",", ".")
Case "Null" : WriteValue = "null"
Case "Boolean" : WriteValue = aj_InlineIf(val, "true", "false")
Case Else : WriteValue = """" & aj_JSONEncode(val) & """"
End Select
End Function

Private Function aj_JSONEncode(ByVal val)
val = Replace(val, "\", "\\")
val = Replace(val, """", "\""")
'val = Replace(val, "/", "\/")
val = Replace(val, Chr(8), "\b")
val = Replace(val, Chr(12), "\f")
val = Replace(val, Chr(10), "\n")
val = Replace(val, Chr(13), "\r")
val = Replace(val, Chr(9), "\t")
aj_JSONEncode = Trim(val)
End Function

Private Function aj_JSONDecode(ByVal val)
val = Replace(val, "\""", """")
val = Replace(val, "\\", "\")
val = Replace(val, "\/", "/")
val = Replace(val, "\b", Chr(8))
val = Replace(val, "\f", Chr(12))
val = Replace(val, "\n", Chr(10))
val = Replace(val, "\r", Chr(13))
val = Replace(val, "\t", Chr(9))
aj_JSONDecode = Trim(val)
End Function

Private Function aj_InlineIf(condition, returntrue, returnfalse)
If condition Then aj_InlineIf = returntrue Else aj_InlineIf = returnfalse
End Function

Private Function aj_Strip(ByVal val, stripper)
If Left(val, 1) = stripper Then val = Mid(val, 2)
If Right(val, 1) = stripper Then val = Left(val, Len(val) - 1)
aj_Strip = val
End Function

Private Function aj_MultilineTrim(TextData)
aj_MultilineTrim = aj_RegExp.Replace(TextData, "$1")
End Function

Private Function aj_Trim(val)
aj_Trim = Trim(val)
Do While Left(aj_Trim, 1) = Chr(9) : aj_Trim = Mid(aj_Trim, 2) : Loop
Do While Right(aj_Trim, 1) = Chr(9) : aj_Trim = Left(aj_Trim, Len(aj_Trim) - 1) : Loop
aj_Trim = Trim(aj_Trim)
End Function

Private Function aj_ReadNumericValue(ByVal val)
If Instr(val, ".") > 0 Then
numdecimals = Len(val) - Instr(val, ".")
val = Clng(Replace(val, ".", ""))
val = val / (10 ^ numdecimals)
aj_ReadNumericValue = val
Else
aj_ReadNumericValue = Clng(val)
End If
End Function
End Class

dim json_Class__Singleton
Function json()
if IsEmpty(json_Class__Singleton) then
set json_Class__Singleton = new aspJSON
end if
set json = json_Class__Singleton
End Function



%>

+ 6
- 5
core/mvc.asp View File

@@ -1,4 +1,5 @@
<!--#include file="../app/Controllers/autoload_controllers.asp" -->
<!--#include file="../app/models/autoload_models.asp" -->
<!--#include file="../app/controllers/autoload_controllers.asp" -->
<%
' Set cache expiration from configuration
Dim cacheYear : cacheYear = GetAppSetting("CacheExpirationYear")
@@ -23,13 +24,13 @@ Class MVC_Dispatcher_Class
'---------------------------------------------------------------------------------------------------------------------
Public Sub DispatchRequest(method, path)
Dim routeArray
routeArray = router.Resolve(method, path)
routeArray = GetRouter().Resolve(method, path)
Dispatch routeArray
End Sub

'---------------------------------------------------------------------------------------------------------------------
' Main dispatch method - executes a resolved route
' RouteArray: Array(controller, action, params) from router.Resolve()
' RouteArray: Array(controller, action, params) from GetRouter().Resolve()
'---------------------------------------------------------------------------------------------------------------------
Public Sub Dispatch(RouteArray)
On Error Resume Next
@@ -67,7 +68,7 @@ Class MVC_Dispatcher_Class
' Check if layout should be used
hasParams = (UBound(RouteArray) >= 2)
If eval(controllerName & ".useLayout") Then
%> <!-- #include file="../app/views/Shared/Header.asp" --> <%
%> <!-- #include file="../app/views/shared/header.asp" --> <%
End If

' Prepare parameters
@@ -82,7 +83,7 @@ Class MVC_Dispatcher_Class

' Include footer if layout is used
If eval(controllerName & ".useLayout") Then
%> <!-- #include file="../app/views/Shared/Footer.asp" --> <%
%> <!-- #include file="../app/views/shared/footer.asp" --> <%
End If
On Error GoTo 0
End Sub


+ 0
- 0
db/migrations/.gitkeep View File


+ 0
- 23
db/migrations/20260324110000_add_do_not_call_fields_to_households.asp View File

@@ -1,23 +0,0 @@
<%
'=======================================================================================================================
' MIGRATION: add_do_not_call_fields_to_households
'=======================================================================================================================

Sub Migration_Up(migration)
migration.AddColumn "Households", "DoNotCall", "SMALLINT"
migration.AddColumn "Households", "DoNotCallDate", "DATETIME"
migration.AddColumn "Households", "DoNotCallNotes", "LONGTEXT"
migration.AddColumn "Households", "DoNotCallPrivateNotes", "LONGTEXT"

migration.ExecuteSQL "UPDATE Households SET DoNotCall = 0 WHERE DoNotCall IS NULL"
migration.CreateIndex "IX_Households_DoNotCall", "Households", "DoNotCall"
End Sub

Sub Migration_Down(migration)
migration.DropIndex "IX_Households_DoNotCall", "Households"
migration.DropColumn "Households", "DoNotCallPrivateNotes"
migration.DropColumn "Households", "DoNotCallNotes"
migration.DropColumn "Households", "DoNotCallDate"
migration.DropColumn "Households", "DoNotCall"
End Sub
%>

BIN
db/webdata.accdb View File


+ 0
- 1543
docs/AGENTS.md
File diff suppressed because it is too large
View File


+ 0
- 994
docs/CLAUDE.md View File

@@ -1,994 +0,0 @@
# CLAUDE.md

## Purpose

This file defines how Claude and Claude-compatible coding agents should operate in this repository.

Read `AGENTS.md` first.

`AGENTS.md` is the primary development policy.

This file defines agent workflow, reasoning discipline, project learning, and self-improvement behavior.

---

# 1. Startup Procedure

At the beginning of a development task:

1. Read `AGENTS.md`.
2. Read this `CLAUDE.md`.
3. Inspect relevant files before editing.
4. Search the repository for similar implementations.
5. Identify existing helpers and abstractions.
6. Determine the affected architectural layers.
7. Identify security-sensitive boundaries.
8. Identify tests relevant to the change.

Do not immediately generate a new abstraction before understanding the existing project.

---

# 2. Treat VBScript as a Language Requiring Agent-Level Static Analysis

VBScript lacks many safeguards found in modern compiled languages.

Therefore, while working, actively inspect for:

```text
undeclared variables
misspelled identifiers
missing Set
wrong argument counts
implicit Variant conversions
Null propagation
Empty values
Nothing references
unexpected ByRef mutation
invalid function return paths
unsafe SQL
unsafe HTML output
broad error suppression
resource leaks
global-state coupling
```

Act as a compiler substitute.

---

# 3. Think in Boundaries

Before changing code, determine which layer owns the behavior.

Preferred direction:

```text
Request
↓
Controller
↓
Service
↓
Repository
↓
Database
```

Views should receive prepared data.

Do not bypass layers for convenience.

---

# 4. Avoid Architectural Drift

When adding functionality, prefer the project's existing good pattern.

Do not create:

```text
CustomerManager
CustomerHandler
CustomerEngine
CustomerProcessor
CustomerHelper
```

if `CustomerService` already represents the business layer.

Reuse terminology consistently.

---

# 5. Search Before Creating

Before creating:

- a helper
- service
- repository
- validator
- utility
- model
- WSC component
- framework function

search for an existing implementation.

Prefer extending an existing appropriate abstraction over creating duplicates.

---

# 6. Make Small Changes

Prefer the smallest coherent change that solves the problem.

Avoid unrelated cleanup unless necessary.

If a task exposes a larger architectural problem:

1. solve the requested problem safely
2. document the larger concern
3. improve the architecture when justified

Do not turn every bug fix into a rewrite.

---

# 7. Never Hide Errors to Make Code Appear Functional

Do not use broad:

```vbscript
On Error Resume Next
```

to make failures disappear.

Errors should be:

```text
prevented
handled
logged
or propagated
```

Never silently swallowed.

---

# 8. Security Review Is Mandatory

For each change involving input, output, authentication, database access, file handling, or state changes, inspect for:

```text
SQL injection
XSS
CSRF
authorization bypass
open redirects
path traversal
unsafe file upload
sensitive logging
session misuse
```

Security checks are not optional even if the user did not explicitly request them.

---

# 9. SQL Generation

Always prefer parameterized ADODB commands.

If existing code concatenates SQL, do not copy the unsafe pattern into new code.

When touching the unsafe section directly, improve it if doing so is reasonably scoped and compatibility can be preserved.

---

# 10. HTML Generation

Dynamic text should be HTML encoded by default.

Do not output raw Request or database values into HTML.

When raw HTML is intentionally supported, make that trust boundary explicit.

---

# 11. Validate at the Boundary

Convert raw external values into trusted application values early.

Think:

```text
Raw Request value
↓
Trim / normalize
↓
Required check
↓
Format validation
↓
Type conversion
↓
Business validation
↓
Use
```

Do not allow raw Request values to flow deeply through the system.

---

# 12. Prefer Explicit Code

In VBScript, explicit code is usually safer than clever code.

Prefer:

```vbscript
Dim customerId
customerId = CLng(value)
```

over relying on automatic coercion.

Prefer clear control flow over compressed expressions.

---

# 13. Functions and Procedures

Keep procedures focused.

If a function performs several unrelated operations, extract meaningful collaborators.

Prefer names that describe intent.

Bad:

```text
ProcessData
HandleStuff
DoWork
RunThing
```

Better:

```text
ValidateCustomer
CalculateOrderTotal
LoadCustomerById
SaveAppointment
```

---

# 14. ByVal and ByRef

Remember:

VBScript defaults parameters to `ByRef`.

When mutation is not intended, prefer:

```vbscript
ByVal
```

Use `ByRef` only when caller mutation is intentional.

Review changed method signatures for accidental ByRef behavior.

---

# 15. Object Assignment

Remember that object assignment requires `Set`.

Review every new or modified object assignment.

Example:

```vbscript
Set service = New CustomerService
```

not:

```vbscript
service = New CustomerService
```

---

# 16. Function Return Values

VBScript functions return values by assigning to their own name.

Review all paths.

Example:

```vbscript
Function IsAllowed(ByVal userId)

If userId <= 0 Then
IsAllowed = False
Exit Function
End If

IsAllowed = True

End Function
```

Do not accidentally leave an important return value as Empty.

---

# 17. COM and ADODB Cleanup

When creating:

- ADODB.Connection
- ADODB.Command
- ADODB.Recordset
- filesystem objects
- external COM components

understand ownership and cleanup behavior.

Explicitly close database resources when appropriate.

Set references to `Nothing` when ownership ends.

---

# 18. Avoid Global State

Prefer explicit dependencies.

Do not add Session or Application state merely because it is convenient.

Ask:

```text
Does this value truly need to survive across requests?
```

If not, keep it request-scoped.

---

# 19. Testing Strategy

When possible, isolate business logic from ASP globals.

Favor code that can be invoked with plain VBScript values or mock collaborators.

When fixing a defect, add a regression test where practical.

---

# 20. Comments

Comments should explain:

```text
why
constraints
non-obvious behavior
compatibility requirements
security rationale
```

Do not add comments that merely repeat the code.

Bad:

```vbscript
' Set customer id
customerId = 10
```

Useful:

```vbscript
' Legacy import files use 0 to represent an unknown customer.
If customerId = 0 Then
```

---

# 21. Preserve Valuable Legacy Behavior

ASP Classic projects may contain old but important behavior.

Do not assume unfamiliar code is wrong.

Before removing or replacing something:

1. search references
2. understand callers
3. identify side effects
4. inspect related documentation
5. preserve compatibility where required

---

# 22. Self-Improvement

This repository is designed to allow agents to improve their own operating instructions.

Self-improvement should make future work:

- safer
- more consistent
- easier to verify
- less repetitive
- more maintainable

Do not change instructions merely to suit the current implementation.

Improve the implementation when practical rather than weakening good rules.

---

# 23. Detect Learnable Events

A learnable event occurs when:

- a repeated bug appears
- a review catches the same mistake repeatedly
- a new reusable pattern proves successful
- a project architecture decision becomes permanent
- a new security requirement becomes necessary
- a repeated workflow can be standardized
- a user establishes a lasting convention
- an existing instruction becomes inaccurate

When a learnable event occurs, determine whether project documentation should change.

---

# 24. Where Learning Should Go

Use the smallest appropriate scope.

Update:

```text
AGENTS.md
```

for project-wide durable policies.

Update:

```text
CLAUDE.md
```

for agent workflow and Claude-specific operating behavior.

Update:

```text
/docs/*
```

for architectural or project documentation.

Update:

```text
/skills/*
```

for reusable specialized procedures.

Update source-code comments only for code-local constraints.

Do not place every lesson into AGENTS.md.

---

# 25. Self-Update Decision

Before modifying an instruction file, ask:

```text
Is this lesson likely to matter again?
```

If no, do not persist it.

Then ask:

```text
Is this project-wide?
```

If yes, consider AGENTS.md.

Otherwise use a specialized document.

---

# 26. Never Self-Weaken Core Safety Rules

Claude must not autonomously remove or weaken requirements involving:

```text
Option Explicit
parameterized SQL
server-side authorization
input validation
output encoding
safe error handling
resource cleanup
secret protection
```

If an unusual project requirement appears to conflict with one of these rules, preserve safety and document the conflict.

---

# 27. Avoid Instruction Inflation

Do not add a new rule for every isolated mistake.

Prefer:

```text
general principle
+
reusable example
```

rather than hundreds of hyper-specific rules.

A rule should prevent a category of mistakes.

---

# 28. Improve Through Abstractions Too

Not every lesson belongs in documentation.

If the same safety requirement appears repeatedly, consider encoding it into the framework.

Examples:

```text
Safe HTML helper
Parameterized database wrapper
Request conversion helper
Validation library
Authorization service
Logging wrapper
Repository base conventions
```

The best rule is sometimes one the architecture makes difficult to violate.

---

# 29. Skill Creation

Claude may create a new skill when the task is:

- specialized
- recurring
- procedural
- reusable across multiple features

Possible skills:

```text
/skills/asp-classic-controller.md
/skills/adodb-repository.md
/skills/sql-parameterization.md
/skills/security-review.md
/skills/vbscript-static-review.md
/skills/testing.md
```

Do not create a skill for a one-time task.

---

# 30. Suggested Skill Format

Each skill should contain:

```text
# Skill Name

## Purpose

## Use When

## Inputs

## Procedure

## Required Rules

## Validation Checklist

## Common Mistakes

## Output

## Improvement Notes
```

---

# 31. Agent Review Loop

For meaningful tasks, use this cycle:

```text
Understand
↓
Inspect
↓
Design
↓
Implement
↓
Review
↓
Test
↓
Learn
```

The `Learn` step asks whether the repository's instructions or abstractions should improve.

---

# 32. Design Before Implementation

For significant changes, identify:

```text
affected layers
new components
existing components
data flow
validation boundaries
security boundaries
failure behavior
testing strategy
```

before writing substantial code.

For small tasks, keep this lightweight.

---

# 33. Avoid Premature Framework Expansion

Do not add framework components simply because another language would have them.

ASP Classic should remain simple.

Only introduce an abstraction when it solves a real recurring problem.

---

# 34. Prefer Composition

When extending behavior, first consider:

```text
small object
+
small collaborator
```

instead of large pseudo-inheritance systems.

VBScript is better suited to simple composition.

---

# 35. Stable Public Contracts

Treat established routes, APIs, class methods, and database contracts carefully.

When changing them:

1. search callers
2. assess compatibility
3. update all consumers
4. document breaking changes

Avoid accidental interface changes.

---

# 36. Database Changes

For schema changes, consider:

```text
backward compatibility
migration order
existing data
Null behavior
indexes
constraints
application deployment timing
rollback implications
```

Do not modify schema casually.

---

# 37. Performance Review

When working with database code, look for:

```text
queries inside loops
SELECT *
unnecessary recordset traversal
missing filters
repeated connection creation
large Session values
unbounded result sets
unnecessary COM calls
```

Prefer database-side filtering and set operations.

---

# 38. Request Lifecycle Awareness

Remember that ASP Classic operates per request.

Avoid assumptions that local variables persist between requests.

Use Session or persistent storage only when the application truly requires cross-request state.

---

# 39. Application Lifecycle Awareness

`Application` state is global to the ASP application.

Do not store user-specific data there.

Be mindful of concurrent requests.

---

# 40. Avoid Hidden Dependencies

A component should not unexpectedly require:

```text
Request
Response
Session
Application
global connection object
global logger
global configuration
```

unless that dependency is part of the documented architecture.

Prefer passing dependencies explicitly.

---

# 41. Compatibility First During Refactoring

When modernizing legacy code:

```text
First preserve behavior.
Then improve structure.
```

Avoid combining major behavior changes with major refactors unless necessary.

---

# 42. Repository Review After Significant Changes

After a meaningful feature or refactor, search for:

- outdated documentation
- duplicate helpers
- now-dead code
- inconsistent naming
- old patterns replaced by the new pattern
- opportunities to update an existing skill

Keep the repository internally consistent.

---

# 43. Learn From User Corrections

If the user corrects Claude on a durable project convention, treat that as a possible learnable event.

Examples:

```text
"We always use this router."
"Repositories never return recordsets."
"All AJAX endpoints use this response format."
"Use WSC components for controllers."
```

If the instruction is durable, update the appropriate project guidance.

Do not persist one-time preferences as permanent architecture rules.

---

# 44. Change Documentation Conservatively

When modifying AGENTS.md, CLAUDE.md, or skills:

- preserve useful existing rules
- remove duplicates
- clarify contradictions
- avoid unnecessary rewrites
- add an update-history entry where appropriate

Instruction files should become clearer over time, not merely longer.

---

# 45. Conflict Detection

If project documentation contradicts itself:

1. identify the conflict
2. use higher-priority instructions
3. resolve the contradiction where safe
4. update documentation so future agents do not face the same conflict

Do not silently choose different interpretations from task to task.

---

# 46. Self-Improvement Is Not Autonomous Product Redesign

Claude may improve:

```text
guidelines
skills
documentation
developer workflow
internal abstractions
```

when justified.

Claude must not independently redefine:

```text
business requirements
user-visible behavior
pricing
authorization policy
data retention policy
major architecture goals
```

without task requirements supporting the change.

---

# 47. Final Review Mode

Before completing a task, temporarily switch from implementation thinking to adversarial review.

Ask:

```text
How could this fail?

What would VBScript fail to warn me about?

What input breaks this?

What happens with Null?

What happens with Empty?

What happens with Nothing?

Did I forget Set?

Could ByRef change the caller?

Could SQL injection occur?

Could XSS occur?

Could authorization be bypassed?

Could an error be swallowed?

Could a recordset remain open?

Did I accidentally duplicate existing functionality?
```

Fix issues found before finishing.

---

# 48. Final Summary

When reporting completed coding work, mention material items such as:

```text
what changed
important architecture choices
tests performed
security implications
documentation or rule updates
remaining limitations
```

Do not produce long explanations for trivial changes.

---

# 49. Core Philosophy

Claude should help make ASP Classic behave like a disciplined modern development environment without destroying the language's simplicity.

The goal is not to turn VBScript into C#.

The goal is to provide the safeguards that VBScript lacks.

Think:

```text
VBScript
+
clear architecture
+
strict conventions
+
reusable framework components
+
agent-level static analysis
+
continuous learning
=
reliable ASP Classic development
```

---

# Update History

2026-09-02
- Initial Claude operating instructions created.
- Added VBScript static-review behavior.
- Added controlled self-improvement workflow.
- Added learnable-event detection and skill creation guidance.

BIN
docs/Windows scripting secrets.pdf View File


+ 0
- 63
docs/api-contracts-mvc-starter.md View File

@@ -1,63 +0,0 @@
# API Contracts - MVC-Starter

**Date:** 2026-03-11T11:59:39Z

## Overview

This project does not expose a standalone JSON API. Its current externally reachable contracts are server-rendered HTTP routes handled by the Classic ASP MVC dispatcher.

## Route Catalog

### `GET /`

- **Controller:** `homeController`
- **Action:** `Index`
- **Behavior:** Renders the home page using the shared layout and `app/views/Home/index.asp`.
- **Layout:** enabled (`useLayout = True`)
- **Response Type:** HTML
- **Status:** `200 OK`

### `GET /home`

- **Controller:** `homeController`
- **Action:** `Index`
- **Behavior:** Alias route to the home page; renders the same content as `/`.
- **Layout:** enabled
- **Response Type:** HTML
- **Status:** `200 OK`

### `GET ""` (empty path fallback)

- **Controller:** `homeController`
- **Action:** `Index`
- **Behavior:** Additional root-path fallback route declared in `public/Default.asp`.
- **Layout:** enabled
- **Response Type:** HTML
- **Status:** `200 OK`

### `GET /404`

- **Controller:** `ErrorController`
- **Action:** `NotFound`
- **Behavior:** Renders the not-found page and sets the response status to `404 Not Found`.
- **Layout:** enabled
- **Response Type:** HTML
- **Status:** `404 Not Found`

## Dispatch Contract

- All non-static requests are rewritten by IIS to `public/Default.asp`.
- `public/Default.asp` registers routes and calls `MVC.DispatchRequest`.
- `core/mvc.asp` validates controller and action names, checks the controller whitelist, resolves the controller dynamically, and invokes the action.
- If `useLayout` is enabled on the resolved controller, shared header and footer views wrap the response.

## Security and Validation Notes

- Controller names must pass format validation and whitelist checks in `core/lib.ControllerRegistry.asp`.
- Action names must pass identifier validation before dispatch.
- Current route handling is page-oriented; there are no documented JSON payload schemas or standalone API auth flows in the application itself.

## Brownfield Notes

- Future endpoint additions require updates in at least three places: route registration, controller include/implementation, and controller whitelist registration.
- This document reflects route contracts, not REST-style service endpoints.

+ 0
- 34
docs/architecture-patterns.md View File

@@ -1,34 +0,0 @@
# Architecture Patterns

**Date:** 2026-03-11T11:59:39Z

## Part: MVC-Starter

### Primary Architecture Pattern

Server-rendered MVC monolith with a starter/framework hybrid structure: IIS and `public/` handle request entry, `core/` provides shared runtime and dispatch behavior, and `app/` provides project-specific extensions.

## Pattern Breakdown

- **End-to-end request path:** IIS URL Rewrite sends requests to `public/Default.asp`, routes are registered there, the router resolves controller/action/params, `core/mvc.asp` validates and dispatches, and shared layout files wrap output when `useLayout` is enabled.
- **Routing pattern:** Routes are declared centrally in `public/Default.asp` and resolved through the RouteKit router object.
- **Dispatch pattern:** `core/mvc.asp` uses validation, controller whitelisting, and dynamic execution to resolve the current controller and action.
- **Application layering:** `core/` contains reusable framework/runtime behavior, while `app/` contains project-specific controllers, views, models, and repositories.
- **Rendering pattern:** Controllers orchestrate and include `.asp` view files; shared header/footer layout files provide common page chrome.
- **Data pattern:** Data access is config-driven through `public/web.config`, with DAL libraries and generator-assisted repositories/POBOs supporting database interaction.
- **Operational tooling pattern:** Schema and scaffolding workflows are handled by standalone VBScript tools under `scripts/`.

## Architectural Implications

- This codebase is optimized around a single IIS-hosted deployable unit rather than separable services.
- Framework bootstrapping and request dispatch are centralized, so edits to `public/` entry files or `core/` runtime files have broad impact.
- Dynamic dispatch is part of the framework design, which makes naming, registration, and validation rules part of the architecture contract.
- Feature development typically extends existing seams in `app/`, `db/`, and `scripts/` rather than introducing new application subsystems.
- The architecture assumes server-side HTML rendering and config-driven runtime behavior rather than client-heavy SPA patterns.

## Brownfield Notes

- The most important architectural boundary is between the framework/runtime layer (`core/`) and the app extension layer (`app/`).
- Controller activation is not automatic; routing, include registration, and whitelist registration are all part of the runtime contract.
- Windows/IIS hosting is part of the architecture, not just deployment detail, because request flow and configuration depend on it.
- Generator scripts are part of the implementation model, not just convenience tooling.

+ 0
- 81
docs/architecture.md View File

@@ -1,81 +0,0 @@
# MVC-Starter - Architecture

**Date:** 2026-03-11T11:59:39Z
**Project Type:** web
**Architecture:** Server-rendered MVC monolith

## Executive Summary

MVC-Starter is a Classic ASP starter application built around a single IIS-hosted deployable unit. Requests enter through `public/Default.asp`, flow through a shared runtime in `core/`, and resolve into application-specific controllers and views under `app/`.

## Technology Stack

- Classic ASP / VBScript
- Windows IIS with URL Rewrite
- RouteKit-style router and MVC dispatcher
- Microsoft Access via ACE OLE DB
- Bootstrap 5.3.3 and Bootstrap Icons 1.11.3 from CDN
- VBScript tooling for scaffolding and migrations

## Architecture Pattern

Starter/framework hybrid MVC monolith:

- `public/` handles web entry and IIS-facing config
- `core/` handles routing, dispatch, validation, helpers, and DAL concerns
- `app/` contains project-specific behavior and server-rendered views
- `db/` and `scripts/` support data and operational workflows

## Request Flow

1. IIS receives the request.
2. `public/web.config` rewrites non-static requests to `public/Default.asp`.
3. `Default.asp` registers routes and calls `MVC.DispatchRequest`.
4. `core/mvc.asp` validates controller/action names, checks whitelist registration, resolves the current controller dynamically, and executes the target action.
5. Shared layout files wrap the response if `useLayout` is enabled.

## Data Architecture

- Database configuration is read from `public/web.config`.
- `db/webdata.accdb` is the included Access database.
- DAL and migration helpers live in `core/`.
- Repositories and POBOs are expected to be generated via `scripts/GenerateRepo.vbs`.

## Component Overview

- Controllers: `app/controllers/`
- Views: `app/views/`
- Shared layout: `app/views/shared/`
- Runtime/framework: `core/`
- Scaffolding/tooling: `scripts/`

## Source Tree

See [source-tree-analysis.md](./source-tree-analysis.md) for the annotated directory breakdown.

## Development Workflow

- Generate migration
- Generate POBO/repository
- Generate controller
- Register controller include, whitelist, and routes
- Add views and validate via IIS-hosted execution

## Deployment Architecture

- Single IIS site
- `public/` as web root
- XML config in `public/web.config`
- No separate service/process topology detected

## Testing Strategy

- No automated test framework detected
- Manual request-flow verification is required
- Script tooling can be validated via `cscript`

## Architectural Constraints

- Dynamic dispatch means naming and registration consistency are part of runtime correctness.
- `core/`, `public/Default.asp`, and `public/web.config` are high-impact files.
- The architecture assumes Windows/IIS hosting rather than cross-platform portability.

+ 0
- 63
docs/component-inventory.md View File

@@ -1,63 +0,0 @@
# MVC-Starter - Component Inventory

**Date:** 2026-03-11T11:59:39Z

## Runtime and MVC Components

### Front Controller

- `public/Default.asp`
- Registers routes
- Boots runtime
- Dispatches requests

### Dispatcher

- `core/mvc.asp`
- Validates controller/action names
- Enforces controller whitelist
- Wraps responses in shared layout when enabled

### Controller Registry

- `core/lib.ControllerRegistry.asp`
- Tracks valid controllers
- Prevents arbitrary controller execution

### Controllers

- `app/controllers/HomeController.asp`
- Home page controller
- `app/controllers/ErrorController.asp`
- 404/not-found handling

## UI/View Components

### Shared Layout

- `app/views/shared/header.asp`
- `app/views/shared/footer.asp`

### Feature Views

- `app/views/Home/index.asp`
- `app/views/Error/NotFound.asp`

## Data/Operational Components

### Database Assets

- `db/webdata.accdb`

### Script Tooling

- `scripts/generateController.vbs`
- `scripts/GenerateRepo.vbs`
- `scripts/generateMigration.vbs`
- `scripts/runMigrations.vbs`

## Reuse Notes

- The main reusable UI surface is the shared layout.
- The main reusable runtime surface is the `core/` library set.
- The data layer is scaffold-oriented and currently has no committed application-specific model/repository classes.

+ 0
- 46
docs/comprehensive-analysis-mvc-starter.md View File

@@ -1,46 +0,0 @@
# Comprehensive Analysis - MVC-Starter

**Date:** 2026-03-11T11:59:39Z

## Configuration Management

- Primary runtime configuration lives in `public/web.config`.
- Important settings include database connection, environment mode, flash timing, 404 redirect timing, cache controls, and error logging paths.
- Configuration is read in application code through helper accessors such as `GetAppSetting`.

## Authentication and Security

- No full authentication subsystem is present in the starter.
- The main observable security boundary is controller/action validation and controller whitelisting in `core/lib.ControllerRegistry.asp`.
- Dispatch also HTML-encodes some user-visible error output to reduce injection risk.

## Entry Points and Bootstrap

- IIS web root: `public/`
- Default document: `public/Default.asp`
- Runtime bootstrap include: `core/autoload_core.asp`
- Request dispatcher: `core/mvc.asp`

## Shared Code

- `core/` contains reusable framework/runtime libraries for routing, data access, flash messaging, forms, uploads, HTML helpers, validation, encryption helpers, and JSON support.
- `scripts/` contains operational generators and migration tooling.

## Event/Async Patterns

- No queue, worker, or event-bus architecture was detected.
- UI behavior is mostly server-rendered with small inline browser-side scripts where needed.

## CI/CD and Deployment

- No CI/CD pipeline configuration was detected.
- Deployment is IIS-based and documented in `README.md` and `public/web.config`.

## Localization

- No localization or i18n framework was detected.

## Testing Surface

- No automated test framework or test files were detected in the application code.
- Validation currently depends on manual runtime checks and script execution in a Windows/IIS environment.

+ 0
- 11
docs/critical-folders-summary.md View File

@@ -1,11 +0,0 @@
# Critical Folders Summary

**Date:** 2026-03-11T11:59:39Z

- `public/`: externally facing web root, rewrite config, and request bootstrap
- `core/`: framework/runtime internals, dispatcher, router, helpers, DAL, and security checks
- `app/controllers/`: project controller implementations and include-based activation surface
- `app/views/`: server-rendered feature views and shared layout
- `db/`: Access database and migration workspace
- `scripts/`: generator and migration tooling used during feature development
- `docs/`: generated brownfield documentation for future planning and AI-assisted work

+ 0
- 42
docs/data-models-mvc-starter.md View File

@@ -1,42 +0,0 @@
# Data Models - MVC-Starter

**Date:** 2026-03-11T11:59:39Z

## Overview

The repository includes a database file and data-access infrastructure, but it does not yet contain checked-in application model or repository source files under `app/models/` or `app/repositories/`.

## Current Data Assets

### Database File

- **Path:** `db/webdata.accdb`
- **Type:** Microsoft Access database
- **Configured Provider:** `Microsoft.ACE.OLEDB.12.0`
- **Configured From:** `public/web.config`

### Data Access Runtime

- **DAL libraries:** `core/lib.DAL.asp`, `core/lib.Data.asp`
- **Migration support:** `core/lib.Migrations.asp`
- **Repository/model generation:** `scripts/GenerateRepo.vbs`

## Schema and Model Strategy

- The intended model pattern is generator-assisted.
- `GenerateRepo.vbs` inspects a target table and produces:
- `POBO_<Table>.asp`
- `<Table>Repository.asp`
- Generated outputs are expected to be moved into `app/models/` and `app/repositories/`.

## Current Repository State

- `app/models/` is currently empty.
- `app/repositories/` is currently empty.
- `db/migrations/` currently has no checked-in migration files.

## Brownfield Implications

- The project is database-capable, but the sample starter does not include domain entities yet.
- Schema evolution and repository creation are expected to happen through the provided VBScript tooling rather than a separate ORM or package-managed migration framework.
- Future data documentation should be regenerated once concrete tables, migration files, or generated POBO/repository files are added.

+ 0
- 82
docs/deployment-configuration.md View File

@@ -1,82 +0,0 @@
# Deployment Configuration

## Dedicated defaults

The deployment controller and host installer use the same isolated defaults:

| Parameter | Default |
| --- | --- |
| `SiteName` | `AspClassicUnifiedFramework` |
| `AppPoolName` | `AspClassicUnifiedFramework` |
| `DeployRoot` | `D:\Deployments\AspClassicUnifiedFramework` |
| `BindingIpAddress` | `100.97.39.23` |
| `BindingPort` | `8085` |
| `HostHeader` | empty |
| `ExpectedBranch` | `master` (controller) |

Every value can be explicitly overridden. Site and pool names, deployment root, and host header containing `Schedulicious` are rejected as an additional safety boundary. The scripts do not enumerate another site as a configuration source and provide no adoption switch.

## Configuration ownership

Repository `public\web.config` is the default template for first deployment. After the package is safely extracted and validated, the host installer initializes:

```text
<DeployRoot>\shared\public.web.config
```

from the staged package's `public\web.config`. If `InitialWebConfigPath` is supplied on that first deployment, the validated host-local file at that path is used instead. The parameter does not replace an existing shared configuration. Configuration is never copied from another IIS site.

Every staged release receives the shared file before promotion. Change the shared file only through normal host configuration/change control and validate its XML. Keep secrets and production database paths out of source control.

## IIS state owned by the pipeline

The pipeline owns only the named dedicated site and app pool. It may:

1. create them, only when both are absent and only after a staged release validates;
2. point the dedicated site at `<DeployRoot>\releases\<release-id>\public`;
3. set `system.webServer/asp enableParentPaths=true` at that site's location;
4. start/recycle the dedicated app pool and start a newly created site.

It does not alter unrelated sites, app pools, bindings, authentication, identities, ACLs, Windows features, or IIS modules. It does not add bindings to an existing site.

When the target already exists, the site and pool must both exist and exactly match the requested app pool, sole HTTP binding, and pipeline-owned release-public path. Any mismatch fails closed.

## Controller parameters

`scripts/deploy-iis-git.ps1` supports:

- `SiteName`, `AppPoolName`, `DeployRoot`, `BindingIpAddress`, `BindingPort`, `HostHeader`: dedicated target identity and binding.
- `InitialWebConfigPath`: optional host-local first-deployment seed.
- `RemoteTarget`, `RemotePort`: OpenSSH transport.
- `SourcePath`: standalone checkout to validate/package.
- `ExpectedBranch`: remains `master` by default.
- `ReleaseId`: optional immutable release identifier.
- `BaseUrl`: explicit host-side smoke-test URL.
- `KeepReleases`: reporting threshold only; no deletion.
- `LocalPreflightOnly`: local source/XML/package/safety validation; no network.
- `PreflightOnly` (`HostPreflightOnly` and `RemotePreflightOnly` aliases): run local/package checks, then stream the installer over SSH for host validation without writing remote files or changing IIS/deployment state.
- `DryRun`: local package validation plus remote command preview; no network.
- `AllowAnyBranch`, `AllowDirty`: reviewed provenance exceptions.
- `RunMigrations`: explicit database migration opt-in.
- `SkipSmokeTest`: explicit smoke-test exception.
- `Rollback` and `RollbackTo`: switch the dedicated target to a validated prior release.

## Host installer parameters

`scripts/install-iis-release.ps1` accepts the same target/configuration parameters plus:

- `PackagePath`, `ReleaseId`, `ExpectedSha256`: deployment artifact inputs.
- `PreflightOnly` or `DryRun`: read-only host checks; the target may be absent.
- `RollbackTo`: validated release ID for rollback.

Host preflight requires elevation and verifies WebAdministration, Classic ASP feature and `AspModule`, URL Rewrite, requested binding conflicts (including wildcard overlap), shared-pool conflicts, deployment drive/path accessibility, names, and exact existing-target state. It makes no IIS or deployment-root changes.

## Failure scope

If creation or smoke testing fails, the installer removes only a site or app pool whose creation flags were set by that invocation. For an existing valid target, it restores the captured physical path and parent-path value. Unrelated IIS resources are never cleanup candidates.

Package staging/release files can remain as diagnostic evidence. Database migrations and external writes are outside IIS rollback.

## Secrets, identity, and writable data

Use OpenSSH configuration, an SSH agent, or a CI secret store. Do not commit passwords, private keys, production connection strings, or database files. Put production databases and logs outside release directories. App-pool identity and filesystem ACL provisioning are explicit host-administration tasks, not inferred from another site.

+ 0
- 134
docs/deployment-guide.md View File

@@ -1,134 +0,0 @@
# IIS Deployment Guide

## Isolation boundary

This pipeline owns one dedicated IIS site and one dedicated application pool. It never discovers, copies configuration from, adopts, or changes another IIS site. In particular, no existing Schedulicious site, app pool, binding, path, or configuration is a deployment source or target.

Defaults (each may be overridden explicitly):

```text
SiteName AspClassicUnifiedFramework
AppPoolName AspClassicUnifiedFramework
DeployRoot D:\Deployments\AspClassicUnifiedFramework
Binding http://100.97.39.23:8085/ (empty host header)
ExpectedBranch master
```

An existing target is accepted only when its name, app pool, sole HTTP binding, and physical path exactly match this pipeline's expected dedicated state. The physical path must be a `public` directory under `<DeployRoot>\releases`. A partial or mismatched target fails closed; there is no adoption mode. Unrelated sites, pools, and bindings are left unchanged.

## Release and web-root model

```text
D:\Deployments\AspClassicUnifiedFramework\
releases\
<release-id>\
app\
core\
db\
public\ <- only this directory is served by IIS
scripts\
tests\
...
shared\
public.web.config
deployment-state.json
```

The complete repository is packaged because `public/Default.asp` uses parent includes from sibling directories. Releases are extracted into `<release-id>.staging`, checked for required files, safe paths/reparse points, and valid `public\web.config` XML, overlaid with shared configuration, and renamed to an immutable release directory. IIS serves only `<release>\public`.

On the first deployment, shared configuration is initialized from the packaged release's `public\web.config`. Supply `-InitialWebConfigPath` only when an explicitly managed host-local configuration file should seed the first deployment. The script validates that file as XML. It never copies configuration from any IIS site. Once created, the shared file is reused and is not automatically refreshed.

Classic ASP parent paths are enabled with a location-scoped `system.webServer/asp` setting for this dedicated site only.

## Scripts

- `scripts/deploy-iis-git.ps1`: controller entry point; validates source, branch, XML, package structure, and safety; hashes and optionally transfers the package.
- `scripts/install-iis-release.ps1`: elevated Windows PowerShell 5.1 host installer; performs read-only host preflight, stages and validates releases, creates/manages only the dedicated target, switches releases, smoke tests, and rolls back target mutations on failure.

Gitea 1.11.4 predates Gitea Actions. Run the controller from a trusted external worker or operator workstation with approved Tailscale/OpenSSH access. No credentials or production configuration belong in this repository.

## Preflight sequence

### 1. Local/controller preflight (no network)

Run from a clean standalone `master` checkout:

```powershell
.\scripts\deploy-iis-git.ps1 -LocalPreflightOnly
```

This validates the dedicated names/binding/root, source provenance, required source files, repository `public\web.config` XML, package creation, extracted package layout, and reparse-point/symlink safety. It does not call SSH/SCP and makes no host change. `-AllowAnyBranch` is still required when the source is not a standalone Git checkout.

`-DryRun` also avoids network access but prints the remote operation that would be performed.

### 2. Full preflight (connects, read-only)

```powershell
.\scripts\deploy-iis-git.ps1 -PreflightOnly -RemoteTarget 'webserver-1'
```

After the local/package checks, the controller streams the installer over SSH and runs it in memory; it does not create a remote transport directory or copy a remote file. The host phase checks elevation, WebAdministration, Classic ASP feature/module, URL Rewrite module, deployment drive/path and resource names, binding conflicts (including wildcard IP overlap), shared-pool conflicts, and existing dedicated target consistency. The dedicated site and pool do not need to exist. No IIS or deployment-root change is made. `-HostPreflightOnly` and `-RemotePreflightOnly` remain aliases.

## First deployment

The installer creates the dedicated app pool and site only after the staged release and selected initial `web.config` validate. Example using all defaults:

```powershell
.\scripts\deploy-iis-git.ps1 -RemoteTarget 'webserver-1'
```

Example with explicit overrides:

```powershell
.\scripts\deploy-iis-git.ps1 `
-SiteName 'AspClassicUnifiedFramework-Test' `
-AppPoolName 'AspClassicUnifiedFramework-Test' `
-DeployRoot 'E:\Deployments\AspClassicUnifiedFramework-Test' `
-BindingIpAddress '100.97.39.23' `
-BindingPort 8185 `
-HostHeader 'framework-test.internal' `
-InitialWebConfigPath 'E:\ManagedConfig\framework-test.web.config' `
-RemoteTarget 'webserver-1' `
-ExpectedBranch 'master'
```

The new app pool uses no managed CLR. Configure any required app-pool identity and ACL policy through separately reviewed host preparation; the deployment does not borrow another pool's identity or permissions.

## Existing target and cutover

For later deployments, the host preflight requires the dedicated site to use:

- exactly `AppPoolName`;
- exactly one HTTP binding matching IP, port, and host header;
- a physical path ending in `\public` under `<DeployRoot>\releases`.

Any mismatch fails without mutation. After the new release validates, the installer changes only the dedicated site's physical path, applies the site-location parent-path setting, recycles/starts the dedicated pool, and smoke tests the configured binding or explicit `-BaseUrl`.

## Failure recovery

The installer records whether this invocation created the target site or pool and snapshots the prior state of an existing valid target.

- If target creation or smoke testing fails, it removes only the site/app pool created by this invocation.
- If an existing target fails during cutover or smoke testing, it restores its previous physical path and previous site-location parent-path value, then restarts/recycles its pool.
- It never removes or edits an unrelated site, pool, or binding.
- Staging/release files may remain for diagnosis; releases are reported as retention candidates and are never deleted automatically.
- Explicit database migrations cannot be undone by IIS rollback.

## Rollback

```powershell
.\scripts\deploy-iis-git.ps1 `
-Rollback `
-RollbackTo '20260914-171500-a1b2c3d4e5f6' `
-RemoteTarget 'webserver-1'
```

Rollback requires an already valid dedicated target and an existing immutable release under the configured `DeployRoot`. It switches only that target's physical path and smoke tests; it does not rewrite the prior release. Failure restores the prior target state.

## Database and writable data

Migrations are disabled by default. `-RunMigrations` is an explicit exception and requires a verified backup; path rollback cannot undo database changes. Keep production databases, logs, and other writable data outside immutable release directories and grant the dedicated app-pool identity only necessary permissions.

## Windows verification gates

Before production use, validate both scripts with the Windows PowerShell 5.1 parser, run host preflight on the intended Windows/IIS host, deploy to an isolated test name/binding, verify HTTP and parent includes, induce a smoke failure to prove invocation-scoped cleanup/restoration, then prove rollback. Linux checks cannot validate WebAdministration behavior, installed IIS features/modules, binding semantics on the live host, elevation, ACLs, app-pool identity, Access/ACE, or an actual HTTP response.

+ 0
- 55
docs/development-guide.md View File

@@ -1,55 +0,0 @@
# MVC-Starter - Development Guide

**Date:** 2026-03-11T11:59:39Z

## Prerequisites

- Windows environment
- IIS with Classic ASP enabled
- IIS URL Rewrite module
- Microsoft Access Database Engine
- Windows Script Host (`cscript`)

## Local Setup

1. Place the project on a Windows machine with IIS.
2. Point the site root to `public/`.
3. Update `public/web.config` for the correct database and logging paths.
4. Browse to `/` and confirm the starter home page renders.

## Common Workflows

### Add a database-backed feature

1. Generate a migration
2. Generate POBO/repository
3. Move generated files into `app/models/` and `app/repositories/`
4. Generate a controller
5. Include the controller from `app/controllers/autoload_controllers.asp`
6. Register the controller in `core/lib.ControllerRegistry.asp`
7. Add routes in `public/Default.asp`
8. Add corresponding views in `app/views/`

### Useful Commands

```bat
cscript //nologo scripts\generateMigration.vbs create_my_table
cscript //nologo scripts\GenerateRepo.vbs /table:my_table /pk:id
cscript //nologo scripts\generateController.vbs MyController "Index;Show(id)"
cscript //nologo scripts\runMigrations.vbs status
```

## Testing Approach

- Manual runtime validation through IIS
- Manual route/layout verification after controller or view changes
- Script validation through `cscript`
- No built-in automated test suite detected

## High-Risk Change Areas

- `public/Default.asp`
- `public/web.config`
- `core/mvc.asp`
- `core/lib.ControllerRegistry.asp`
- shared layout files under `app/views/shared/`

+ 0
- 59
docs/development-instructions.md View File

@@ -1,59 +0,0 @@
# Development Instructions

**Date:** 2026-03-11T11:59:39Z

## Prerequisites

- Windows Server or Windows development environment
- IIS with Classic ASP enabled
- IIS URL Rewrite module
- Microsoft Access Database Engine for `.accdb` support
- Windows Script Host / `cscript`

## Setup

1. Copy the project to the target IIS host.
2. Point the IIS site root to `public/`.
3. Update `public/web.config`:
- `ConnectionString`
- `ErrorLogPath` if logging is desired
4. Ensure the Access database file path is valid for the environment.

## Common Development Tasks

### Generate a migration

```bat
cscript //nologo scripts\generateMigration.vbs create_my_table
```

### Generate POBO and repository

```bat
cscript //nologo scripts\GenerateRepo.vbs /table:my_table /pk:id
```

Move generated files into `app/models/` and `app/repositories/`.

### Generate a controller

```bat
cscript //nologo scripts\generateController.vbs MyController "Index;Show(id);Create;Store"
```

Move the generated controller into `app/controllers/`.

### Activate a controller

After generating a controller:

1. Include it from `app/controllers/autoload_controllers.asp`
2. Register it in `core/lib.ControllerRegistry.asp`
3. Add routes in `public/Default.asp`
4. Create corresponding views in `app/views/`

## Validation Approach

- Manual browser validation is required for runtime changes.
- Route/layout changes should be checked through IIS-hosted execution.
- Migration and generator changes should be validated with `cscript`.

+ 0
- 46
docs/existing-documentation-inventory.md View File

@@ -1,46 +0,0 @@
# Existing Documentation Inventory

**Date:** 2026-03-11T11:59:39Z

## Summary

The project has a small set of directly relevant documentation files plus BMAD framework support files. For brownfield understanding, the highest-priority sources are the project README and a small number of repo-specific instruction files.

## Priority Documentation for Project Understanding

### `README.md`

- **Type:** readme
- **Path:** `/workspace/MVC-Starter/README.md`
- **Scope:** whole project
- **Notes:** Documents IIS setup, project structure, generator workflow, and baseline runtime requirements.

### `.github/copilot-instructions.md`

- **Type:** project instructions
- **Path:** `/workspace/MVC-Starter/.github/copilot-instructions.md`
- **Scope:** whole project
- **Notes:** Documents BMAD runtime conventions, config locations, workflow engine usage, and agent/runtime structure.

### `_bmad-output/project-context.md`

- **Type:** generated ai-project-context
- **Path:** `/workspace/MVC-Starter/_bmad-output/project-context.md`
- **Scope:** whole project
- **Notes:** Derivative documentation generated from workflow analysis. Useful for AI implementation rules, but not an original source of project design intent.

## BMAD Framework Documentation Assets

- `.github/agents/*.md` and `.github/prompts/*.md` provide BMAD agent and prompt definitions.
- `_bmad/` contains the installed BMAD framework, workflows, templates, and configuration.
- These files are important for maintaining the BMAD layer, but they are secondary to the application docs when documenting the MVC starter itself.

## Generated Documentation in This Workflow Run

- Files created under `docs/` by this workflow should be treated as generated brownfield documentation outputs, not original project-authored documents.

## Observations

- No dedicated architecture, deployment, API, or data-model markdown docs existed for the application before this workflow run.
- The README is the main human-authored source of project usage and structure.
- Most other markdown assets in the repo belong to the BMAD toolchain rather than the Classic ASP application itself.

+ 0
- 12
docs/ideas.md View File

@@ -1,12 +0,0 @@
Create and agents.md and claude.md so agents can use this repo to quickly develop applications


to do :
refactor so that classes and functions are wsl components that are unregistered and reregestered at application startup in the global.asa file

we need a scrit that will turn classes and functions into wsl files that the code can call and use

need to design classes with reflection in mind so that classes know about themselves and what they can do

also need to desgin functions and methods with contract by design in mind so that errors can be trapped better


+ 0
- 71
docs/index.md View File

@@ -1,71 +0,0 @@
# MVC-Starter Documentation Index

**Type:** monolith
**Primary Language:** VBScript / Classic ASP
**Architecture:** Server-rendered MVC monolith
**Last Updated:** 2026-03-11T11:59:39Z

## Project Overview

MVC-Starter is a RouteKit Classic ASP starter application for Windows IIS. It uses a single front controller, shared runtime/framework libraries, server-rendered views, an Access database, and VBScript-based scaffolding tools.

## Quick Reference

- **Tech Stack:** Classic ASP, VBScript, IIS, Access, Bootstrap
- **Entry Point:** `public/Default.asp`
- **Architecture Pattern:** Starter/framework hybrid MVC monolith
- **Database:** `db/webdata.accdb` via ACE OLE DB
- **Deployment:** Manual IIS deployment

## Generated Documentation

### Core Documentation

- [Project Overview](./project-overview.md) - Executive summary and high-level architecture
- [Project Structure](./project-structure.md) - Classification and structural boundaries
- [Source Tree Analysis](./source-tree-analysis.md) - Annotated directory structure
- [Architecture](./architecture.md) - Detailed technical architecture
- [Architecture Patterns](./architecture-patterns.md) - Runtime and design patterns
- [Technology Stack](./technology-stack.md) - Stack inventory and justification
- [Component Inventory](./component-inventory.md) - Runtime, UI, and tooling components
- [Development Guide](./development-guide.md) - Setup and common workflows
- [Deployment Guide](./deployment-guide.md) - IIS deployment and config guidance
- [API Contracts](./api-contracts-mvc-starter.md) - HTTP route contracts
- [Data Models](./data-models-mvc-starter.md) - Current data/model state and strategy

### Supporting Analysis

- [Existing Documentation Inventory](./existing-documentation-inventory.md)
- [User-Provided Context](./user-provided-context.md)
- [State Management Patterns](./state-management-patterns-mvc-starter.md)
- [UI Component Inventory](./ui-component-inventory-mvc-starter.md)
- [Comprehensive Analysis](./comprehensive-analysis-mvc-starter.md)
- [Critical Folders Summary](./critical-folders-summary.md)
- [Development Instructions](./development-instructions.md)
- [Deployment Configuration](./deployment-configuration.md)
- [Project Parts Metadata](./project-parts.json)
- [Project Scan State](./project-scan-report.json)

## Existing Documentation

- [README.md](../README.md) - Setup, structure, and feature scaffolding workflow
- [.github/copilot-instructions.md](../.github/copilot-instructions.md) - BMAD/Copilot repo instructions
- [_bmad-output/project-context.md](../_bmad-output/project-context.md) - Generated AI implementation context

## Getting Started

### For Humans

1. Read [project-overview.md](./project-overview.md)
2. Review [architecture.md](./architecture.md)
3. Use [development-guide.md](./development-guide.md) for feature work

### For AI-Assisted Development

- Start from this index
- Use [architecture.md](./architecture.md) and [project-context.md](../_bmad-output/project-context.md) together
- Reference [api-contracts-mvc-starter.md](./api-contracts-mvc-starter.md) and [data-models-mvc-starter.md](./data-models-mvc-starter.md) for route/data planning

---

Documentation generated by BMAD `document-project`.

+ 0
- 70
docs/project-overview.md View File

@@ -1,70 +0,0 @@
# MVC-Starter - Project Overview

**Date:** 2026-03-11T11:59:39Z
**Type:** web
**Architecture:** Server-rendered MVC monolith

## Executive Summary

MVC-Starter is a RouteKit Classic ASP starter for building server-rendered MVC applications on Windows IIS. It combines a shared framework/runtime layer in `core/` with application-specific controllers and views in `app/`, and supports database-backed features through Access and VBScript-based scaffolding.

## Project Classification

- **Repository Type:** monolith
- **Project Type(s):** web
- **Primary Language(s):** VBScript, Classic ASP
- **Architecture Pattern:** Starter/framework hybrid MVC monolith

## Technology Stack Summary

- Runtime: Classic ASP on IIS
- Routing/dispatch: RouteKit-style router and MVC dispatcher
- Data: ADO + Microsoft Access
- UI: Bootstrap CDN + server-rendered ASP views
- Tooling: Windows Script Host VBScript scripts

## Key Features

- Front-controller request flow through `public/Default.asp`
- Controller whitelist and dynamic dispatch in `core/mvc.asp`
- Shared header/footer layout for page rendering
- Generator-assisted migrations, repositories, and controllers
- Included starter pages for home and 404 handling

## Architecture Highlights

- Single deployable web app
- Clear split between runtime/framework code and app-specific code
- Config-driven behavior through `public/web.config`
- Manual but structured development workflow through scripts and route/controller wiring

## Development Overview

### Prerequisites

- Windows + IIS + Classic ASP
- IIS URL Rewrite
- Microsoft Access Database Engine
- `cscript` for tooling

### Getting Started

Point IIS at `public/`, update `public/web.config`, then validate the home page loads. Use the provided VBScript generators to create migrations, repositories, and controllers for new features.

### Key Commands

- **Generate migration:** `cscript //nologo scripts\generateMigration.vbs create_my_table`
- **Generate repo:** `cscript //nologo scripts\GenerateRepo.vbs /table:my_table /pk:id`
- **Generate controller:** `cscript //nologo scripts\generateController.vbs MyController "Index;Show(id)"`
- **Run migrations:** `cscript //nologo scripts\runMigrations.vbs status`

## Repository Structure

`public/` is the web entry surface, `core/` is the framework/runtime layer, `app/` is the application layer, `db/` contains database assets, and `scripts/` contains operational tooling.

## Documentation Map

- [index.md](./index.md)
- [architecture.md](./architecture.md)
- [source-tree-analysis.md](./source-tree-analysis.md)
- [development-guide.md](./development-guide.md)

+ 0
- 26
docs/project-parts.json View File

@@ -1,26 +0,0 @@
{
"repository_type": "monolith",
"parts": [
{
"part_id": "mvc-starter",
"part_name": "MVC-Starter",
"root_path": "/workspace/MVC-Starter",
"project_type_id": "web",
"runtime_shape": "server-rendered-mvc-monolith",
"hosting_assumption": "Windows IIS with URL Rewrite",
"entry_point": "public/Default.asp",
"framework_runtime_path": "core/",
"application_surface_path": "app/",
"operational_support_paths": [
"db/",
"scripts/"
],
"primary_technologies": [
"Classic ASP",
"VBScript",
"IIS",
"Microsoft Access"
]
}
]
}

+ 0
- 1
docs/project-scan-report.json View File

@@ -1 +0,0 @@
{"workflow_version":"1.2.0","timestamps":{"started":"2026-03-11T11:59:39Z","last_updated":"2026-03-11T12:13:30Z","completed":"2026-03-11T12:13:30Z"},"mode":"initial_scan","scan_level":"exhaustive","project_root":"/workspace/MVC-Starter","project_knowledge":"/workspace/MVC-Starter/docs","completed_steps":[{"step":"step_1","status":"completed","timestamp":"2026-03-11T12:03:40Z","summary":"Classified as monolith with 1 part; detected Classic ASP MVC web application hosted via IIS entrypoint in public/Default.asp"},{"step":"step_2","status":"completed","timestamp":"2026-03-11T12:06:06Z","summary":"Inventoried 3 relevant existing documentation files and recorded no additional user focus areas"},{"step":"step_3","status":"completed","timestamp":"2026-03-11T12:09:06Z","summary":"Analyzed technology stack and architecture pattern as Classic ASP/VBScript MVC monolith on IIS with Access and VBScript tooling"},{"step":"step_4","status":"completed","timestamp":"2026-03-11T12:12:40Z","summary":"Completed exhaustive conditional analysis and generated API, data, state, UI, and comprehensive analysis documents"},{"step":"step_5","status":"completed","timestamp":"2026-03-11T12:12:55Z","summary":"Generated source tree analysis and critical folders summary"},{"step":"step_6","status":"completed","timestamp":"2026-03-11T12:13:05Z","summary":"Generated development instructions and deployment configuration documentation"},{"step":"step_8","status":"completed","timestamp":"2026-03-11T12:13:10Z","summary":"Generated architecture.md for the single application part"},{"step":"step_9","status":"completed","timestamp":"2026-03-11T12:13:15Z","summary":"Generated supporting overview, component, development, deployment, and index-adjacent docs"},{"step":"step_10","status":"completed","timestamp":"2026-03-11T12:13:20Z","summary":"Generated master index with complete links and no incomplete markers"},{"step":"step_11","status":"completed","timestamp":"2026-03-11T12:13:25Z","summary":"Validated generated docs, found no incomplete documentation markers"},{"step":"step_12","status":"completed","timestamp":"2026-03-11T12:13:30Z","summary":"Workflow complete"}],"current_step":"completed","findings":{"project_classification":"monolith, 1 part, Classic ASP/VBScript web application","existing_documentation":"3 relevant docs found; README, Copilot instructions, and generated project context","technology_stack":"Classic ASP/VBScript on IIS with Access, RouteKit-style MVC runtime, Bootstrap CDN, and VBScript tooling","batch_summaries":["Application routes, controllers, views, and shared layout documented from app/ and public/","Runtime and framework behavior documented from core/","Database and operational tooling documented from db/ and scripts/"]},"project_types":[{"part_id":"mvc-starter","project_type_id":"web","display_name":"web"}],"outputs_generated":["project-scan-report.json","project-structure.md","project-parts.json","existing-documentation-inventory.md","user-provided-context.md","technology-stack.md","architecture-patterns.md","api-contracts-mvc-starter.md","data-models-mvc-starter.md","state-management-patterns-mvc-starter.md","ui-component-inventory-mvc-starter.md","comprehensive-analysis-mvc-starter.md","source-tree-analysis.md","critical-folders-summary.md","development-instructions.md","deployment-configuration.md","architecture.md","project-overview.md","component-inventory.md","development-guide.md","deployment-guide.md","index.md"],"resume_instructions":"Workflow complete. Start a fresh scan only if the project changes materially.","verification_summary":"Exhaustive file-system scan of app/core/public/scripts/db; extracted runtime config, routes, controllers, views, and tooling docs; checked docs for incomplete markers; no IIS runtime tests executed.","open_risks":"Documentation is based on static code/config analysis in this Linux workspace; Windows IIS runtime behavior, Access connectivity, and script execution were not validated live.","next_checks":"Review docs/index.md, validate the app on a Windows IIS host, confirm web.config paths, and regenerate docs after adding real models/repositories/migrations."}

+ 0
- 38
docs/project-structure.md View File

@@ -1,38 +0,0 @@
# MVC-Starter Project Structure

**Date:** 2026-03-11T11:59:39Z
**Repository Type:** monolith
**Detected Project Type:** web
**Specific Runtime Shape:** Classic ASP server-rendered MVC starter on Windows IIS
**Primary Technologies:** Classic ASP, VBScript, IIS, Microsoft Access

## Classification Summary

This repository is a single deployable web application, not a multi-part client/server system. It is a server-rendered Classic ASP MVC starter with:

- `public/` as the IIS web root and deploy entrypoint
- `core/` as shared framework/runtime code
- `app/` as the application extension surface for controllers, views, models, and repositories
- `db/` as database and migration support
- `scripts/` as scaffolding and operational tooling

## Detected Part

### MVC-Starter

- **Root Path:** `/workspace/MVC-Starter`
- **Project Type:** web
- **Runtime Shape:** Server-rendered MVC monolith
- **Hosting Assumption:** Windows IIS with URL Rewrite
- **Deploy Entry Point:** `public/Default.asp`
- **Framework Runtime:** `core/`
- **Application Extension Surface:** `app/`
- **Operational Support Directories:** `db/`, `scripts/`

## Why This Classification Fits

- The repository exposes a single web entrypoint through `public/Default.asp` and IIS rewrite config in `public/web.config`.
- Request handling flows through `public/` into framework code in `core/`, while application behavior is implemented in `app/`.
- Request handling, view rendering, routing, data access, and framework runtime are all contained in one application tree.
- There are no separate client/server packages, independent deployables, or service boundaries that would justify multi-part classification.
- The repo structure matches a classic server-rendered MVC application rather than a frontend/backend split web stack.

+ 0
- 100
docs/source-tree-analysis.md View File

@@ -1,100 +0,0 @@
# MVC-Starter - Source Tree Analysis

**Date:** 2026-03-11T11:59:39Z

## Overview

The repository is organized as a Classic ASP MVC starter with a clear split between deploy entry, shared runtime, application code, database assets, and operational tooling.

## Complete Directory Structure

```text
MVC-Starter/
├── app/ # Application-specific MVC layer
│ ├── controllers/ # Controllers and controller includes
│ ├── models/ # Intended POBO/model location (currently empty)
│ ├── repositories/ # Intended repository location (currently empty)
│ └── views/ # Server-rendered ASP views
│ ├── Error/
│ ├── Home/
│ └── shared/
├── core/ # Framework/runtime libraries and dispatcher
├── db/ # Database file and future migrations
│ ├── migrations/
│ └── webdata.accdb
├── docs/ # Generated brownfield documentation
├── public/ # IIS web root and request entrypoint
│ ├── Default.asp
│ └── web.config
├── scripts/ # Scaffolding and migration tooling
├── _bmad/ # Installed BMAD framework assets
├── _bmad-output/ # Generated BMAD workflow artifacts
└── .github/ # Copilot/BMAD prompt and agent support files
```

## Critical Directories

### `public/`

Purpose: deploy-facing web root and request bootstrap.

- Contains the front controller `Default.asp`
- Contains `web.config` with rewrite and runtime config
- Entry point for all non-static requests

### `core/`

Purpose: shared framework/runtime layer.

- Contains dispatcher, router, controller registry, helpers, DAL, migrations, flash helpers, and utility libraries
- High-blast-radius area for architectural changes

### `app/`

Purpose: project-specific extension surface.

- `controllers/` contains active controllers and include registration
- `views/` contains page templates and shared layout files
- `models/` and `repositories/` are intended generator targets

### `db/`

Purpose: database storage and schema evolution support.

- Includes `webdata.accdb`
- Includes `migrations/` directory for migration files

### `scripts/`

Purpose: development and operations support tooling.

- Controller generator
- Repository/POBO generator
- Migration generator
- Migration runner

## Entry Points

- Main request entry: `public/Default.asp`
- Runtime bootstrap: `core/autoload_core.asp`
- MVC dispatcher: `core/mvc.asp`
- Migration tooling entry: `scripts/runMigrations.vbs`

## Configuration Files

- `public/web.config` - IIS routing and runtime application settings
- `README.md` - setup and workflow guidance
- `.github/copilot-instructions.md` - BMAD/Copilot workflow guidance for repo maintenance

## File Organization Patterns

- Request handling starts in `public/`, not `app/`
- Shared reusable runtime code lives in `core/`
- Feature-specific behavior belongs in `app/`
- Operational scripts live outside the runtime in `scripts/`
- Generated documentation is isolated under `docs/`

## Development Notes

- This structure assumes IIS deployment with `public/` as the site root.
- Future application growth is expected to add controllers, views, models, repositories, and migrations without changing the overall directory shape.

+ 0
- 26
docs/state-management-patterns-mvc-starter.md View File

@@ -1,26 +0,0 @@
# State Management Patterns - MVC-Starter

**Date:** 2026-03-11T11:59:39Z

## Overview

This project does not implement client-side application state management in the SPA sense. State is primarily handled on the server/request side through controller properties, request data, and helper libraries.

## Observed Patterns

- **Request-scoped flow:** Incoming requests are routed and dispatched per request through `public/Default.asp` and `core/mvc.asp`.
- **Controller-held page state:** Controllers expose simple properties such as `useLayout` and `Title` to influence rendering behavior.
- **Flash messaging:** Shared layout calls `Flash().ShowErrorsIfPresent` and `Flash().ShowSuccessIfPresent`, indicating transient server-side UI messaging.
- **Configuration-driven behavior:** Runtime flags and UI behavior are sourced from `public/web.config` via `GetAppSetting`.
- **Form/cache helpers available:** `core/lib.FormCache.asp` and related helpers suggest server-side request/form support patterns.

## What Is Not Present

- No Redux, Context API, Vuex, MobX, Zustand, or similar client-state library
- No SPA store layer
- No separate API/client state synchronization layer

## Brownfield Notes

- Treat this app as server-rendered and request-driven.
- If richer client-side interactivity is added later, it will be a new architectural layer rather than an extension of an existing state-management system.

+ 0
- 28
docs/technology-stack.md View File

@@ -1,28 +0,0 @@
# Technology Stack

**Date:** 2026-03-11T11:59:39Z

## Part: MVC-Starter

| Category | Technology | Version / Variant | Justification |
|---|---|---|---|
| Runtime | Classic ASP | legacy IIS-hosted runtime | Request entrypoint is `public/Default.asp`, with `.asp` controllers, views, and framework files across `app/` and `core/`. |
| Language | VBScript | Classic ASP server-side VBScript | Controllers, framework code, helpers, and operational scripts are written in VBScript. |
| Web Server | IIS | Windows IIS with URL Rewrite | `public/web.config` configures default document behavior and rewrite rules to route requests through `Default.asp`. |
| MVC Framework | RouteKit Classic ASP | project-local framework/starter | README identifies RouteKit Classic ASP; routing and dispatch are implemented by `router.wsc`, `core/mvc.asp`, and controller registry logic. |
| Routing | RouteKit router + IIS rewrite | custom runtime routing | `router.AddRoute` is used in `public/Default.asp`, and incoming requests are rewritten by IIS before dispatch. |
| Data Access | ADO / OLE DB | Classic ASP ADODB stack | DAL and repository generation rely on ADO connections and Classic ASP data access libraries. |
| Database | Microsoft Access | `Microsoft.ACE.OLEDB.12.0` provider | `public/web.config` configures an `.accdb` connection string; `db/webdata.accdb` is included in the repo. |
| Database Migration | Custom VBScript migration runner | project-local | `scripts/runMigrations.vbs` manages migration application, rollback, and status outside IIS. |
| UI Framework | Bootstrap | 5.3.3 | Shared header loads Bootstrap CSS and JS from CDN for layout and components. |
| Icon Library | Bootstrap Icons | 1.11.3 | Shared header loads Bootstrap Icons from CDN. |
| Frontend Rendering | Server-rendered HTML views | Classic ASP include-based rendering | Controllers include `.asp` view files, with shared header/footer layout wrapping page content. |
| Tooling | Windows Script Host VBScript scripts | project-local generators | `scripts/generateController.vbs`, `GenerateRepo.vbs`, `generateMigration.vbs`, and `runMigrations.vbs` drive scaffolding and DB workflow. |
| Configuration | IIS `web.config` + appSettings | XML-based runtime config | Connection strings, environment flags, cache settings, flash timing, and other behavior are driven from `public/web.config`. |

## Stack Notes

- This is a server-rendered web app, not a separate frontend/backend split stack.
- The repo has no `package.json`, `requirements.txt`, or other modern package manifest for the application itself.
- Frontend assets are primarily CDN-hosted Bootstrap resources plus local static assets served from `public/`.
- Development and operational tooling assume a Windows environment with IIS and Windows Script Host.

+ 0
- 50
docs/ui-component-inventory-mvc-starter.md View File

@@ -1,50 +0,0 @@
# UI Component Inventory - MVC-Starter

**Date:** 2026-03-11T11:59:39Z

## Overview

The current UI surface is small and server-rendered. Reuse is primarily achieved through shared layout files and Bootstrap utility/component classes rather than a formal component library.

## Shared UI Surfaces

### Shared Layout

- `app/views/shared/header.asp`
- Sets page charset/codepage
- Resolves the page title from `CurrentController.Title`
- Loads Bootstrap 5.3.3 and Bootstrap Icons 1.11.3 from CDN
- Renders the top navigation shell
- Displays flash error/success messages

- `app/views/shared/footer.asp`
- Closes the main layout wrapper
- Loads the Bootstrap JS bundle from CDN

## Feature Views

### Home View

- `app/views/Home/index.asp`
- Welcome/placeholder landing page
- Uses Bootstrap cards, grid, typography, and code snippets
- Documents where new controllers, repositories, and views belong

### Error View

- `app/views/Error/NotFound.asp`
- 404 page with countdown redirect behavior
- Uses Bootstrap card layout and iconography
- Reads redirect timing from config via `GetAppSetting("Error404RedirectSeconds")`

## Reusable UI Patterns

- Shared header/footer layout wrapping
- Bootstrap-based cards and grid layout
- Config-driven flash messages in shared layout
- Simple server-rendered page title convention via controller property

## Brownfield Notes

- Reuse is currently layout-oriented, not component-library oriented.
- New UI work will likely create additional `.asp` view files under `app/views/` rather than reusable frontend components in a JS framework.

+ 0
- 13
docs/user-provided-context.md View File

@@ -1,13 +0,0 @@
# User-Provided Context

**Date:** 2026-03-11T11:59:39Z

No additional documents, paths, or focus areas were provided by the user for this documentation run.

## Implication for This Scan

The scan should prioritize:

- the main application structure under `public/`, `core/`, `app/`, `db/`, and `scripts/`
- existing first-party guidance in `README.md`
- BMAD-related project instructions only where they affect project understanding or AI-assisted maintenance

+ 7
- 4
public/Default.asp View File

@@ -1,4 +1,4 @@
<!--#include file="..\core\autoload_core.asp" -->
<!--#include file="../core/autoload_core.asp" -->

<%
' Define starter application routes
@@ -7,7 +7,10 @@
router.AddRoute "GET", "", "HomeController", "Index"
router.AddRoute "GET", "/404", "ErrorController", "NotFound"

' Dispatch the request (resolves route and executes controller action)
MVC.DispatchRequest Request.ServerVariables("REQUEST_METHOD"), _
TrimQueryParams(Request.ServerVariables("HTTP_X_ORIGINAL_URL"))
' API docs (Swagger UI)
router.AddRoute "GET", "/api/docs", "DocsController", "Index"

' Dispatch the request (resolves route and executes controller action).
' MVC() is called with parentheses: AxonASP cannot use "MVC.Method args" on a parameterless function.
MVC().DispatchRequest Request.ServerVariables("REQUEST_METHOD"), GetRequestPath()
%>

+ 7
- 8
public/web.config View File

@@ -3,12 +3,11 @@

<appSettings>
<!--
Access connection string.
IMPORTANT: Change Data Source to the real physical path
to your webdata.accdb file.
SQLite connection string (AxonASP ADODB layer: "sqlite:" prefix + file path).
docker-compose.yml mounts the framework folder at /opt/axonasp/site, so db/ is /opt/axonasp/site/db.
The file is created on first open if it does not exist.
-->
<add key="ConnectionString"
value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\YourApp\db\webdata.accdb;Persist Security Info=False;" />
<add key="ConnectionString" value="sqlite:/opt/axonasp/site/db/app.sqlite" />

<!-- Environment flag (Development / Staging / Production) -->
<add key="Environment" value="Development" />
@@ -50,18 +49,18 @@
</files>
</defaultDocument>

<!-- URL Rewrite: send everything through Default.asp except static assets -->
<!-- URL Rewrite: send everything that is not an existing file/folder through Default.asp (RE2: no lookahead; the original path is passed as __route) -->
<rewrite>
<rules>
<rule name="Rewrite to Default.asp" stopProcessing="true">
<match url="^(?!Default\.asp$|css/|js/|images/|aspunit/|favicon\.ico$).*$" />
<match url="^(.+)$" />

<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>

<action type="Rewrite" url="/Default.asp" />
<action type="Rewrite" url="/Default.asp?__route=/{R:1}" appendQueryString="true" />
</rule>
</rules>
</rewrite>


+ 0
- 4
run_site.cmd View File

@@ -1,4 +0,0 @@
@echo off
setlocal
set "ASPC_STARTER_ROOT=%~dp0"
"C:\Program Files\IIS Express\iisexpress.exe" /config:"%~dp0applicationhost.config"

+ 611
- 0
scripts/GenerateApi.vbs View File

@@ -0,0 +1,611 @@
'==============================================================
' GenerateApi.vbs (AxonASP CLI + G3DB edition)
'
' Usage (runs under the AxonASP CLI in the container; gen.cmd runs GenerateRepo.vbs first):
' scripts\gen.cmd api /table:Products /pk:Id
'
' Sets up a JSON API for one table:
' app/controllers/Api<Table>Controller.asp controller (list/search/paging, show, create, PUT, PATCH, delete)
' app/controllers/autoload_controllers.asp include line added
' app/models/autoload_models.asp POBO + repository include lines added
' core/lib.ControllerRegistry.asp controller whitelisted
' public/Default.asp 6 routes under /api/<table> added
' public/api/<table>.openapi.json OpenAPI spec (shows up in the /api/docs Swagger UI)
' api-tests/<table>.http sample requests (VS Code REST Client)
'
' Notes: a JSON null is not accepted for a field (omit it instead). Needs app/models/POBO_<Table>.asp and <Table>Repository.asp (GenerateRepo.vbs). Refuses to overwrite an
' existing controller. Validation is derived from the column types and NOT NULL / DEFAULT; add business rules
' (ranges, lengths) in the generated controller by hand.
'==============================================================

Option Explicit

' AxonASP CLI: provide the WScript object (see _cli.vbs)
Dim shimFso
Set shimFso = CreateObject("Scripting.FileSystemObject")
ExecuteGlobal shimFso.OpenTextFile(Server.MapPath("/scripts/_cli.vbs"), 1).ReadAll

Dim fso, args, i, arg, parts, tableName, primaryKey, csKey, configPath
Set fso = CreateObject("Scripting.FileSystemObject")
Set args = WScript.Arguments
csKey = "ConnectionString"
configPath = Server.MapPath("/public/web.config")

For i = 0 To args.Count - 1
arg = args(i)
If InStr(arg, ":") > 0 Then
parts = Split(arg, ":", 2)
Select Case LCase(Replace(parts(0), "/", ""))
Case "table": tableName = parts(1)
Case "pk": primaryKey = parts(1)
End Select
End If
Next

If Len(tableName) = 0 Or Len(primaryKey) = 0 Then
WScript.Echo "Usage: scripts\gen.cmd api /table:<TableName> /pk:<PrimaryKey>"
WScript.Quit 1
End If
If Not IsValidIdentifier(tableName) Or Not IsValidIdentifier(primaryKey) Then
WScript.Echo "Error: table and primary key may only contain letters, numbers and underscores."
WScript.Quit 1
End If

Dim ctrlPath, routeName, constName
routeName = LCase(tableName)
constName = "API_" & UCase(tableName)
ctrlPath = Server.MapPath("/app/controllers/Api" & tableName & "Controller.asp")
If fso.FileExists(ctrlPath) Then
WScript.Echo "Error: " & ctrlPath & " already exists. Delete it first if you want to regenerate."
WScript.Quit 1
End If
If Not fso.FileExists(Server.MapPath("/app/models/" & tableName & "Repository.asp")) Then
WScript.Echo "Error: app/models/" & tableName & "Repository.asp not found. Run: scripts\gen.cmd repo /table:" & tableName & " /pk:" & primaryKey
WScript.Quit 1
End If

'---------------- Connection + schema ----------------
Dim connStr, p, dsn, db
connStr = GetAppSetting(csKey, configPath)
p = InStr(connStr, ":")
If connStr = "nothing" Or p < 2 Then
WScript.Echo "Error: ConnectionString not found or malformed in " & configPath
WScript.Quit 1
End If
If LCase(Left(connStr, p - 1)) <> "sqlite" Then
WScript.Echo "Error: schema discovery is implemented for SQLite only."
WScript.Quit 1
End If
dsn = Mid(connStr, p + 1)
Set db = Server.CreateObject("G3DB")
If Not db.Open("sqlite", dsn) Then
WScript.Echo "DB connection failed: " & db.LastError
WScript.Quit 1
End If

' cols(i) name, kinds(i) string|int|real|bool|date, needs(i) True when NOT NULL without DEFAULT, isPk(i)
Dim cols(), kinds(), needs(), isPk(), dflts(), idx, rs, declType, notNull, dflt, pkFlag
idx = -1
Set rs = db.Query("PRAGMA table_info(" & tableName & ")")
If IsEmpty(rs) Then
WScript.Echo "Error reading table [" & tableName & "]: " & db.LastError
WScript.Quit 1
End If
Do Until rs.EOF
idx = idx + 1
ReDim Preserve cols(idx), kinds(idx), needs(idx), isPk(idx), dflts(idx)
cols(idx) = CStr(rs(1))
declType = "" & rs(2)
notNull = rs(3)
dflt = rs(4)
dflts(idx) = dflt
pkFlag = rs(5)
kinds(idx) = ApiKind(declType)
isPk(idx) = (StrEqualCI(cols(idx), primaryKey) Or CLng(pkFlag) > 0)
needs(idx) = (CLng(notNull) = 1 And IsNull(dflt) And Not isPk(idx))
rs.MoveNext
Loop
rs.Close
db.Close
If idx < 0 Then
WScript.Echo "No columns found for table [" & tableName & "]. Run the migrations first."
WScript.Quit 1
End If

'---------------- Build the pieces ----------------
Dim newDefaults, updStamps, dv, members, clearFields, parseBody, applyBody, rowJson, docFields, searchCols, orderCol, writable
newDefaults = "" : updStamps = "" : members = "" : clearFields = "" : parseBody = "" : applyBody = "" : rowJson = "" : docFields = "" : searchCols = "" : orderCol = primaryKey
writable = 0

Dim q
q = Chr(34)
For i = 0 To idx
Dim c, camel, fv
c = cols(i)
camel = LCase(Left(c, 1)) & Mid(c, 2)
fv = "f_" & c

' ---- output JSON (all columns)
If Len(rowJson) = 0 Then
rowJson = q & "{" & q & q & camel & q & q & ":" & q & " & " & JsonExpr(c, kinds(i), isPk(i))
Else
rowJson = rowJson & " & _" & vbCrLf & " " & q & "," & q & q & camel & q & q & ":" & q & " & " & JsonExpr(c, kinds(i), isPk(i))
End If

' ---- first string column is the default sort, string columns are searchable
If kinds(i) = "string" And Not isPk(i) Then
If Len(searchCols) > 0 Then searchCols = searchCols & ", "
searchCols = searchCols & """" & c & """"
If orderCol = primaryKey Then orderCol = c
End If

If isPk(i) Then
docFields = docFields & "' " & camel & " (read-only primary key)" & vbCrLf
ElseIf IsStampCol(c, kinds(i)) Then
' CreatedAt / UpdatedAt are managed by the server
If LCase(c) = "createdat" Then
newDefaults = newDefaults & " rec." & c & " = NowStamp()" & vbCrLf
Else
newDefaults = newDefaults & " rec." & c & " = NowStamp()" & vbCrLf
updStamps = updStamps & " rec." & c & " = NowStamp()" & vbCrLf
End If
docFields = docFields & "' " & camel & " (set by the server)" & vbCrLf
Else
writable = writable + 1
dv = DefaultLiteral(dflts(i))
If Len(dv) > 0 Then
newDefaults = newDefaults & " rec." & c & " = " & dv & vbCrLf
End If
members = members & " Private " & fv & vbCrLf
clearFields = clearFields & " " & fv & " = Empty" & vbCrLf
parseBody = parseBody & BuildParse(c, camel, fv, kinds(i), needs(i))
applyBody = applyBody & " If Not IsEmpty(" & fv & ") Then" & vbCrLf & _
" rec." & c & " = " & fv & vbCrLf & _
" End If" & vbCrLf
docFields = docFields & "' " & c & " (" & kinds(i) & Pick(needs(i), ", required", "") & ")" & vbCrLf
End If
Next

rowJson = rowJson & " & ""}"""
If Len(searchCols) = 0 Then
searchCols = "Empty"
Else
searchCols = "Array(" & searchCols & ")"
End If
docFields = Left(docFields, Len(docFields) - 2)

'---------------- Write the controller ----------------
Dim t
t = ReadTemplate("Api.tpl.asp")
t = Replace(t, "{{TABLE}}", tableName)
t = Replace(t, "{{PK}}", primaryKey)
t = Replace(t, "{{ROUTE}}", routeName)
t = Replace(t, "{{CONST}}", constName)
If Len(updStamps) = 0 Then
t = Replace(t, "{{UPDATE_STAMPS}}" & vbLf, "")
t = Replace(t, "{{UPDATE_STAMPS}}" & vbCrLf, "")
Else
t = Replace(t, "{{UPDATE_STAMPS}}", Left(updStamps, Len(updStamps) - 2))
End If
If Len(newDefaults) = 0 Then
t = Replace(t, "{{NEW_DEFAULTS}}" & vbCrLf, "")
Else
t = Replace(t, "{{NEW_DEFAULTS}}", Left(newDefaults, Len(newDefaults) - 2))
End If
t = Replace(t, "{{DATE}}", CStr(Now()))
t = Replace(t, "{{DOC_FIELDS}}", docFields)
t = Replace(t, "{{MEMBERS}}", Left(members, Len(members) - 2))
t = Replace(t, "{{CLEAR_FIELDS}}", Left(clearFields, Len(clearFields) - 2))
t = Replace(t, "{{PARSE_BODY}}", parseBody)
t = Replace(t, "{{APPLY_BODY}}", Left(applyBody, Len(applyBody) - 2))
t = Replace(t, "{{SEARCH_COLS}}", searchCols)
t = Replace(t, "{{ORDER_COL}}", orderCol)
t = Replace(t, "{{ROW_JSON}}", rowJson)
WriteFile ctrlPath, t
WScript.Echo "Controller: " & ctrlPath

'---------------- Wire it up ----------------
AppendIfMissing "/app/models/autoload_models.asp", "POBO_" & tableName & ".asp", "<!--#include file=""POBO_" & tableName & ".asp"" -->"
AppendIfMissing "/app/models/autoload_models.asp", tableName & "Repository.asp", "<!--#include file=""" & tableName & "Repository.asp"" -->"
AppendIfMissing "/app/controllers/autoload_controllers.asp", "Api" & tableName & "Controller.asp", "<!--#include file=""Api" & tableName & "Controller.asp"" -->"
WScript.Echo "Includes: autoload_models.asp, autoload_controllers.asp"

InsertAfterLine "/core/lib.ControllerRegistry.asp", "RegisterController ""errorcontroller""", "api" & LCase(tableName) & "controller", _
" RegisterController ""api" & LCase(tableName) & "controller"""
WScript.Echo "Registry: api" & LCase(tableName) & "controller whitelisted"

Dim r
r = vbTab & "' " & tableName & " JSON API (generated by GenerateApi.vbs)" & vbCrLf & _
vbTab & "router.AddRoute ""GET"", ""/api/" & routeName & """, ""Api" & tableName & "Controller"", ""Index""" & vbCrLf & _
vbTab & "router.AddRoute ""POST"", ""/api/" & routeName & """, ""Api" & tableName & "Controller"", ""Create""" & vbCrLf & _
vbTab & "router.AddRoute ""GET"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Show""" & vbCrLf & _
vbTab & "router.AddRoute ""PUT"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Update""" & vbCrLf & _
vbTab & "router.AddRoute ""PATCH"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Update""" & vbCrLf & _
vbTab & "router.AddRoute ""DELETE"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Delete""" & vbCrLf & vbCrLf
InsertBeforeLine "/public/Default.asp", "' Dispatch the request", "Api" & tableName & "Controller", r
WScript.Echo "Routes: /api/" & routeName & " and /api/" & routeName & "/:id added to public/Default.asp"

'---------------- Spec + sample requests ----------------
Dim specDir, specPath
specDir = Server.MapPath("/public/api")
If Not fso.FolderExists(specDir) Then fso.CreateFolder specDir
specPath = specDir & "/" & routeName & ".openapi.json"
WriteFile specPath, BuildSpec()
WScript.Echo "OpenAPI spec: " & specPath

Dim httpDir, httpPath
httpDir = Server.MapPath("/api-tests")
If Not fso.FolderExists(httpDir) Then fso.CreateFolder httpDir
httpPath = httpDir & "/" & routeName & ".http"
WriteFile httpPath, BuildHttp()
WScript.Echo "Sample calls: " & httpPath

WScript.Echo ""
WScript.Echo "Done. Restart the container (docker restart axonasp), then open /api/docs and pick '" & tableName & "' in the spec list."

'==============================================================
' Code generation
'==============================================================
Function BuildParse(c, camel, fv, kind, required)
Dim s, label
label = c
s = " k = """"" & vbCrLf
s = s & " If input.Exists(""" & c & """) Then" & vbCrLf
s = s & " k = """ & c & """" & vbCrLf
If camel <> c Then
s = s & " ElseIf input.Exists(""" & camel & """) Then" & vbCrLf
s = s & " k = """ & camel & """" & vbCrLf
End If
s = s & " End If" & vbCrLf
s = s & " If Len(k) > 0 Then" & vbCrLf
s = s & " v = input.Item(k)" & vbCrLf
Select Case kind
Case "string"
s = s & " v = Trim("""" & v)" & vbCrLf
If required Then
s = s & " If Len(v) = 0 Then" & vbCrLf
s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " is required.""" & vbCrLf
s = s & " End If" & vbCrLf
End If
s = s & " " & fv & " = v" & vbCrLf
Case "int", "real"
s = s & " If VarType(v) = 11 Then" & vbCrLf
s = s & " v = CLng(v) * -1" & vbCrLf
s = s & " End If" & vbCrLf
s = s & " If IsNumeric(v) And Not IsNull(v) And VarType(v) <> 8 Then" & vbCrLf
If kind = "int" Then
s = s & " If CDbl(v) <> Int(CDbl(v)) Then" & vbCrLf
s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be a whole number.""" & vbCrLf
s = s & " Else" & vbCrLf
s = s & " " & fv & " = CLng(v)" & vbCrLf
s = s & " End If" & vbCrLf
Else
s = s & " " & fv & " = CDbl(v)" & vbCrLf
End If
s = s & " Else" & vbCrLf
s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be a number.""" & vbCrLf
s = s & " End If" & vbCrLf
Case "bool"
s = s & " If VarType(v) = 11 Then" & vbCrLf
s = s & " " & fv & " = v" & vbCrLf
s = s & " ElseIf IsNumeric(v) And Not IsNull(v) And VarType(v) <> 8 Then" & vbCrLf
s = s & " " & fv & " = (CDbl(v) <> 0)" & vbCrLf
s = s & " Else" & vbCrLf
s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be true or false.""" & vbCrLf
s = s & " End If" & vbCrLf
Case "date"
s = s & " If IsDate(v) Then" & vbCrLf
s = s & " " & fv & " = CDate(v)" & vbCrLf
s = s & " Else" & vbCrLf
s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be a date.""" & vbCrLf
s = s & " End If" & vbCrLf
End Select
If required Then
s = s & " ElseIf Not partial Then" & vbCrLf
s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " is required.""" & vbCrLf
End If
s = s & " End If" & vbCrLf & vbCrLf
BuildParse = s
End Function

' VBScript expression (generator output) that renders column c of "rec" as a JSON value
Function JsonExpr(c, kind, pk)
If pk Or kind = "int" Then
JsonExpr = "CLng(rec." & c & ")"
ElseIf kind = "real" Then
JsonExpr = "JsonLite_Num(rec." & c & ")"
ElseIf kind = "bool" Then
JsonExpr = "LCase(CStr(CBool(rec." & c & ")))"
ElseIf kind = "date" Then
JsonExpr = "JsonDate(rec." & c & ")"
Else
JsonExpr = "JsonLite_Quote(rec." & c & ")"
End If
End Function

Function BuildSpec()
Dim sch, inp, req, k, nm, ty, ex, exs, sep
sch = "" : inp = "" : req = "" : exs = ""
For k = 0 To idx
nm = LCase(Left(cols(k), 1)) & Mid(cols(k), 2)
ty = SpecType(kinds(k), isPk(k))
If Len(sch) > 0 Then sch = sch & "," & vbCrLf
sch = sch & " """ & nm & """: " & ty
If Not isPk(k) And Not IsStampCol(cols(k), kinds(k)) Then
If Len(inp) > 0 Then inp = inp & "," & vbCrLf
inp = inp & " """ & cols(k) & """: " & ty
If needs(k) Then
If Len(req) > 0 Then req = req & ", "
req = req & """" & cols(k) & """"
End If
If Len(exs) > 0 Then exs = exs & ", "
exs = exs & """" & cols(k) & """: " & SampleValue(kinds(k))
End If
Next
Dim reqLine
reqLine = ""
If Len(req) > 0 Then reqLine = " ""required"": [" & req & "]," & vbCrLf

Dim T, R
T = tableName : R = routeName
Dim s
s = "{" & vbCrLf
s = s & " ""openapi"": ""3.0.3""," & vbCrLf
s = s & " ""info"": { ""title"": """ & T & " API"", ""version"": ""1.0.0"", ""description"": ""Generated by GenerateApi.vbs from the " & T & " table. Stateless: no auth or CSRF. Request fields use the column names (camelCase also accepted); responses use camelCase."" }," & vbCrLf
s = s & " ""servers"": [{ ""url"": ""/"" }]," & vbCrLf
s = s & " ""tags"": [{ ""name"": """ & T & """ }]," & vbCrLf
s = s & " ""paths"": {" & vbCrLf
s = s & " ""/api/" & R & """: {" & vbCrLf
s = s & " ""get"": { ""tags"": [""" & T & """], ""summary"": ""List (search + paging)""," & vbCrLf
s = s & " ""parameters"": [" & vbCrLf
s = s & " { ""name"": ""q"", ""in"": ""query"", ""schema"": { ""type"": ""string"" }, ""description"": ""Case-insensitive match on the text columns"" }," & vbCrLf
s = s & " { ""name"": ""page"", ""in"": ""query"", ""schema"": { ""type"": ""integer"", ""minimum"": 1, ""default"": 1 } }," & vbCrLf
s = s & " { ""name"": ""per_page"", ""in"": ""query"", ""schema"": { ""type"": ""integer"", ""minimum"": 1, ""maximum"": 100, ""default"": 10 } }" & vbCrLf
s = s & " ]," & vbCrLf
s = s & " ""responses"": { ""200"": { ""description"": ""A page of records"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/List"" } } } } } }," & vbCrLf
s = s & " ""post"": { ""tags"": [""" & T & """], ""summary"": ""Create""," & vbCrLf
s = s & " ""requestBody"": { ""required"": true, ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Input"" }, ""example"": {" & exs & "} } } }," & vbCrLf
s = s & " ""responses"": { ""201"": { ""description"": ""Created (Location header has the new URL)"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Envelope"" } } } }, ""400"": { ""$ref"": ""#/components/responses/Error"" }, ""422"": { ""$ref"": ""#/components/responses/Error"" } } }" & vbCrLf
s = s & " }," & vbCrLf
s = s & " ""/api/" & R & "/{id}"": {" & vbCrLf
s = s & " ""parameters"": [{ ""name"": ""id"", ""in"": ""path"", ""required"": true, ""schema"": { ""type"": ""integer"" } }]," & vbCrLf
s = s & " ""get"": { ""tags"": [""" & T & """], ""summary"": ""Get one""," & vbCrLf
s = s & " ""responses"": { ""200"": { ""description"": ""The record"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Envelope"" } } } }, ""404"": { ""$ref"": ""#/components/responses/Error"" } } }," & vbCrLf
s = s & " ""put"": { ""tags"": [""" & T & """], ""summary"": ""Replace (required fields enforced)""," & vbCrLf
s = s & " ""requestBody"": { ""required"": true, ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Input"" }, ""example"": {" & exs & "} } } }," & vbCrLf
s = s & " ""responses"": { ""200"": { ""description"": ""Updated"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Envelope"" } } } }, ""400"": { ""$ref"": ""#/components/responses/Error"" }, ""404"": { ""$ref"": ""#/components/responses/Error"" }, ""422"": { ""$ref"": ""#/components/responses/Error"" } } }," & vbCrLf
s = s & " ""patch"": { ""tags"": [""" & T & """], ""summary"": ""Partial update (only fields sent change)""," & vbCrLf
s = s & " ""requestBody"": { ""required"": true, ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Input"" }, ""example"": {} } } }," & vbCrLf
s = s & " ""responses"": { ""200"": { ""description"": ""Updated"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Envelope"" } } } }, ""400"": { ""$ref"": ""#/components/responses/Error"" }, ""404"": { ""$ref"": ""#/components/responses/Error"" }, ""422"": { ""$ref"": ""#/components/responses/Error"" } } }," & vbCrLf
s = s & " ""delete"": { ""tags"": [""" & T & """], ""summary"": ""Delete""," & vbCrLf
s = s & " ""responses"": { ""200"": { ""description"": ""Deleted"", ""content"": { ""application/json"": { ""schema"": { ""type"": ""object"", ""properties"": { ""deleted"": { ""type"": ""boolean"" }, ""id"": { ""type"": ""integer"" } } } } } }, ""404"": { ""$ref"": ""#/components/responses/Error"" } } }" & vbCrLf
s = s & " }" & vbCrLf
s = s & " }," & vbCrLf
s = s & " ""components"": {" & vbCrLf
s = s & " ""schemas"": {" & vbCrLf
s = s & " ""Record"": { ""type"": ""object"", ""properties"": {" & vbCrLf & sch & vbCrLf & " } }," & vbCrLf
s = s & " ""Input"": { ""type"": ""object""," & vbCrLf & reqLine & " ""properties"": {" & vbCrLf & inp & vbCrLf & " } }," & vbCrLf
s = s & " ""Envelope"": { ""type"": ""object"", ""properties"": { ""data"": { ""$ref"": ""#/components/schemas/Record"" } } }," & vbCrLf
s = s & " ""List"": { ""type"": ""object"", ""properties"": { ""data"": { ""type"": ""array"", ""items"": { ""$ref"": ""#/components/schemas/Record"" } }, ""meta"": { ""type"": ""object"", ""properties"": { ""page"": { ""type"": ""integer"" }, ""per_page"": { ""type"": ""integer"" }, ""page_count"": { ""type"": ""integer"" }, ""record_count"": { ""type"": ""integer"" } } } } }," & vbCrLf
s = s & " ""Error"": { ""type"": ""object"", ""properties"": { ""error"": { ""type"": ""object"", ""properties"": { ""message"": { ""type"": ""string"" }, ""details"": { ""type"": ""array"", ""items"": { ""type"": ""string"" } } } } } }" & vbCrLf
s = s & " }," & vbCrLf
s = s & " ""responses"": { ""Error"": { ""description"": ""Error"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Error"" } } } } }" & vbCrLf
s = s & " }" & vbCrLf
s = s & "}" & vbCrLf
BuildSpec = s
End Function

Function BuildHttp()
Dim k, ex, h
ex = ""
For k = 0 To idx
If Not isPk(k) And Not IsStampCol(cols(k), kinds(k)) Then
If Len(ex) > 0 Then ex = ex & ", "
ex = ex & """" & cols(k) & """: " & SampleValue(kinds(k))
End If
Next
h = "### " & tableName & " JSON API. Use with the VS Code ""REST Client"" extension (or any .http runner)." & vbLf
h = h & "@base = http://localhost:8801" & vbLf & vbLf
h = h & "### List (q = text search, page, per_page max 100)" & vbLf & "GET {{base}}/api/" & routeName & "?page=1&per_page=5" & vbLf & vbLf
h = h & "### Show" & vbLf & "GET {{base}}/api/" & routeName & "/1" & vbLf & vbLf
h = h & "### Create -> 201 + Location header" & vbLf & "POST {{base}}/api/" & routeName & vbLf & "Content-Type: application/json" & vbLf & vbLf & "{ " & ex & " }" & vbLf & vbLf
h = h & "### Replace (required fields enforced)" & vbLf & "PUT {{base}}/api/" & routeName & "/1" & vbLf & "Content-Type: application/json" & vbLf & vbLf & "{ " & ex & " }" & vbLf & vbLf
h = h & "### Partial update (only the fields sent change)" & vbLf & "PATCH {{base}}/api/" & routeName & "/1" & vbLf & "Content-Type: application/json" & vbLf & vbLf & "{ }" & vbLf & vbLf
h = h & "### Delete" & vbLf & "DELETE {{base}}/api/" & routeName & "/1" & vbLf
BuildHttp = h
End Function

Function SpecType(kind, pk)
If pk Or kind = "int" Then
SpecType = "{ ""type"": ""integer"" }"
ElseIf kind = "real" Then
SpecType = "{ ""type"": ""number"" }"
ElseIf kind = "bool" Then
SpecType = "{ ""type"": ""boolean"" }"
ElseIf kind = "date" Then
SpecType = "{ ""type"": ""string"", ""format"": ""date-time"", ""nullable"": true }"
Else
SpecType = "{ ""type"": ""string"" }"
End If
End Function

' SQLite DEFAULT text -> VBScript literal ("" when it is not a plain number or quoted string)
Function DefaultLiteral(d)
Dim s
DefaultLiteral = ""
If IsNull(d) Then Exit Function
s = Trim("" & d)
If Len(s) = 0 Then Exit Function
If IsNumeric(s) Then
DefaultLiteral = s
ElseIf Len(s) >= 2 And Left(s, 1) = "'" And Right(s, 1) = "'" Then
s = Mid(s, 2, Len(s) - 2)
DefaultLiteral = """" & Replace(Replace(s, "''", "'"), """", """""") & """"
End If
End Function

Function SampleValue(kind)
Select Case kind
Case "int": SampleValue = "1"
Case "real": SampleValue = "9.99"
Case "bool": SampleValue = "true"
Case "date": SampleValue = """2026-01-01 00:00:00"""
Case Else: SampleValue = """text"""
End Select
End Function

'==============================================================
' File helpers
'==============================================================
Function ReadTemplate(name)
Dim ts
Set ts = fso.OpenTextFile(Server.MapPath("/scripts/templates/" & name), 1)
ReadTemplate = ts.ReadAll
ts.Close
End Function

Function ReadFile(path)
Dim ts
Set ts = fso.OpenTextFile(Server.MapPath(path), 1)
ReadFile = ts.ReadAll
ts.Close
End Function

Sub WriteFile(path, text)
Dim tf
Set tf = fso.CreateTextFile(path, True)
tf.Write text
tf.Close
End Sub

Function EolOf(text)
If InStr(text, vbCrLf) > 0 Then
EolOf = vbCrLf
Else
EolOf = vbLf
End If
End Function

Function WithEol(text, eol)
WithEol = Replace(Replace(text, vbCrLf, vbLf), vbLf, eol)
End Function

' Appends a line to the file unless "marker" is already in it
Sub AppendIfMissing(path, marker, line)
Dim s, eol
s = ReadFile(path)
If InStr(1, s, marker, vbTextCompare) > 0 Then Exit Sub
eol = EolOf(s)
If Right(s, 1) <> vbLf Then s = s & eol
WriteFile Server.MapPath(path), s & line & eol
End Sub

' Inserts newText on a new line after the first line containing anchor (unless marker is already present)
Sub InsertAfterLine(path, anchor, marker, newText)
Dim s, eol, pos, eolPos
s = ReadFile(path)
If InStr(1, s, marker, vbTextCompare) > 0 Then Exit Sub
eol = EolOf(s)
pos = InStr(1, s, anchor, vbTextCompare)
If pos = 0 Then
WScript.Echo "Warning: anchor '" & anchor & "' not found in " & path & "; add the line yourself: " & newText
Exit Sub
End If
eolPos = InStr(pos, s, eol)
s = Left(s, eolPos - 1) & eol & newText & Mid(s, eolPos)
WriteFile Server.MapPath(path), s
End Sub

' Inserts newText before the line containing anchor (unless marker is already present)
Sub InsertBeforeLine(path, anchor, marker, newText)
Dim s, eol, pos, lineStart
s = ReadFile(path)
If InStr(1, s, marker, vbTextCompare) > 0 Then Exit Sub
eol = EolOf(s)
pos = InStr(1, s, anchor, vbTextCompare)
If pos = 0 Then
WScript.Echo "Warning: anchor '" & anchor & "' not found in " & path & "; add the routes yourself:" & vbCrLf & newText
Exit Sub
End If
lineStart = InStrRev(s, eol, pos)
If lineStart = 0 Then
lineStart = 1
Else
lineStart = lineStart + Len(eol)
End If
s = Left(s, lineStart - 1) & WithEol(newText, eol) & Mid(s, lineStart)
WriteFile Server.MapPath(path), s
End Sub

'==============================================================
' Misc helpers
'==============================================================
' SQLite declared type -> string | int | real | bool | date
Function ApiKind(declType)
Dim t
t = UCase("" & declType)
If InStr(t, "BOOL") > 0 Then
ApiKind = "bool"
ElseIf InStr(t, "DATE") > 0 Or InStr(t, "TIME") > 0 Then
ApiKind = "date"
ElseIf InStr(t, "CHAR") > 0 Or InStr(t, "CLOB") > 0 Or InStr(t, "TEXT") > 0 Then
ApiKind = "string"
ElseIf InStr(t, "INT") > 0 Then
ApiKind = "int"
ElseIf InStr(t, "REAL") > 0 Or InStr(t, "FLOA") > 0 Or InStr(t, "DOUB") > 0 Or InStr(t, "NUM") > 0 Or InStr(t, "DEC") > 0 Then
ApiKind = "real"
Else
ApiKind = "string"
End If
End Function

' CreatedAt / UpdatedAt text or date columns are filled in by the server, not accepted from clients
Function IsStampCol(name, kind)
IsStampCol = False
If kind = "string" Or kind = "date" Then
If LCase(name) = "createdat" Or LCase(name) = "updatedat" Then IsStampCol = True
End If
End Function

Function Pick(cond, a, b)
If cond Then
Pick = a
Else
Pick = b
End If
End Function

Function GetAppSetting(key, configFilePath)
Dim xml, nodes, node, j
If Not fso.FileExists(configFilePath) Then
GetAppSetting = "nothing"
Exit Function
End If
Set xml = CreateObject("Microsoft.XMLDOM")
xml.Async = False
xml.Load(configFilePath)
Set nodes = xml.selectNodes("//appSettings/add")
For j = 0 To nodes.Length - 1
Set node = nodes.Item(j)
If node.getAttribute("key") = key Then
GetAppSetting = node.getAttribute("value")
Exit Function
End If
Next
GetAppSetting = "nothing"
End Function

Function StrEqualCI(a, b)
StrEqualCI = (LCase(CStr(a)) = LCase(CStr(b)))
End Function

Function IsValidIdentifier(name)
Dim n, ch
IsValidIdentifier = False
If Len(name) = 0 Then Exit Function
For n = 1 To Len(name)
ch = Mid(name, n, 1)
If Not ((ch >= "a" And ch <= "z") Or (ch >= "A" And ch <= "Z") Or (ch >= "0" And ch <= "9") Or ch = "_") Then Exit Function
Next
IsValidIdentifier = True
End Function

+ 215
- 509
scripts/GenerateRepo.vbs View File

@@ -1,29 +1,34 @@
'==============================================================
' GeneratePOBOAndRepository.vbs
' GenerateRepo.vbs (AxonASP CLI + G3DB edition)
'
' Usage:
' cscript //nologo GeneratePOBOAndRepository.vbs /table:Orders /pk:OrderID [/cs:MyConnString] [/config:C:\path\web.config]
' Usage (runs under the AxonASP CLI in the container):
' scripts\gen.cmd repo /table:Products /pk:Id
'
' Reads connection string from web.config <appSettings>,
' discovers [table] schema, and generates:
' � POBO_<Table>.asp (Classic ASP class with typed Property Lets)
' � <Table>Repository.asp (parameterized CRUD + paging + search)
' Reads the connection string from public\web.config (<appSettings> ConnectionString = "<driver>:<dsn>"),
' discovers the table schema, and generates into app/models/:
' POBO_<Table>.asp (class with typed Property Let/Get)
' <Table>Repository.asp (parameterized CRUD + filter + paging + search, via DAL())
'
' Safe for Access or SQL Server connection strings.
' Schema discovery currently supports SQLite (PRAGMA table_info). Templates live in scripts/templates/.
'==============================================================

Option Explicit

' AxonASP CLI: provide the WScript object (see _cli.vbs)
Dim shimFso
Set shimFso = CreateObject("Scripting.FileSystemObject")
ExecuteGlobal shimFso.OpenTextFile(Server.MapPath("/scripts/_cli.vbs"), 1).ReadAll

'---------------- Args & paths ----------------
Dim fso, args, i, arg, parts
Dim tableName, primaryKey, csKey, configPath, thisFolder
Dim tableName, primaryKey, csKey, configPath, outDir

Set fso = CreateObject("Scripting.FileSystemObject")
Set args = WScript.Arguments

csKey = "ConnectionString"
thisFolder = fso.GetParentFolderName(WScript.ScriptFullName)
configPath = fso.GetParentFolderName(fso.GetParentFolderName(WScript.ScriptFullName)) & "\public\web.config"
configPath = Server.MapPath("/public/web.config")
outDir = Server.MapPath("/app/models")

For i = 0 To args.Count - 1
arg = args(i)
@@ -39,482 +44,257 @@ For i = 0 To args.Count - 1
Next

If Len(tableName) = 0 Or Len(primaryKey) = 0 Then
WScript.Echo "Usage: cscript //nologo GeneratePOBOAndRepository.vbs /table:<TableName> /pk:<PrimaryKey> [/cs:<ConnStringKey>] [/config:<PathToWebConfig>]"
WScript.Echo "Usage: scripts\gen.cmd repo /table:<TableName> /pk:<PrimaryKey>"
WScript.Quit 1
End If

' Validate table name format (alphanumeric, underscore only - prevent SQL injection)
If Not IsValidIdentifier(tableName) Then
WScript.Echo "Error: Invalid table name format. Only letters, numbers, and underscores are allowed."
WScript.Quit 1
End If

' Validate primary key format
If Not IsValidIdentifier(primaryKey) Then
WScript.Echo "Error: Invalid primary key format. Only letters, numbers, and underscores are allowed."
WScript.Quit 1
End If

'---------------- Config & connection ----------------
Dim connStr
Dim connStr, p, driver, dsn
connStr = GetAppSetting(csKey, configPath)
If connStr = "nothing" Then
WScript.Echo "Error: Key '" & csKey & "' not found in " & configPath
WScript.Quit 1
End If

Dim conn
Set conn = CreateObject("ADODB.Connection")
On Error Resume Next
conn.Open connStr
If Err.Number <> 0 Then
WScript.Echo "DB connection failed: " & Err.Description
p = InStr(connStr, ":")
If p < 2 Then
WScript.Echo "Error: ConnectionString must look like '<driver>:<dsn>'. Got: " & connStr
WScript.Quit 1
End If
On Error GoTo 0

'---------------- Discover schema (portable) ----------------
' Strategy:
' 1) Try OpenSchema(adSchemaColumns) for rich metadata.
' 2) Fallback to "SELECT * WHERE 1=0" to at least get names/types.
Const adSchemaColumns = 4

Dim cols(), types(), nullable(), ordinals(), fld, idx
Dim haveSchema : haveSchema = False

On Error Resume Next
Dim rsCols
Set rsCols = conn.OpenSchema(adSchemaColumns, Array(Empty, Empty, tableName, Empty))
If Err.Number = 0 Then
idx = -1
Do Until rsCols.EOF
idx = idx + 1
ReDim Preserve cols(idx), types(idx), nullable(idx), ordinals(idx)
cols(idx) = CStr(rsCols("COLUMN_NAME"))
types(idx) = Nz(rsCols("DATA_TYPE"), 0) ' ADO type enum
nullable(idx) = LCase(CStr(Nz(rsCols("IS_NULLABLE"), "YES"))) = "yes"
ordinals(idx) = CLng(Nz(rsCols("ORDINAL_POSITION"), idx+1))
rsCols.MoveNext
Loop
rsCols.Close : Set rsCols = Nothing
haveSchema = (idx >= 0)
Else
Err.Clear
driver = LCase(Left(connStr, p - 1))
dsn = Mid(connStr, p + 1)

If driver <> "sqlite" And driver <> "sqlite3" Then
WScript.Echo "Error: schema discovery is implemented for SQLite only (driver is '" & driver & "')."
WScript.Quit 1
End If
On Error GoTo 0

If Not haveSchema Then
' Fallback: get names/types from zero-row select
On Error Resume Next
Dim rsProbe
Set rsProbe = conn.Execute("SELECT * FROM " & QI(tableName) & " WHERE 1=0")
If Err.Number <> 0 Then
WScript.Echo "Error querying table [" & tableName & "]: " & Err.Description
conn.Close : Set conn = Nothing
WScript.Quit 1
End If
On Error GoTo 0

idx = -1
For Each fld In rsProbe.Fields
idx = idx + 1
ReDim Preserve cols(idx), types(idx), nullable(idx), ordinals(idx)
cols(idx) = fld.Name
types(idx) = fld.Type
nullable(idx) = True ' Unknown; assume nullable
ordinals(idx) = idx + 1
Next
rsProbe.Close : Set rsProbe = Nothing

Dim db
Set db = Server.CreateObject("G3DB")
If Not db.Open("sqlite", dsn) Then
WScript.Echo "DB connection failed: " & db.LastError
WScript.Quit 1
End If

If idx < 0 Then
WScript.Echo "No columns found for table [" & tableName & "]."
'---------------- Discover schema ----------------
Dim cols(), kinds(), idx, rs
idx = -1
Set rs = db.Query("PRAGMA table_info(" & tableName & ")")
If IsEmpty(rs) Then
WScript.Echo "Error reading table [" & tableName & "]: " & db.LastError
WScript.Quit 1
End If

' Sort metadata by ordinal (defensive)
Call ArraySortByParallel(ordinals, Array(cols, types, nullable))
Do Until rs.EOF
idx = idx + 1
ReDim Preserve cols(idx), kinds(idx)
cols(idx) = CStr(rs(1)) ' name
kinds(idx) = TypeKind(rs(2)) ' declared type -> string/number/bool/date
rs.MoveNext
Loop
rs.Close
db.Close

If idx < 0 Then
WScript.Echo "No columns found for table [" & tableName & "]. Run the migrations first."
WScript.Quit 1
End If

' Validate PK exists
If Not InArrayInsensitive(cols, primaryKey) Then
WScript.Echo "Primary key '" & primaryKey & "' not found in table [" & tableName & "]."
WScript.Quit 1
End If

'---------------- Generate POBO_<Table>.asp ----------------
Dim poboOut
poboOut = BuildPOBO(cols, types, tableName, primaryKey)
'---------------- Generate files from templates ----------------
If Not fso.FolderExists(outDir) Then fso.CreateFolder outDir

Dim poboPath, tf
poboPath = fso.BuildPath(thisFolder, "POBO_" & tableName & ".asp")
Set tf = fso.CreateTextFile(poboPath, True, False)
tf.Write poboOut
tf.Close
Set tf = Nothing
WScript.Echo "POBO class written to: " & poboPath
Dim poboPath, repoPath
poboPath = outDir & "/POBO_" & tableName & ".asp"
repoPath = outDir & "/" & tableName & "Repository.asp"

'---------------- Generate <Table>Repository.asp ----------------
Dim repoOut
repoOut = BuildRepository(cols, tableName, primaryKey)
WriteFile poboPath, BuildPOBO(cols, kinds, tableName, primaryKey)
WScript.Echo "POBO class written to: " & poboPath

Dim repoPath
repoPath = fso.BuildPath(thisFolder, tableName & "Repository.asp")
Set tf = fso.CreateTextFile(repoPath, True, False)
tf.Write repoOut
tf.Close
Set tf = Nothing
WriteFile repoPath, BuildRepository(cols, tableName, primaryKey)
WScript.Echo "Repository written to: " & repoPath

'---------------- Cleanup ----------------
conn.Close : Set conn = Nothing
WScript.Echo ""
WScript.Echo "Next steps:"
WScript.Echo "1. Include both files from app/models/autoload_models.asp:"
WScript.Echo " <!--#include file=""POBO_" & tableName & ".asp""-->"
WScript.Echo " <!--#include file=""" & tableName & "Repository.asp""-->"

Set fso = Nothing

'==============================================================
' POBO generator (your example, integrated)
' Generators
'==============================================================
Function BuildPOBO(byRef colsArr, byRef typesArr, ByVal tName, ByVal pk)
Dim classDef, idxLocal, name, ftype
Dim parts()
ReDim parts(1000) ' Pre-allocate for performance
Dim partIdx : partIdx = 0

' Build using array for performance (StringBuilder pattern)
parts(partIdx) = "<%" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = "' Auto-generated POBO for table [" & tName & "]" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = "' Generated on " & Now() & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = "' Generator: GenerateRepo.vbs v1.0" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = "'" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = "' Dependencies: core/helpers.asp (QuoteValue function)" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = vbCrLf & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = "Class POBO_" & tName & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " ' Public array of all property names" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " Public Properties" & vbCrLf & vbCrLf : partIdx = partIdx + 1

' Private backing fields
For idxLocal = 0 To UBound(colsArr)
parts(partIdx) = " Private p" & colsArr(idxLocal) & vbCrLf : partIdx = partIdx + 1
Next
Function ReadTemplate(name)
Dim ts
Set ts = fso.OpenTextFile(Server.MapPath("/scripts/templates/" & name), 1)
ReadTemplate = ts.ReadAll
ts.Close
End Function

' Initializer with defaults
parts(partIdx) = vbCrLf & " Private Sub Class_Initialize()" & vbCrLf : partIdx = partIdx + 1
For idxLocal = 0 To UBound(colsArr)
Select Case typesArr(idxLocal)
Case 200,201,202,203 ' adChar, adVarChar, adVarWChar, adWChar (strings)
parts(partIdx) = " p" & colsArr(idxLocal) & " = """"" & vbCrLf : partIdx = partIdx + 1
Case 7,133,135 ' adDate, adDBDate, adDBTimeStamp (dates)
parts(partIdx) = " p" & colsArr(idxLocal) & " = #1/1/1970#" & vbCrLf : partIdx = partIdx + 1
Case 2,3,4,5,6,14,131 ' adSmallInt, adInteger, adSingle, adDouble, adCurrency, adDecimal, adNumeric
parts(partIdx) = " p" & colsArr(idxLocal) & " = 0" & vbCrLf : partIdx = partIdx + 1
Case 11 ' adBoolean
parts(partIdx) = " p" & colsArr(idxLocal) & " = False" & vbCrLf : partIdx = partIdx + 1
Case Else
parts(partIdx) = " p" & colsArr(idxLocal) & " = Null" & vbCrLf : partIdx = partIdx + 1
End Select
Next
Sub WriteFile(path, text)
Dim tf
Set tf = fso.CreateTextFile(path, True)
tf.Write text
tf.Close
End Sub

Function BuildPOBO(colsArr, kindsArr, tName, pk)
Dim fields, defaults, propList, props, k, name, kind
fields = "" : defaults = "" : propList = "" : props = ""

For k = 0 To UBound(colsArr)
name = colsArr(k)
kind = kindsArr(k)

parts(partIdx) = " Properties = Array(""" & Join(colsArr, """,""") & """)" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " End Sub" & vbCrLf & vbCrLf : partIdx = partIdx + 1

parts(partIdx) = " Public Property Get PrimaryKey()" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " PrimaryKey = """ & pk & """" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " End Property" & vbCrLf & vbCrLf : partIdx = partIdx + 1

parts(partIdx) = " Public Property Get TableName()" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " TableName = """ & tName & """" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " End Property" & vbCrLf & vbCrLf : partIdx = partIdx + 1

' Get/Let with coercion
For idxLocal = 0 To UBound(colsArr)
name = colsArr(idxLocal)
ftype = typesArr(idxLocal)

parts(partIdx) = " Public Property Get " & name & "()" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " " & name & " = p" & name & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " End Property" & vbCrLf & vbCrLf : partIdx = partIdx + 1

parts(partIdx) = " Public Property Let " & name & "(val)" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " On Error Resume Next" & vbCrLf : partIdx = partIdx + 1

Select Case ftype
Case 200,201,202,203 ' Strings
parts(partIdx) = " p" & name & " = CStr(val)" & vbCrLf : partIdx = partIdx + 1
Case 7 ' Dates
parts(partIdx) = " p" & name & " = CDate(val)" & vbCrLf : partIdx = partIdx + 1
Case 133,135 ' Timestamps
parts(partIdx) = " p" & name & " = QuoteValue(val)" & vbCrLf : partIdx = partIdx + 1
Case 11 ' Boolean
parts(partIdx) = " p" & name & " = CBool(val)" & vbCrLf : partIdx = partIdx + 1
Case Else ' Numeric or other
parts(partIdx) = " If IsNumeric(val) Then" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " p" & name & " = CDbl(val)" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " Else" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " p" & name & " = val" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " End If" & vbCrLf : partIdx = partIdx + 1
fields = fields & " Private p" & name & vbCrLf

Select Case kind
Case "string": defaults = defaults & " p" & name & " = """"" & vbCrLf
Case "number": defaults = defaults & " p" & name & " = 0" & vbCrLf
Case "bool": defaults = defaults & " p" & name & " = False" & vbCrLf
Case Else: defaults = defaults & " p" & name & " = Null" & vbCrLf
End Select

parts(partIdx) = " If Err.Number <> 0 Then" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " Err.Raise Err.Number, ""POBO_" & tName & "." & name & """, ""Invalid value for " & name & ": "" & Err.Description" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " End If" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " On Error GoTo 0" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = " End Property" & vbCrLf & vbCrLf : partIdx = partIdx + 1
If k > 0 Then propList = propList & ","
propList = propList & """" & name & """"

props = props & " Public Property Get " & name & "()" & vbCrLf
props = props & " " & name & " = p" & name & vbCrLf
props = props & " End Property" & vbCrLf & vbCrLf
props = props & " Public Property Let " & name & "(val)" & vbCrLf
props = props & " On Error Resume Next" & vbCrLf
Select Case kind
Case "string"
props = props & " p" & name & " = CStr(val)" & vbCrLf
Case "bool"
props = props & " p" & name & " = CBool(val)" & vbCrLf
Case "date"
props = props & " p" & name & " = CDate(val)" & vbCrLf
Case Else
props = props & " If IsNumeric(val) Then" & vbCrLf
props = props & " p" & name & " = CDbl(val)" & vbCrLf
props = props & " Else" & vbCrLf
props = props & " p" & name & " = val" & vbCrLf
props = props & " End If" & vbCrLf
End Select
props = props & " If Err.Number <> 0 Then" & vbCrLf
props = props & " Err.Raise Err.Number, ""POBO_" & tName & "." & name & """, ""Invalid value for " & name & ": "" & Err.Description" & vbCrLf
props = props & " End If" & vbCrLf
props = props & " On Error GoTo 0" & vbCrLf
props = props & " End Property" & vbCrLf & vbCrLf
Next

parts(partIdx) = "End Class" & vbCrLf : partIdx = partIdx + 1
parts(partIdx) = "%>" & vbCrLf : partIdx = partIdx + 1

' Join array for performance
ReDim Preserve parts(partIdx - 1)
BuildPOBO = Join(parts, "")
Dim t
t = ReadTemplate("POBO.tpl.asp")
t = Replace(t, "{{TABLE}}", tName)
t = Replace(t, "{{PK}}", pk)
t = Replace(t, "{{DATE}}", CStr(Now()))
t = Replace(t, "{{FIELDS}}", fields)
t = Replace(t, "{{DEFAULTS}}", defaults)
t = Replace(t, "{{PROPLIST}}", propList)
t = Replace(t, "{{PROPERTIES}}", props)
BuildPOBO = t
End Function

'==============================================================
' Repository generator (parameterized; DAL.* expected)
'==============================================================
Function BuildRepository(byRef colsArr, ByVal tName, ByVal pk)
Dim insertCols(), updateCols(), allCols(), idCol
Dim iLocal, cName
idCol = pk

' Copy columns (no array-to-array assignment in VBScript)
ReDim allCols(UBound(colsArr))
For iLocal = 0 To UBound(colsArr)
allCols(iLocal) = colsArr(iLocal)
Next
Function BuildRepository(colsArr, tName, pk)
Dim selectList, colList, mapLines, insCols, insPh, insParams, updSet, updParams, k, c
selectList = "" : colList = "" : mapLines = "" : insCols = "" : insPh = "" : insParams = "" : updSet = "" : updParams = ""

' Insert/Update sets: exclude PK
Dim insIdx : insIdx = -1
For Each cName In colsArr
If Not StrEqualCI(cName, idCol) Then
insIdx = insIdx + 1
ReDim Preserve insertCols(insIdx)
insertCols(insIdx) = cName
For k = 0 To UBound(colsArr)
c = colsArr(k)
If k > 0 Then
selectList = selectList & ", "
colList = colList & "|"
End If
Next

Dim updIdx : updIdx = -1
For Each cName In colsArr
If Not StrEqualCI(cName, idCol) Then
updIdx = updIdx + 1
ReDim Preserve updateCols(updIdx)
updateCols(updIdx) = cName
selectList = selectList & QI(c)
colList = colList & c
mapLines = mapLines & " If Not IsNull(rs(" & k & ")) Then m." & c & " = rs(" & k & ")" & vbCrLf

If Not StrEqualCI(c, pk) Then
If Len(insCols) > 0 Then
insCols = insCols & ", "
insPh = insPh & ", "
insParams = insParams & ", "
updSet = updSet & ", "
updParams = updParams & ", "
End If
insCols = insCols & QI(c)
insPh = insPh & "?"
insParams = insParams & "model." & c
updSet = updSet & QI(c) & " = ?"
updParams = updParams & "model." & c
End If
Next

Dim QTable, QPK, selectList, selectBase
QTable = QI(tName)
QPK = QI(idCol)
selectList = JoinQI(allCols, ", ")
selectBase = "Select " & selectList & " FROM " & QTable

Dim out
out = out & "<%" & vbCrLf
out = out & "' Auto-generated Repository for table [" & tName & "]" & vbCrLf
out = out & "' Generated on " & Now() & vbCrLf
out = out & "' Generator: GenerateRepo.vbs v1.0" & vbCrLf
out = out & "'" & vbCrLf
out = out & "' Dependencies:" & vbCrLf
out = out & "' - core/lib.DAL.asp (DAL singleton for database access)" & vbCrLf
out = out & "' - core/lib.AutoMapper.asp (Automapper for object mapping)" & vbCrLf
out = out & "' - core/lib.Collections.asp (LinkedList_Class)" & vbCrLf
out = out & "' - core/lib.helpers.asp (KVUnzip, BuildOrderBy, QI, Destroy)" & vbCrLf
out = out & vbCrLf & vbCrLf

Dim className : className = tName & "Repository_Class"
out = out & "Class " & className & vbCrLf & vbCrLf

' FindByID
out = out & " Public Function FindByID(id)" & vbCrLf
out = out & " Dim sql : sql = """ & selectBase & " WHERE " & QPK & " = ?""" & vbCrLf
out = out & " Dim rs : Set rs = DAL.Query(sql, Array(id))" & vbCrLf
out = out & " If rs.EOF Then" & vbCrLf
out = out & " Err.Raise 1, """ & className & """, RecordNotFoundException(""" & idCol & """, id)" & vbCrLf
out = out & " Else" & vbCrLf
out = out & " Set FindByID = Automapper.AutoMap(rs, ""POBO_" & tName & """)" & vbCrLf
out = out & " End If" & vbCrLf
out = out & " Destroy rs" & vbCrLf
out = out & " End Function" & vbCrLf & vbCrLf

' GetAll -> Find
out = out & " Public Function GetAll(orderBy)" & vbCrLf
out = out & " Set GetAll = Find(Empty, orderBy)" & vbCrLf
out = out & " End Function" & vbCrLf & vbCrLf

' Find
out = out & " Public Function Find(where_kvarray, order_string_or_array)" & vbCrLf
out = out & " Dim sql : sql = """ & selectBase & """" & vbCrLf
out = out & " Dim where_keys, where_values, i" & vbCrLf
out = out & " If Not IsEmpty(where_kvarray) Then" & vbCrLf
out = out & " KVUnzip where_kvarray, where_keys, where_values" & vbCrLf
out = out & " If Not IsEmpty(where_keys) Then" & vbCrLf
out = out & " sql = sql & "" WHERE """ & vbCrLf
out = out & " For i = 0 To UBound(where_keys)" & vbCrLf
out = out & " If i > 0 Then sql = sql & "" AND """ & vbCrLf
out = out & " sql = sql & "" "" & QI(where_keys(i)) & "" = ?""" & vbCrLf
out = out & " Next" & vbCrLf
out = out & " End If" & vbCrLf
out = out & " End If" & vbCrLf
out = out & " sql = sql & BuildOrderBy(order_string_or_array, """ & QPK & """)" & vbCrLf
out = out & " Dim rs : Set rs = DAL.Query(sql, where_values)" & vbCrLf
out = out & " Dim list : Set list = new LinkedList_Class" & vbCrLf
out = out & " Do Until rs.EOF" & vbCrLf
out = out & " list.Push Automapper.AutoMap(rs, ""POBO_" & tName & """)" & vbCrLf
out = out & " rs.MoveNext" & vbCrLf
out = out & " Loop" & vbCrLf
out = out & " Set Find = list" & vbCrLf
out = out & " Destroy rs" & vbCrLf
out = out & " End Function" & vbCrLf & vbCrLf

' FindPaged
out = out & " Public Function FindPaged(where_kvarray, order_string_or_array, per_page, page_num, ByRef page_count, ByRef record_count)" & vbCrLf
out = out & " Dim sql : sql = """ & selectBase & """" & vbCrLf
out = out & " Dim where_keys, where_values, i" & vbCrLf
out = out & " If Not IsEmpty(where_kvarray) Then" & vbCrLf
out = out & " KVUnzip where_kvarray, where_keys, where_values" & vbCrLf
out = out & " If Not IsEmpty(where_keys) Then" & vbCrLf
out = out & " sql = sql & "" WHERE """ & vbCrLf
out = out & " For i = 0 To UBound(where_keys)" & vbCrLf
out = out & " If i > 0 Then sql = sql & "" AND """ & vbCrLf
out = out & " sql = sql & "" "" & QI(where_keys(i)) & "" = ?""" & vbCrLf
out = out & " Next" & vbCrLf
out = out & " End If" & vbCrLf
out = out & " End If" & vbCrLf
out = out & " sql = sql & BuildOrderBy(order_string_or_array, """ & QPK & """)" & vbCrLf
out = out & " Dim rs : Set rs = DAL.PagedQuery(sql, where_values, per_page, page_num)" & vbCrLf
out = out & " If Not rs.EOF Then" & vbCrLf
out = out & " rs.PageSize = per_page" & vbCrLf
out = out & " rs.AbsolutePage = page_num" & vbCrLf
out = out & " page_count = rs.PageCount" & vbCrLf
out = out & " record_count = rs.RecordCount" & vbCrLf
out = out & " End If" & vbCrLf
out = out & " Set FindPaged = PagedList(rs, per_page)" & vbCrLf
out = out & " Destroy rs" & vbCrLf
out = out & " End Function" & vbCrLf & vbCrLf

' SearchTablePaged (OR col LIKE ?)
out = out & " Public Function SearchTablePaged(columns_array, search_value, order_string_or_array, per_page, page_num, ByRef page_count, ByRef record_count)" & vbCrLf
out = out & " Dim sql : sql = """ & selectBase & """" & vbCrLf
out = out & " Dim i, params()" & vbCrLf
out = out & " If IsArray(columns_array) And UBound(columns_array) >= 0 Then" & vbCrLf
out = out & " sql = sql & "" WHERE """ & vbCrLf
out = out & " ReDim params(UBound(columns_array))" & vbCrLf
out = out & " For i = 0 To UBound(columns_array)" & vbCrLf
out = out & " If i > 0 Then sql = sql & "" OR """ & vbCrLf
out = out & " sql = sql & "" "" & QI(columns_array(i)) & "" LIKE ?""" & vbCrLf
out = out & " params(i) = ""%"" & search_value & ""%""" & vbCrLf
out = out & " Next" & vbCrLf
out = out & " End If" & vbCrLf
out = out & " sql = sql & BuildOrderBy(order_string_or_array, """ & QPK & """)" & vbCrLf
out = out & " Dim rs : Set rs = DAL.PagedQuery(sql, params, per_page, page_num)" & vbCrLf
out = out & " If Not rs.EOF Then" & vbCrLf
out = out & " rs.PageSize = per_page" & vbCrLf
out = out & " rs.AbsolutePage = page_num" & vbCrLf
out = out & " page_count = rs.PageCount" & vbCrLf
out = out & " record_count = rs.RecordCount" & vbCrLf
out = out & " End If" & vbCrLf
out = out & " Set SearchTablePaged = PagedList(rs, per_page)" & vbCrLf
out = out & " Destroy rs" & vbCrLf
out = out & " End Function" & vbCrLf & vbCrLf

' PagedList helper
out = out & " Private Function PagedList(rs, per_page)" & vbCrLf
out = out & " Dim list : Set list = new LinkedList_Class" & vbCrLf
out = out & " Dim x : x = 0" & vbCrLf
out = out & " Do While (per_page <= 0 Or x < per_page) And Not rs.EOF" & vbCrLf
out = out & " list.Push Automapper.AutoMap(rs, ""POBO_" & tName & """)" & vbCrLf
out = out & " x = x + 1" & vbCrLf
out = out & " rs.MoveNext" & vbCrLf
out = out & " Loop" & vbCrLf
out = out & " Set PagedList = list" & vbCrLf
out = out & " End Function" & vbCrLf & vbCrLf

' AddNew
out = out & " Public Sub AddNew(ByRef model)" & vbCrLf
out = out & " Dim sql : sql = ""INSERT INTO " & QTable & " (" & JoinQI(insertCols, ", ") & ") VALUES (" & Placeholders(UBound(insertCols)+1) & ")""" & vbCrLf
out = out & " DAL.Execute sql, " & BuildModelParamsArray("model", insertCols) & vbCrLf
out = out & " " & vbCrLf
out = out & " ' Retrieve the newly inserted ID" & vbCrLf
out = out & " On Error Resume Next" & vbCrLf
out = out & " Dim rsId : Set rsId = DAL.Query(""SELECT @@IDENTITY AS NewID"", Empty)" & vbCrLf
out = out & " If Err.Number <> 0 Then" & vbCrLf
out = out & " ' Fallback for Access databases" & vbCrLf
out = out & " Err.Clear" & vbCrLf
out = out & " Set rsId = DAL.Query(""SELECT TOP 1 " & QPK & " FROM " & QTable & " ORDER BY " & QPK & " DESC"", Empty)" & vbCrLf
out = out & " End If" & vbCrLf
out = out & " On Error GoTo 0" & vbCrLf
out = out & " " & vbCrLf
out = out & " If Not rsId.EOF Then" & vbCrLf
out = out & " If Not IsNull(rsId(0)) Then model." & idCol & " = rsId(0)" & vbCrLf
out = out & " End If" & vbCrLf
out = out & " Destroy rsId" & vbCrLf
out = out & " End Sub" & vbCrLf & vbCrLf

' Update
out = out & " Public Sub Update(model)" & vbCrLf
out = out & " Dim sql : sql = ""UPDATE " & QTable & " SET " & JoinSetters(updateCols) & " WHERE " & QPK & " = ?""" & vbCrLf
out = out & " DAL.Execute sql, " & BuildModelParamsArrayWithPK("model", updateCols, idCol) & vbCrLf
out = out & " End Sub" & vbCrLf & vbCrLf

' Delete
out = out & " Public Sub Delete(id)" & vbCrLf
out = out & " Dim sql : sql = ""DELETE FROM " & QTable & " WHERE " & QPK & " = ?""" & vbCrLf
out = out & " DAL.Execute sql, Array(id)" & vbCrLf
out = out & " End Sub" & vbCrLf & vbCrLf

' Exceptions & helpers
out = out & " Private Function RecordNotFoundException(ByVal field_name, ByVal field_val)" & vbCrLf
out = out & " RecordNotFoundException = """ & tName & " record was not found with "" & field_name & "" = '"" & field_val & ""'.""" & vbCrLf
out = out & " End Function" & vbCrLf & vbCrLf

out = out & " Private Function QI(name)" & vbCrLf
out = out & " QI = ""["" & Replace(CStr(name), ""]"", ""]]"") & ""]""" & vbCrLf
out = out & " End Function" & vbCrLf & vbCrLf

out = out & " Private Function BuildOrderBy(orderArg, defaultCol)" & vbCrLf
out = out & " Dim s : s = """"" & vbCrLf
out = out & " If IsEmpty(orderArg) Or IsNull(orderArg) Or orderArg = """" Then" & vbCrLf
out = out & " s = "" ORDER BY "" & defaultCol & "" ASC""" & vbCrLf
out = out & " ElseIf IsArray(orderArg) Then" & vbCrLf
out = out & " Dim i : s = "" ORDER BY """ & vbCrLf
out = out & " For i = 0 To UBound(orderArg)" & vbCrLf
out = out & " If i > 0 Then s = s & "", """ & vbCrLf
out = out & " s = s & QI(orderArg(i))" & vbCrLf
out = out & " Next" & vbCrLf
out = out & " Else" & vbCrLf
out = out & " s = "" ORDER BY "" & QI(orderArg)" & vbCrLf
out = out & " End If" & vbCrLf
out = out & " BuildOrderBy = s" & vbCrLf
out = out & " End Function" & vbCrLf

out = out & "End Class" & vbCrLf & vbCrLf

out = out & "Dim " & tName & "Repository__Singleton" & vbCrLf
out = out & "Function " & tName & "Repository()" & vbCrLf
out = out & " If IsEmpty(" & tName & "Repository__Singleton) Then" & vbCrLf
out = out & " Set " & tName & "Repository__Singleton = new " & className & vbCrLf
out = out & " End If" & vbCrLf
out = out & " Set " & tName & "Repository = " & tName & "Repository__Singleton" & vbCrLf
out = out & "End Function" & vbCrLf

out = out & "%>" & vbCrLf

BuildRepository = out
Dim t
t = ReadTemplate("Repository.tpl.asp")
t = Replace(t, "{{TABLE}}", tName)
t = Replace(t, "{{PK}}", pk)
t = Replace(t, "{{QTABLE}}", QI(tName))
t = Replace(t, "{{QPK}}", QI(pk))
t = Replace(t, "{{DATE}}", CStr(Now()))
t = Replace(t, "{{COLUMN_LIST}}", colList)
t = Replace(t, "{{SELECT_LIST}}", selectList)
t = Replace(t, "{{MAP_LINES}}", mapLines)
t = Replace(t, "{{INSERT_COLS}}", insCols)
t = Replace(t, "{{INSERT_PLACEHOLDERS}}", insPh)
t = Replace(t, "{{INSERT_PARAMS}}", "Array(" & insParams & ")")
t = Replace(t, "{{UPDATE_SET}}", updSet)
t = Replace(t, "{{UPDATE_PARAMS}}", "Array(" & updParams & ", model." & pk & ")")
BuildRepository = t
End Function

'==============================================================
' Helpers (generator side)
'==============================================================
' Quoted identifier for use inside the generated VBScript string literals: "Col" -> ""Col""
Function QI(name)
QI = """""" & Replace(CStr(name), """", """""""""") & """"""
End Function

' SQLite declared type -> simple kind (follows SQLite's affinity rules, roughly)
Function TypeKind(declType)
Dim t
t = UCase("" & declType)
If InStr(t, "BOOL") > 0 Then
TypeKind = "bool"
ElseIf InStr(t, "DATE") > 0 Or InStr(t, "TIME") > 0 Then
TypeKind = "date"
ElseIf InStr(t, "CHAR") > 0 Or InStr(t, "CLOB") > 0 Or InStr(t, "TEXT") > 0 Then
TypeKind = "string"
ElseIf InStr(t, "INT") > 0 Or InStr(t, "REAL") > 0 Or InStr(t, "FLOA") > 0 Or InStr(t, "DOUB") > 0 Or InStr(t, "NUM") > 0 Or InStr(t, "DEC") > 0 Then
TypeKind = "number"
ElseIf Len(t) = 0 Then
TypeKind = "string"
Else
TypeKind = "string"
End If
End Function

Function GetAppSetting(key, configFilePath)
Dim xml, nodes, node, j, localFso
Set localFso = CreateObject("Scripting.FileSystemObject")
Set xml = CreateObject("Microsoft.XMLDOM")
If Not localFso.FileExists(configFilePath) Then
GetAppSetting = "nothing" : Exit Function
Dim xml, nodes, node, j
If Not fso.FileExists(configFilePath) Then
GetAppSetting = "nothing"
Exit Function
End If
Set xml = CreateObject("Microsoft.XMLDOM")
xml.Async = False
xml.Load(configFilePath)
If xml.ParseError.ErrorCode <> 0 Then
GetAppSetting = "nothing" : Exit Function
End If
Set nodes = xml.selectNodes("//appSettings/add")
For j = 0 To nodes.Length - 1
Set node = nodes.Item(j)
@@ -526,35 +306,14 @@ Function GetAppSetting(key, configFilePath)
GetAppSetting = "nothing"
End Function

Function Nz(val, defaultVal)
If IsNull(val) Or IsEmpty(val) Then
Nz = defaultVal
Else
Nz = val
End If
End Function

Sub ArraySortByParallel(keys, arrs)
Dim iLocal, jLocal, kLocal, tmpKey, tmp
For iLocal = 0 To UBound(keys) - 1
For jLocal = iLocal + 1 To UBound(keys)
If keys(jLocal) < keys(iLocal) Then
tmpKey = keys(iLocal) : keys(iLocal) = keys(jLocal) : keys(jLocal) = tmpKey
For kLocal = 0 To UBound(arrs)
tmp = arrs(kLocal)(iLocal)
arrs(kLocal)(iLocal) = arrs(kLocal)(jLocal)
arrs(kLocal)(jLocal) = tmp
Next
End If
Next
Next
End Sub

Function InArrayInsensitive(a, val)
Dim z
InArrayInsensitive = False
For z = 0 To UBound(a)
If StrEqualCI(a(z), val) Then InArrayInsensitive = True : Exit Function
If StrEqualCI(a(z), val) Then
InArrayInsensitive = True
Exit Function
End If
Next
End Function

@@ -562,76 +321,23 @@ Function StrEqualCI(a, b)
StrEqualCI = (LCase(CStr(a)) = LCase(CStr(b)))
End Function

Function QI(name)
QI = "[" & Replace(CStr(name), "]", "]]") & "]"
End Function

Function JoinQI(a, sep)
Dim j, s : s = ""
For j = 0 To UBound(a)
If j > 0 Then s = s & sep
s = s & QI(a(j))
Next
JoinQI = s
End Function

Function Placeholders(n)
Dim j, s : s = ""
For j = 1 To n
If j > 1 Then s = s & ", "
s = s & "?"
Next
Placeholders = s
End Function

Function JoinSetters(a)
Dim j, s : s = ""
For j = 0 To UBound(a)
If j > 0 Then s = s & ", "
s = s & QI(a(j)) & " = ?"
Next
JoinSetters = s
End Function

Function BuildModelParamsArray(modelName, a)
Dim j, s : s = "Array("
For j = 0 To UBound(a)
If j > 0 Then s = s & ", "
s = s & modelName & "." & a(j)
Next
s = s & ")"
BuildModelParamsArray = s
End Function

Function BuildModelParamsArrayWithPK(modelName, a, pk)
Dim j, s : s = "Array("
For j = 0 To UBound(a)
If j > 0 Then s = s & ", "
s = s & modelName & "." & a(j)
Next
s = s & ", " & modelName & "." & pk & ")"
BuildModelParamsArrayWithPK = s
End Function

' Validate identifier (table name, column name, etc.)
Function IsValidIdentifier(name)
If IsEmpty(name) Or Len(name) = 0 Then
Dim n, ch
If IsEmpty(name) Then
IsValidIdentifier = False
Exit Function
End If

Dim i, ch
For i = 1 To Len(name)
ch = Mid(name, i, 1)
' Allow a-z, A-Z, 0-9, and underscore only
If Not ((ch >= "a" And ch <= "z") Or _
(ch >= "A" And ch <= "Z") Or _
(ch >= "0" And ch <= "9") Or _
ch = "_") Then
If Len(name) = 0 Then
IsValidIdentifier = False
Exit Function
End If
For n = 1 To Len(name)
ch = Mid(name, n, 1)
If Not ((ch >= "a" And ch <= "z") Or (ch >= "A" And ch <= "Z") Or (ch >= "0" And ch <= "9") Or ch = "_") Then
IsValidIdentifier = False
Exit Function
End If
Next

IsValidIdentifier = True
End Function

+ 33
- 0
scripts/_cli.vbs View File

@@ -0,0 +1,33 @@
'=======================================================================================================================
' WScript compatibility shim for AxonASP CLI (axonasp-cli -m vbscript)
'=======================================================================================================================
' AxonASP has no WScript host object. This defines the parts the generator scripts use:
' WScript.Arguments (Count, Item) - read from environment variables ARG1..ARG9 (set by scripts\gen.cmd)
' WScript.ScriptFullName - a path inside scripts/ (only its folder is used)
' WScript.Echo / WScript.Quit - Quit stops the script (exit code is not propagated by the CLI)
' Loaded by each generator with: ExecuteGlobal <contents of _cli.vbs>
Class WScript_Shim
Public Arguments
Public ScriptFullName

Private Sub Class_Initialize()
Dim sh, i, v
Set sh = CreateObject("WScript.Shell")
Set Arguments = CreateObject("Scripting.Dictionary")
For i = 1 To 9
v = sh.ExpandEnvironmentStrings("%ARG" & i & "%")
If v = "%ARG" & i & "%" Then Exit For
Arguments.Add Arguments.Count, v
Next
ScriptFullName = Server.MapPath("/scripts/generator.vbs")
End Sub

Public Sub Echo(s)
Response.Write s & vbCrLf
End Sub

Public Sub Quit(code)
Response.End
End Sub
End Class
Dim WScript : Set WScript = New WScript_Shim

+ 0
- 320
scripts/deploy-iis-git.ps1 View File

@@ -1,320 +0,0 @@
<#
.SYNOPSIS
Validates, packages, and deploys this repository to its dedicated IIS site.

.DESCRIPTION
The controller packages the complete repository, computes SHA-256, transfers
the package and host installer over OpenSSH, and invokes the installer.
-LocalPreflightOnly validates source provenance, XML, package layout, and
archive safety without connecting. -PreflightOnly additionally streams the
installer to the host and runs its read-only IIS preflight without writing a
remote installer or package.
#>

[CmdletBinding()]
param(
[ValidatePattern('^[A-Za-z0-9_. -]+$')]
[string]$SiteName = 'AspClassicUnifiedFramework',
[ValidatePattern('^[A-Za-z0-9_. -]+$')]
[string]$AppPoolName = 'AspClassicUnifiedFramework',
[string]$DeployRoot = 'D:\Deployments\AspClassicUnifiedFramework',
[string]$BindingIpAddress = '100.97.39.23',
[ValidateRange(1, 65535)]
[int]$BindingPort = 8085,
[AllowEmptyString()]
[string]$HostHeader = '',
[string]$InitialWebConfigPath = '',
[string]$RemoteTarget = 'webserver-1',
[ValidateRange(1, 65535)]
[int]$RemotePort = 22,
[string]$SourcePath = (Split-Path $PSScriptRoot -Parent),
[string]$BaseUrl = '',
[string]$ReleaseId = '',
[string]$ExpectedBranch = 'master',
[ValidateRange(2, 100)]
[int]$KeepReleases = 5,
[string]$SshExe = 'ssh',
[string]$ScpExe = 'scp',
[switch]$AllowAnyBranch,
[switch]$AllowDirty,
[switch]$RunMigrations,
[switch]$SkipSmokeTest,
[Alias('HostPreflightOnly', 'RemotePreflightOnly')]
[switch]$PreflightOnly,
[switch]$LocalPreflightOnly,
[switch]$Rollback,
[string]$RollbackTo = '',
[switch]$DryRun,
[switch]$KeepPackage
)

Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'

function Write-Step { param([string]$Message) Write-Host ('==> ' + $Message) }

function Assert-Command {
param([string]$Name)
if (-not (Get-Command $Name -ErrorAction SilentlyContinue)) {
throw "$Name was not found on PATH."
}
}

function ConvertTo-SingleQuotedPowerShell {
param([string]$Value)
return "'" + $Value.Replace("'", "''") + "'"
}

function Add-RemoteArgument {
param(
[System.Collections.Generic.List[string]]$Arguments,
[string]$Name,
[string]$Value
)
$Arguments.Add($Name)
$Arguments.Add((ConvertTo-SingleQuotedPowerShell $Value))
}

function Assert-SafeNameValue {
param([string]$Name, [string]$Value)
if ([string]::IsNullOrWhiteSpace($Value) -or $Value -notmatch '^[A-Za-z0-9_. -]+$') {
throw "$Name contains unsupported characters."
}
if ($Value -match '(?i)schedulicious') {
throw "$Name must not identify a Schedulicious resource."
}
}

function Assert-SafeDeploymentValues {
Assert-SafeNameValue -Name 'SiteName' -Value $SiteName
Assert-SafeNameValue -Name 'AppPoolName' -Value $AppPoolName
if ($DeployRoot -match '(?i)schedulicious') {
throw 'DeployRoot must not reference Schedulicious.'
}
if ([string]::IsNullOrWhiteSpace($BindingIpAddress)) {
throw 'BindingIpAddress must not be empty.'
}
$parsedAddress = $null
if (-not [System.Net.IPAddress]::TryParse($BindingIpAddress, [ref]$parsedAddress)) {
throw "BindingIpAddress is not a valid IP address: $BindingIpAddress"
}
if ($HostHeader -match '[:/\\]') {
throw 'HostHeader must be empty or a DNS host name without a scheme, port, slash, or backslash.'
}
if ($HostHeader -match '(?i)schedulicious') {
throw 'HostHeader must not reference Schedulicious.'
}
}

function Copy-ReleaseSource {
param([string]$From, [string]$To)

$excludedNames = @('.git', '.deployment', 'releases')
$packageRoots = @(Get-ChildItem -LiteralPath $From -Force | Where-Object { $excludedNames -notcontains $_.Name })
$unsafeSourceItem = $packageRoots |
ForEach-Object {
if (($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { $_ }
elseif ($_.PSIsContainer) { Get-ChildItem -LiteralPath $_.FullName -Recurse -Force }
} |
Where-Object { ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 } |
Select-Object -First 1
if ($null -ne $unsafeSourceItem) {
throw "Source contains a reparse point/symbolic link, which is not package-safe: $($unsafeSourceItem.FullName)"
}

New-Item -ItemType Directory -Force -Path $To | Out-Null
$packageRoots | ForEach-Object {
if ($excludedNames -contains $_.Name) { return }
if (($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {
throw "Source contains a reparse point/symbolic link, which is not package-safe: $($_.FullName)"
}
Copy-Item -LiteralPath $_.FullName -Destination $To -Recurse -Force
}

$unsafeEntry = Get-ChildItem -LiteralPath $To -Recurse -Force |
Where-Object { ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 } |
Select-Object -First 1
if ($null -ne $unsafeEntry) {
throw "Package staging contains a reparse point/symbolic link: $($unsafeEntry.FullName)"
}
}

function Assert-ReleaseLayout {
param([string]$Root)
$required = @(
'public\Default.asp',
'public\web.config',
'core\autoload_core.asp',
'app\controllers\autoload_controllers.asp',
'scripts\install-iis-release.ps1'
)
foreach ($relativePath in $required) {
if (-not (Test-Path -LiteralPath (Join-Path $Root $relativePath) -PathType Leaf)) {
throw "Package/source tree is incomplete; missing $relativePath"
}
}
foreach ($xmlFile in Get-ChildItem -LiteralPath $Root -Recurse -Force -Filter 'web.config') {
try {
[xml](Get-Content -LiteralPath $xmlFile.FullName -Raw) | Out-Null
} catch {
throw "$($xmlFile.FullName) is not valid XML: $($_.Exception.Message)"
}
}
}

Assert-SafeDeploymentValues
$SourcePath = [System.IO.Path]::GetFullPath($SourcePath)
$installerPath = Join-Path $PSScriptRoot 'install-iis-release.ps1'
Assert-ReleaseLayout -Root $SourcePath

$directGitRoot = Test-Path -LiteralPath (Join-Path $SourcePath '.git')
$commit = 'nogit'
if ($directGitRoot) {
Assert-Command 'git'
$branch = (& git -C $SourcePath branch --show-current).Trim()
if ($LASTEXITCODE -ne 0) { throw 'Could not determine the Git branch.' }
if ((-not $AllowAnyBranch) -and $branch -ne $ExpectedBranch) {
throw "Refusing to deploy branch '$branch'; expected '$ExpectedBranch'."
}
$dirty = & git -C $SourcePath status --porcelain
if ($LASTEXITCODE -ne 0) { throw 'Could not inspect the Git worktree.' }
if ((-not $AllowDirty) -and $null -ne $dirty -and @($dirty).Count -gt 0) {
throw 'Refusing to deploy a dirty worktree. Use -AllowDirty only for a reviewed exception.'
}
$commit = (& git -C $SourcePath rev-parse --short=12 HEAD).Trim()
if ($LASTEXITCODE -ne 0) { throw 'Could not determine the Git commit.' }
Write-Host "Source branch: $branch"
Write-Host "Source commit: $commit"
} else {
Write-Warning 'SourcePath is not a standalone Git checkout; branch and dirty-worktree checks cannot be enforced.'
if (-not $AllowAnyBranch) {
throw 'Use a standalone checkout, or pass -AllowAnyBranch for a reviewed non-Git source tree.'
}
}

if ([string]::IsNullOrWhiteSpace($ReleaseId)) {
$ReleaseId = (Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + $commit
}
if ($ReleaseId -notmatch '^[A-Za-z0-9._-]+$') { throw 'ReleaseId contains unsupported characters.' }
if ($Rollback -and [string]::IsNullOrWhiteSpace($RollbackTo)) { throw '-Rollback requires -RollbackTo.' }
if ((-not $Rollback) -and -not [string]::IsNullOrWhiteSpace($RollbackTo)) { throw '-RollbackTo requires -Rollback.' }
if ($RunMigrations -and $Rollback) { throw '-RunMigrations is not valid during rollback.' }
if (($PreflightOnly -or $LocalPreflightOnly) -and $Rollback) {
throw 'Preflight modes cannot be combined with -Rollback.'
}
if ($PreflightOnly -and $LocalPreflightOnly) {
throw '-PreflightOnly and -LocalPreflightOnly are mutually exclusive.'
}

$workRoot = Join-Path ([System.IO.Path]::GetTempPath()) ('asp-iis-deploy-' + [Guid]::NewGuid().ToString('N'))
$packageStage = Join-Path $workRoot 'package'
$packageExtract = Join-Path $workRoot 'verify'
$packagePath = Join-Path $workRoot ($ReleaseId + '.zip')
$remoteDirectory = 'C:\Windows\Temp\asp-iis-deploy-' + $ReleaseId
$remotePackage = $remoteDirectory + '\' + $ReleaseId + '.zip'
$remoteInstaller = $remoteDirectory + '\install-iis-release.ps1'

try {
$sha256 = ''
if (-not $Rollback) {
Write-Step 'Staging the complete repository for packaging'
Copy-ReleaseSource -From $SourcePath -To $packageStage
Assert-ReleaseLayout -Root $packageStage
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::CreateFromDirectory($packageStage, $packagePath, [System.IO.Compression.CompressionLevel]::Optimal, $false)
[System.IO.Compression.ZipFile]::ExtractToDirectory($packagePath, $packageExtract)
Assert-ReleaseLayout -Root $packageExtract
$sha256 = (Get-FileHash -LiteralPath $packagePath -Algorithm SHA256).Hash
Write-Host "Package: $packagePath"
Write-Host "SHA-256: $sha256"
}

if ($LocalPreflightOnly) {
Write-Step 'Local/controller preflight passed; no network connection or host change was made'
exit 0
}

$remoteArguments = New-Object 'System.Collections.Generic.List[string]'
$remoteArguments.Add('&')
$remoteArguments.Add((ConvertTo-SingleQuotedPowerShell $remoteInstaller))
Add-RemoteArgument $remoteArguments '-SiteName' $SiteName
Add-RemoteArgument $remoteArguments '-AppPoolName' $AppPoolName
Add-RemoteArgument $remoteArguments '-DeployRoot' $DeployRoot
Add-RemoteArgument $remoteArguments '-BindingIpAddress' $BindingIpAddress
Add-RemoteArgument $remoteArguments '-BindingPort' $BindingPort.ToString()
Add-RemoteArgument $remoteArguments '-HostHeader' $HostHeader
Add-RemoteArgument $remoteArguments '-KeepReleases' $KeepReleases.ToString()
if (-not [string]::IsNullOrWhiteSpace($InitialWebConfigPath)) { Add-RemoteArgument $remoteArguments '-InitialWebConfigPath' $InitialWebConfigPath }
if (-not [string]::IsNullOrWhiteSpace($BaseUrl)) { Add-RemoteArgument $remoteArguments '-BaseUrl' $BaseUrl }

if ($Rollback) {
Add-RemoteArgument $remoteArguments '-RollbackTo' $RollbackTo
} elseif ($PreflightOnly) {
$remoteArguments.Add('-PreflightOnly')
} else {
Add-RemoteArgument $remoteArguments '-PackagePath' $remotePackage
Add-RemoteArgument $remoteArguments '-ReleaseId' $ReleaseId
Add-RemoteArgument $remoteArguments '-ExpectedSha256' $sha256
}
if ($RunMigrations) { $remoteArguments.Add('-RunMigrations') }
if ($SkipSmokeTest) { $remoteArguments.Add('-SkipSmokeTest') }

$remoteScript = $remoteArguments -join ' '
$remoteEncodedCommand = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($remoteScript))
$remoteCommand = 'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -EncodedCommand ' + $remoteEncodedCommand

if ($DryRun) {
Write-Step 'Dry-run complete; no network connection was made'
Write-Host "Would use dedicated site '$SiteName' and app pool '$AppPoolName'."
Write-Host "Would use binding ${BindingIpAddress}:$BindingPort with host header '$HostHeader'."
if ($PreflightOnly) {
Write-Host 'Would stream the installer over SSH for a read-only host preflight; no remote file would be written.'
} else {
Write-Host "Would create remote directory: $remoteDirectory"
Write-Host "Would copy installer: $installerPath"
if (-not $Rollback) { Write-Host "Would copy package: $packagePath" }
Write-Host ('Would execute host script: ' + $remoteScript)
}
exit 0
}

Assert-Command $SshExe
if ($PreflightOnly) {
Write-Step 'Streaming the installer for read-only host preflight'
$installerSource = Get-Content -LiteralPath $installerPath -Raw
$argumentTail = @($remoteArguments | Select-Object -Skip 2) -join ' '
$stdinScript = "& {`r`n" + $installerSource + "`r`n} " + $argumentTail
$stdinScript | & $SshExe -p $RemotePort $RemoteTarget 'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -Command -'
if ($LASTEXITCODE -ne 0) { throw "Remote preflight failed with exit code $LASTEXITCODE." }
Write-Step 'Remote host preflight completed successfully without persistent host changes'
exit 0
}

Assert-Command $ScpExe
Write-Step 'Creating remote temporary directory'
$mkdirScript = "New-Item -ItemType Directory -Force -Path $(ConvertTo-SingleQuotedPowerShell $remoteDirectory) | Out-Null"
$mkdirEncoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($mkdirScript))
& $SshExe -p $RemotePort $RemoteTarget ('powershell.exe -NoProfile -NonInteractive -EncodedCommand ' + $mkdirEncoded)
if ($LASTEXITCODE -ne 0) { throw 'Remote directory creation failed.' }

Write-Step 'Copying the host installer'
& $ScpExe -P $RemotePort $installerPath ($RemoteTarget + ':' + $remoteDirectory.Replace('\', '/') + '/install-iis-release.ps1')
if ($LASTEXITCODE -ne 0) { throw 'Installer copy failed.' }
if (-not $Rollback) {
Write-Step 'Copying the release package'
& $ScpExe -P $RemotePort $packagePath ($RemoteTarget + ':' + $remoteDirectory.Replace('\', '/') + '/' + $ReleaseId + '.zip')
if ($LASTEXITCODE -ne 0) { throw 'Package copy failed.' }
}

Write-Step 'Invoking the host-side installer'
& $SshExe -p $RemotePort $RemoteTarget $remoteCommand
if ($LASTEXITCODE -ne 0) { throw "Remote installer failed with exit code $LASTEXITCODE." }
Write-Step 'Remote operation completed successfully'
} finally {
if ($KeepPackage -and (Test-Path -LiteralPath $packagePath)) {
$keptPath = Join-Path (Get-Location) ([System.IO.Path]::GetFileName($packagePath))
Copy-Item -LiteralPath $packagePath -Destination $keptPath -Force
Write-Host "Package retained at $keptPath"
}
if (Test-Path -LiteralPath $workRoot) { Remove-Item -LiteralPath $workRoot -Recurse -Force }
}

+ 43
- 0
scripts/gen.cmd View File

@@ -0,0 +1,43 @@
@echo off
rem Runs a code generator inside the running "axonasp" container with the AxonASP CLI.
rem
rem scripts\gen.cmd migration <migration_name>
rem scripts\gen.cmd controller <Name> Index "Show(id)" NewForm Create "Edit(id)" "Update(id)" "Delete(id)"
rem scripts\gen.cmd repo /table:<Table> /pk:<PrimaryKey>
rem scripts\gen.cmd api /table:<Table> /pk:<PrimaryKey> (repo + JSON API controller, routes, OpenAPI spec)
rem
rem Controller actions are separate arguments (quote the ones with parentheses).
setlocal
set "GEN=%~1"
set "SCRIPT="
if "%GEN%"=="migration" set "SCRIPT=generateMigration.vbs"
if "%GEN%"=="controller" set "SCRIPT=generateController.vbs"
if "%GEN%"=="repo" set "SCRIPT=GenerateRepo.vbs"
if "%GEN%"=="api" set "SCRIPT=GenerateRepo.vbs"
if not defined SCRIPT goto usage
set "A1=%~2"
set "A2=%~3"
if not "%GEN%"=="controller" goto run
set "A2="
shift
shift
:collect
set "CUR=%~1"
if not defined CUR goto run
if defined A2 goto join
set "A2=%CUR%"
goto next
:join
set "A2=%A2%;%CUR%"
:next
shift
goto collect
:run
docker exec -e SERVER_WEB_ROOT=/opt/axonasp/site -e "ARG1=%A1%" -e "ARG2=%A2%" axonasp ./axonasp-cli -m vbscript -r /opt/axonasp/site/scripts/%SCRIPT%
if not "%GEN%"=="api" exit /b %errorlevel%
rem api: the repo/POBO were generated above, now the controller, routes and spec
docker exec -e SERVER_WEB_ROOT=/opt/axonasp/site -e "ARG1=%A1%" -e "ARG2=%A2%" axonasp ./axonasp-cli -m vbscript -r /opt/axonasp/site/scripts/GenerateApi.vbs
exit /b %errorlevel%
:usage
echo Usage: scripts\gen.cmd (migration^|controller^|repo^|api) args...
exit /b 1

BIN
scripts/generateController.vbs View File


+ 13
- 9
scripts/generateMigration.vbs View File

@@ -4,25 +4,30 @@
' Generates a new migration file with timestamp-based versioning.
'
' Usage:
' cscript //nologo scripts\generateMigration.vbs migration_name
' scripts\gen.cmd migration migration_name (runs under the AxonASP CLI in the container)
'
' Example:
' cscript //nologo scripts\generateMigration.vbs create_users_table
' scripts\gen.cmd migration create_users_table
' Creates: db/migrations/20260109153045_create_users_table.asp
'

Option Explicit

' AxonASP CLI: provide the WScript object (see _cli.vbs)
Dim shimFso
Set shimFso = CreateObject("Scripting.FileSystemObject")
ExecuteGlobal shimFso.OpenTextFile(Server.MapPath("/scripts/_cli.vbs"), 1).ReadAll

Dim fso, migrationName, timestamp, filename, filepath, content

Set fso = CreateObject("Scripting.FileSystemObject")

' Check arguments
If WScript.Arguments.Count < 1 Then
WScript.Echo "Usage: cscript //nologo scripts\generateMigration.vbs migration_name"
WScript.Echo "Usage: scripts\gen.cmd migration migration_name"
WScript.Echo ""
WScript.Echo "Example:"
WScript.Echo " cscript //nologo scripts\generateMigration.vbs create_users_table"
WScript.Echo " scripts\gen.cmd migration create_users_table"
WScript.Quit 1
End If

@@ -42,14 +47,13 @@ filename = timestamp & "_" & migrationName & ".asp"

' Ensure migrations directory exists
Dim migrationsDir
migrationsDir = fso.GetParentFolderName(WScript.ScriptFullName) & "\..\db\migrations"
migrationsDir = fso.GetAbsolutePathName(migrationsDir)
migrationsDir = Server.MapPath("/db/migrations")

If Not fso.FolderExists(migrationsDir) Then
CreateDirectoryPath migrationsDir
End If

filepath = migrationsDir & "\" & filename
filepath = migrationsDir & "/" & filename

' Check if file already exists
If fso.FileExists(filepath) Then
@@ -70,7 +74,7 @@ WScript.Echo "Migration created: " & filename
WScript.Echo "Path: " & filepath
WScript.Echo ""
WScript.Echo "Edit the file to add your migration logic, then run:"
WScript.Echo " cscript //nologo scripts\runMigrations.vbs"
WScript.Echo " scripts\migrate.cmd up"

WScript.Quit 0

@@ -126,7 +130,7 @@ Function GenerateMigrationContent(name)
template = template & "'-----------------------------------------------------------------------------------------------------------------------"& vbCrLf
template = template & "Sub Migration_Up(migration)"& vbCrLf
template = template & " ' Example: Create a table"& vbCrLf
template = template & " ' migration.CreateTable ""users"", ""id AUTOINCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255), created_at DATETIME"""& vbCrLf
template = template & " ' migration.CreateTable ""users"", ""id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT"""& vbCrLf
template = template & " "& vbCrLf
template = template & " ' Example: Add an index"& vbCrLf
template = template & " ' migration.CreateIndex ""idx_users_email"", ""users"", ""email"""& vbCrLf


+ 0
- 476
scripts/install-iis-release.ps1 View File

@@ -1,476 +0,0 @@
<#
.SYNOPSIS
Installs or rolls back an immutable release in a dedicated IIS site/app pool.

.DESCRIPTION
The complete repository is retained in each immutable release and IIS serves
only <release>\public. The script never discovers or adopts another site.
A missing dedicated target is created only after package extraction, layout,
and XML validation succeed. Host preflight is read-only and does not require
the dedicated target to exist.
#>

[CmdletBinding(DefaultParameterSetName = 'Deploy')]
param(
[ValidatePattern('^[A-Za-z0-9_. -]+$')]
[string]$SiteName = 'AspClassicUnifiedFramework',
[ValidatePattern('^[A-Za-z0-9_. -]+$')]
[string]$AppPoolName = 'AspClassicUnifiedFramework',
[string]$DeployRoot = 'D:\Deployments\AspClassicUnifiedFramework',
[string]$BindingIpAddress = '100.97.39.23',
[ValidateRange(1, 65535)]
[int]$BindingPort = 8085,
[AllowEmptyString()]
[string]$HostHeader = '',
[string]$InitialWebConfigPath = '',

[Parameter(ParameterSetName = 'Deploy')]
[string]$PackagePath = '',
[Parameter(ParameterSetName = 'Deploy')]
[ValidatePattern('^[A-Za-z0-9._-]+$')]
[string]$ReleaseId = (Get-Date -Format 'yyyyMMdd-HHmmss'),
[Parameter(Mandatory = $true, ParameterSetName = 'Rollback')]
[ValidatePattern('^[A-Za-z0-9._-]+$')]
[string]$RollbackTo,

[string]$BaseUrl = '',
[ValidateRange(2, 100)]
[int]$KeepReleases = 5,
[string]$ExpectedSha256 = '',
[switch]$RunMigrations,
[switch]$SkipSmokeTest,
[switch]$PreflightOnly,
[switch]$DryRun
)

Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'

function Write-Step { param([string]$Message) Write-Host ('==> ' + $Message) }

function Get-NormalizedPath {
param([string]$Path)
return [System.IO.Path]::GetFullPath([Environment]::ExpandEnvironmentVariables($Path)).TrimEnd('\')
}

function Assert-Administrator {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw 'An elevated Administrator PowerShell session is required.'
}
}

function Assert-SafeNameValue {
param([string]$Name, [string]$Value)
if ([string]::IsNullOrWhiteSpace($Value) -or $Value -notmatch '^[A-Za-z0-9_. -]+$') {
throw "$Name contains unsupported characters."
}
if ($Value -match '(?i)schedulicious') {
throw "$Name must not identify a Schedulicious resource."
}
}

function Assert-DeploymentInputs {
Assert-SafeNameValue -Name 'SiteName' -Value $SiteName
Assert-SafeNameValue -Name 'AppPoolName' -Value $AppPoolName
if ($DeployRoot -match '(?i)schedulicious') { throw 'DeployRoot must not reference Schedulicious.' }
if ($HostHeader -match '(?i)schedulicious') { throw 'HostHeader must not reference Schedulicious.' }
if ($HostHeader -match '[:/\\]') {
throw 'HostHeader must be empty or a DNS host name without a scheme, port, slash, or backslash.'
}
$parsedAddress = $null
if (-not [System.Net.IPAddress]::TryParse($BindingIpAddress, [ref]$parsedAddress)) {
throw "BindingIpAddress is not a valid IP address: $BindingIpAddress"
}
}

function Assert-ReleaseLayout {
param([string]$ReleasePath)
$required = @(
'public\Default.asp',
'public\web.config',
'core\autoload_core.asp',
'app\controllers\autoload_controllers.asp',
'scripts\install-iis-release.ps1'
)
foreach ($relativePath in $required) {
if (-not (Test-Path -LiteralPath (Join-Path $ReleasePath $relativePath) -PathType Leaf)) {
throw "Release is incomplete; missing $relativePath"
}
}
foreach ($xmlFile in Get-ChildItem -LiteralPath $ReleasePath -Recurse -Force -Filter 'web.config') {
try {
[xml](Get-Content -LiteralPath $xmlFile.FullName -Raw) | Out-Null
} catch {
throw "$($xmlFile.FullName) is not valid XML: $($_.Exception.Message)"
}
}
}

function Assert-ArchiveEntries {
param([string]$ZipPath)
Add-Type -AssemblyName System.IO.Compression.FileSystem
$archive = [System.IO.Compression.ZipFile]::OpenRead($ZipPath)
try {
foreach ($entry in $archive.Entries) {
$name = $entry.FullName.Replace('/', '\')
if ([System.IO.Path]::IsPathRooted($name) -or $name -match '(^|\\)\.\.(\\|$)') {
throw "Package contains an unsafe path: $($entry.FullName)"
}
}
} finally {
$archive.Dispose()
}
}

function Get-BindingInformation {
return $BindingIpAddress + ':' + $BindingPort + ':' + $HostHeader
}

function Assert-HostCapabilities {
# Query IIS directly instead of Get-WindowsFeature/Get-WindowsOptionalFeature:
# those feature cmdlets can stall while collecting server-manager state.
$aspHandler = (Get-WebConfiguration -PSPath 'MACHINE/WEBROOT/APPHOST' -Filter 'system.webServer/handlers').Collection |
Where-Object { $_.path -eq '*.asp' -and $_.modules -match '(^|,)IsapiModule(,|$)' -and $_.scriptProcessor -match '(?i)asp\.dll$' } |
Select-Object -First 1
if ($null -eq $aspHandler) {
throw 'The IIS Classic ASP handler (*.asp through asp.dll) was not found.'
}
try {
Get-WebConfigurationProperty -PSPath 'MACHINE/WEBROOT/APPHOST' -Filter 'system.webServer/asp' -Name 'enableParentPaths' -ErrorAction Stop | Out-Null
} catch {
throw "The IIS Classic ASP configuration section is unavailable: $($_.Exception.Message)"
}
if ($null -eq (Get-WebGlobalModule -Name RewriteModule -ErrorAction SilentlyContinue)) {
throw 'IIS URL Rewrite is not installed (RewriteModule was not found).'
}
}

function Assert-DeployRoot {
param([string]$Path)
$root = [System.IO.Path]::GetPathRoot($Path)
if ([string]::IsNullOrWhiteSpace($root) -or -not (Test-Path -LiteralPath $root -PathType Container)) {
throw "The deployment drive/root is unavailable: $root"
}
if ($Path.TrimEnd('\') -eq $root.TrimEnd('\')) { throw 'DeployRoot must not be a drive root.' }
if ((Test-Path -LiteralPath $Path) -and -not (Test-Path -LiteralPath $Path -PathType Container)) {
throw "DeployRoot exists but is not a directory: $Path"
}
$ancestor = $Path
while (-not (Test-Path -LiteralPath $ancestor -PathType Container)) {
$parent = Split-Path -Parent $ancestor
if ([string]::IsNullOrWhiteSpace($parent) -or $parent -eq $ancestor) { break }
$ancestor = $parent
}
if (-not (Test-Path -LiteralPath $ancestor -PathType Container)) {
throw "No accessible ancestor exists for DeployRoot: $Path"
}
Get-Item -LiteralPath $ancestor -ErrorAction Stop | Out-Null
}

function Test-PathUnderRoot {
param([string]$Path, [string]$Root)
$normalizedPath = Get-NormalizedPath $Path
$prefix = (Get-NormalizedPath $Root) + '\'
return $normalizedPath.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)
}

function Get-TargetState {
$site = Get-Website -Name $SiteName -ErrorAction SilentlyContinue
$poolExists = Test-Path -LiteralPath ('IIS:\AppPools\' + $AppPoolName)
if (($null -eq $site) -ne (-not $poolExists)) {
throw 'Dedicated target is partial: the site and app pool must either both exist or both be absent.'
}
if ($null -eq $site) {
return [pscustomobject]@{
Exists = $false; Site = $null; PhysicalPath = ''; ParentPaths = $null
SiteState = ''; PoolState = ''
}
}
if ($site.applicationPool -ne $AppPoolName) {
throw "Existing target site uses app pool '$($site.applicationPool)', expected '$AppPoolName'. Refusing adoption."
}
$otherPoolConsumer = Get-Website |
Where-Object { $_.Name -ne $SiteName -and $_.applicationPool -eq $AppPoolName } |
Select-Object -First 1
if ($null -ne $otherPoolConsumer) {
throw "App pool '$AppPoolName' is also used by site '$($otherPoolConsumer.Name)'. Refusing to alter a shared pool."
}
$bindings = @($site.Bindings.Collection)
$expectedBinding = Get-BindingInformation
if ($bindings.Count -ne 1 -or $bindings[0].protocol -ne 'http' -or $bindings[0].bindingInformation -ne $expectedBinding) {
throw "Existing target binding does not exactly match http/$expectedBinding. Refusing adoption or binding changes."
}
$physicalPath = Get-NormalizedPath $site.physicalPath
$releasesRoot = Join-Path $DeployRoot 'releases'
if (-not (Test-PathUnderRoot -Path $physicalPath -Root $releasesRoot) -or
-not $physicalPath.EndsWith('\public', [StringComparison]::OrdinalIgnoreCase)) {
throw "Existing target physicalPath is outside this pipeline's release public directories: $physicalPath"
}
if (-not (Test-Path -LiteralPath $physicalPath -PathType Container)) {
throw "Existing target physicalPath does not exist: $physicalPath"
}
Assert-ReleaseLayout -ReleasePath (Split-Path -Parent $physicalPath)
$parentPaths = (Get-WebConfigurationProperty -PSPath 'MACHINE/WEBROOT/APPHOST' -Location $SiteName -Filter 'system.webServer/asp' -Name 'enableParentPaths').Value
return [pscustomobject]@{
Exists = $true; Site = $site; PhysicalPath = $physicalPath; ParentPaths = [bool]$parentPaths
SiteState = (Get-WebsiteState -Name $SiteName).Value
PoolState = (Get-WebAppPoolState -Name $AppPoolName).Value
}
}

function Assert-NoBindingConflict {
param($TargetState)
$expectedBinding = Get-BindingInformation
foreach ($candidate in Get-Website) {
if ($TargetState.Exists -and $candidate.Name -eq $SiteName) { continue }
foreach ($binding in @($candidate.Bindings.Collection)) {
if ($binding.protocol -ne 'http') { continue }
if ($binding.bindingInformation -notmatch '^(.*):(\d+):(.*)$') { continue }
$candidateIp = $Matches[1]
$candidatePort = [int]$Matches[2]
$candidateHost = $Matches[3]
$ipOverlaps = ($candidateIp -eq '*' -or $candidateIp -eq '0.0.0.0' -or $candidateIp -eq $BindingIpAddress)
if ($candidatePort -eq $BindingPort -and $candidateHost -eq $HostHeader -and $ipOverlaps) {
throw "Requested binding http/$expectedBinding conflicts with existing site '$($candidate.Name)' binding '$($binding.bindingInformation)'."
}
}
}
}

function Get-SmokeUrl {
if (-not [string]::IsNullOrWhiteSpace($BaseUrl)) { return $BaseUrl }
$hostPart = $BindingIpAddress
if ($hostPart.Contains(':')) { $hostPart = '[' + $hostPart + ']' }
return 'http://' + $hostPart + ':' + $BindingPort
}

function Invoke-SmokeTest {
if ($SkipSmokeTest) {
Write-Step 'Smoke test skipped by explicit request'
return
}
$target = (Get-SmokeUrl).TrimEnd('/') + '/'
Write-Step ('Smoke testing ' + $target)
$headers = @{}
if (-not [string]::IsNullOrWhiteSpace($HostHeader)) { $headers['Host'] = $HostHeader }
$response = Invoke-WebRequest -UseBasicParsing -Uri $target -Headers $headers -TimeoutSec 30
if ($response.StatusCode -lt 200 -or $response.StatusCode -ge 400) {
throw "Smoke test returned HTTP $($response.StatusCode)"
}
Write-Host ('Smoke test returned HTTP ' + $response.StatusCode)
}

function Set-IisRelease {
param([string]$PhysicalPath)
Set-ItemProperty -Path ('IIS:\Sites\' + $SiteName) -Name physicalPath -Value $PhysicalPath
$poolState = (Get-WebAppPoolState -Name $AppPoolName).Value
if ($poolState -eq 'Started') { Restart-WebAppPool -Name $AppPoolName }
else { Start-WebAppPool -Name $AppPoolName }
}

function Restore-ExistingTarget {
param($TargetState)
if (-not $TargetState.Exists) { return }
Set-ItemProperty -Path ('IIS:\Sites\' + $SiteName) -Name physicalPath -Value $TargetState.PhysicalPath
Set-WebConfigurationProperty -PSPath 'MACHINE/WEBROOT/APPHOST' -Location $SiteName -Filter 'system.webServer/asp' -Name 'enableParentPaths' -Value $TargetState.ParentPaths
if ($TargetState.PoolState -eq 'Started') {
if ((Get-WebAppPoolState -Name $AppPoolName).Value -eq 'Started') { Restart-WebAppPool -Name $AppPoolName }
else { Start-WebAppPool -Name $AppPoolName }
} elseif ((Get-WebAppPoolState -Name $AppPoolName).Value -eq 'Started') {
Stop-WebAppPool -Name $AppPoolName
}
if ($TargetState.SiteState -eq 'Started') {
if ((Get-WebsiteState -Name $SiteName).Value -ne 'Started') { Start-Website -Name $SiteName }
} elseif ((Get-WebsiteState -Name $SiteName).Value -eq 'Started') {
Stop-Website -Name $SiteName
}
}

if ($env:OS -ne 'Windows_NT') { throw 'This script must run on Windows.' }
Assert-Administrator
Import-Module WebAdministration -ErrorAction Stop
Assert-DeploymentInputs
$DeployRoot = Get-NormalizedPath $DeployRoot
Assert-DeployRoot -Path $DeployRoot
if (-not [string]::IsNullOrWhiteSpace($InitialWebConfigPath)) {
$preflightInitialConfig = Get-NormalizedPath $InitialWebConfigPath
if (-not (Test-Path -LiteralPath $preflightInitialConfig -PathType Leaf)) {
throw "InitialWebConfigPath not found: $preflightInitialConfig"
}
try { [xml](Get-Content -LiteralPath $preflightInitialConfig -Raw) | Out-Null }
catch { throw "InitialWebConfigPath is not valid XML: $($_.Exception.Message)" }
}
Assert-HostCapabilities
$targetState = Get-TargetState
Assert-NoBindingConflict -TargetState $targetState

Write-Step "Dedicated site: $SiteName"
Write-Host "Dedicated app pool: $AppPoolName"
Write-Host "Binding: http/$(Get-BindingInformation)"
Write-Host "Deployment root: $DeployRoot"
if ($targetState.Exists) {
Write-Host 'Target state: existing and exactly matched'
} else {
Write-Host 'Target state: absent; eligible for isolated creation after release validation'
}

if ($PreflightOnly -or $DryRun) {
Write-Step 'Host preflight passed; no IIS or filesystem changes were made'
exit 0
}

$releasesRoot = Join-Path $DeployRoot 'releases'
$sharedRoot = Join-Path $DeployRoot 'shared'
$sharedConfig = Join-Path $sharedRoot 'public.web.config'
$statePath = Join-Path $DeployRoot 'deployment-state.json'

if ($PSCmdlet.ParameterSetName -eq 'Rollback') {
if (-not $targetState.Exists) { throw 'Rollback requires the dedicated target site and app pool to exist.' }
if (-not (Test-Path -LiteralPath $sharedConfig -PathType Leaf)) { throw "Shared configuration is missing: $sharedConfig" }
$rollbackRoot = Get-NormalizedPath (Join-Path $releasesRoot $RollbackTo)
if (-not (Test-PathUnderRoot -Path $rollbackRoot -Root $releasesRoot)) { throw 'Rollback target escaped the releases directory.' }
Assert-ReleaseLayout -ReleasePath $rollbackRoot
try { [xml](Get-Content -LiteralPath $sharedConfig -Raw) | Out-Null }
catch { throw "Shared configuration is not valid XML: $($_.Exception.Message)" }
try {
Set-WebConfigurationProperty -PSPath 'MACHINE/WEBROOT/APPHOST' -Location $SiteName -Filter 'system.webServer/asp' -Name 'enableParentPaths' -Value $true
Set-IisRelease -PhysicalPath (Join-Path $rollbackRoot 'public')
Invoke-SmokeTest
[ordered]@{
siteName = $SiteName; appPoolName = $AppPoolName; currentRelease = $RollbackTo
currentPhysicalPath = (Join-Path $rollbackRoot 'public'); previousPhysicalPath = $targetState.PhysicalPath
binding = (Get-BindingInformation); switchedAtUtc = (Get-Date).ToUniversalTime().ToString('o'); operation = 'rollback'
} | ConvertTo-Json | Set-Content -LiteralPath $statePath -Encoding UTF8
} catch {
Write-Warning 'Rollback failed; restoring the prior dedicated target path and parent-path setting.'
Restore-ExistingTarget -TargetState $targetState
throw
}
Write-Step "Rollback complete: $RollbackTo"
exit 0
}

if ([string]::IsNullOrWhiteSpace($PackagePath)) { throw '-PackagePath is required for deployment.' }
$PackagePath = Get-NormalizedPath $PackagePath
if (-not (Test-Path -LiteralPath $PackagePath -PathType Leaf)) { throw "Package not found: $PackagePath" }
if ([System.IO.Path]::GetExtension($PackagePath) -ne '.zip') { throw 'PackagePath must name a .zip package.' }
if (-not [string]::IsNullOrWhiteSpace($ExpectedSha256)) {
$actualHash = (Get-FileHash -LiteralPath $PackagePath -Algorithm SHA256).Hash
if ($actualHash -ne $ExpectedSha256) { throw "Package SHA-256 mismatch. Expected $ExpectedSha256; got $actualHash" }
Write-Host ('Package SHA-256 verified: ' + $actualHash)
}
Assert-ArchiveEntries -ZipPath $PackagePath

$releaseRoot = Join-Path $releasesRoot $ReleaseId
$stagingRoot = $releaseRoot + '.staging'
if ((Test-Path -LiteralPath $releaseRoot) -or (Test-Path -LiteralPath $stagingRoot)) { throw "Release already exists: $ReleaseId" }

$createdSite = $false
$createdPool = $false
$createdSharedConfig = $false
$iisMutationStarted = $false
try {
New-Item -ItemType Directory -Force -Path $releasesRoot, $sharedRoot | Out-Null
New-Item -ItemType Directory -Force -Path $stagingRoot | Out-Null
Expand-Archive -LiteralPath $PackagePath -DestinationPath $stagingRoot -Force
$unsafeExtractedItem = Get-ChildItem -LiteralPath $stagingRoot -Recurse -Force |
Where-Object { ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 } |
Select-Object -First 1
if ($null -ne $unsafeExtractedItem) {
throw "Extracted release contains a reparse point: $($unsafeExtractedItem.FullName)"
}
Assert-ReleaseLayout -ReleasePath $stagingRoot

if (-not (Test-Path -LiteralPath $sharedConfig -PathType Leaf)) {
$initialConfig = Join-Path $stagingRoot 'public\web.config'
if (-not [string]::IsNullOrWhiteSpace($InitialWebConfigPath)) {
$initialConfig = Get-NormalizedPath $InitialWebConfigPath
if (-not (Test-Path -LiteralPath $initialConfig -PathType Leaf)) { throw "InitialWebConfigPath not found: $initialConfig" }
}
try { [xml](Get-Content -LiteralPath $initialConfig -Raw) | Out-Null }
catch { throw "Initial web.config is not valid XML: $($_.Exception.Message)" }
Copy-Item -LiteralPath $initialConfig -Destination $sharedConfig -Force
$createdSharedConfig = $true
Write-Step "Initialized shared configuration from $initialConfig"
}
try { [xml](Get-Content -LiteralPath $sharedConfig -Raw) | Out-Null }
catch { throw "Shared configuration is not valid XML: $($_.Exception.Message)" }
Copy-Item -LiteralPath $sharedConfig -Destination (Join-Path $stagingRoot 'public\web.config') -Force
Assert-ReleaseLayout -ReleasePath $stagingRoot

if ($RunMigrations) {
$migrationScript = Join-Path $stagingRoot 'scripts\runMigrations.vbs'
if (-not (Test-Path -LiteralPath $migrationScript -PathType Leaf)) { throw "Migration script not found: $migrationScript" }
Write-Warning 'Running migrations by explicit request; IIS rollback cannot undo data changes.'
Push-Location $stagingRoot
try {
& cscript.exe //nologo $migrationScript up
if ($LASTEXITCODE -ne 0) { throw "Migration command exited with code $LASTEXITCODE" }
} finally { Pop-Location }
}

Move-Item -LiteralPath $stagingRoot -Destination $releaseRoot
$newPublic = Join-Path $releaseRoot 'public'

$iisMutationStarted = $true
if (-not $targetState.Exists) {
New-WebAppPool -Name $AppPoolName | Out-Null
$createdPool = $true
Set-ItemProperty -Path ('IIS:\AppPools\' + $AppPoolName) -Name managedRuntimeVersion -Value ''
New-Website -Name $SiteName -PhysicalPath $newPublic -ApplicationPool $AppPoolName -IPAddress $BindingIpAddress -Port $BindingPort -HostHeader $HostHeader | Out-Null
$createdSite = $true
} else {
Set-IisRelease -PhysicalPath $newPublic
}

Set-WebConfigurationProperty -PSPath 'MACHINE/WEBROOT/APPHOST' -Location $SiteName -Filter 'system.webServer/asp' -Name 'enableParentPaths' -Value $true
if (-not $targetState.Exists) {
$poolState = (Get-WebAppPoolState -Name $AppPoolName).Value
if ($poolState -ne 'Started') { Start-WebAppPool -Name $AppPoolName }
$siteState = (Get-WebsiteState -Name $SiteName).Value
if ($siteState -ne 'Started') { Start-Website -Name $SiteName }
}
Invoke-SmokeTest

[ordered]@{
siteName = $SiteName; appPoolName = $AppPoolName; currentRelease = $ReleaseId
currentPhysicalPath = $newPublic; previousPhysicalPath = $targetState.PhysicalPath
binding = (Get-BindingInformation); packageSha256 = (Get-FileHash -LiteralPath $PackagePath -Algorithm SHA256).Hash
switchedAtUtc = (Get-Date).ToUniversalTime().ToString('o'); migrationsRun = [bool]$RunMigrations; operation = 'deploy'
} | ConvertTo-Json | Set-Content -LiteralPath $statePath -Encoding UTF8

$protectedPaths = @($newPublic, $targetState.PhysicalPath)
$oldReleases = Get-ChildItem -LiteralPath $releasesRoot -Directory |
Where-Object { $_.Name -notlike '*.staging' } |
Sort-Object LastWriteTimeUtc -Descending |
Select-Object -Skip $KeepReleases
foreach ($oldRelease in $oldReleases) {
$oldPublic = Join-Path $oldRelease.FullName 'public'
if ($protectedPaths -notcontains $oldPublic) { Write-Step ('Retention candidate (not deleted): ' + $oldRelease.FullName) }
}
Write-Step "Deployment complete: $ReleaseId"
} catch {
$failure = $_
if ($iisMutationStarted) {
if ($createdSite -and (Get-Website -Name $SiteName -ErrorAction SilentlyContinue)) {
Write-Warning "Removing site created by this invocation: $SiteName"
Remove-Website -Name $SiteName
}
if ($createdPool -and (Test-Path -LiteralPath ('IIS:\AppPools\' + $AppPoolName))) {
Write-Warning "Removing app pool created by this invocation: $AppPoolName"
Remove-WebAppPool -Name $AppPoolName
}
if ($targetState.Exists) {
Write-Warning 'Restoring the prior dedicated target state.'
Restore-ExistingTarget -TargetState $targetState
}
}
if ($createdSharedConfig -and (Test-Path -LiteralPath $sharedConfig -PathType Leaf)) {
Write-Warning 'Removing shared configuration initialized by this failed invocation.'
Remove-Item -LiteralPath $sharedConfig -Force
}
if (Test-Path -LiteralPath $stagingRoot) { Write-Warning "Incomplete staging retained for inspection: $stagingRoot" }
throw $failure
}

+ 27
- 0
scripts/migrate.asp View File

@@ -0,0 +1,27 @@
<%
' Migration runner for AxonASP CLI (the WSH runMigrations.vbs cannot run on Linux/AxonASP).
'
' docker exec -e SERVER_WEB_ROOT=/opt/axonasp/site -e MIGRATE=status axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/migrate.asp
' MIGRATE = up (default) | down | status
'
Dim cmd : cmd = LCase(CreateObject("WScript.Shell").ExpandEnvironmentStrings("%MIGRATE%"))
If cmd = "%migrate%" Or cmd = "" Then cmd = "up"
%>
<!--#include file="../core/autoload_core.asp" -->
<%
Dim m : Set m = Migrator()
m.MigrationsPath = Server.MapPath("/db/migrations") ' requires SERVER_WEB_ROOT=<framework folder>
m.EnsureSchemaMigrationsTable
Select Case cmd
Case "up" : m.ApplyAllPending
Case "down" : m.RollbackLast
Case "status"
Dim k
Response.Write "Applied:" & vbCrLf
For Each k In m.GetAppliedMigrations().Keys : Response.Write " " & k & vbCrLf : Next
Response.Write "Pending:" & vbCrLf
For Each k In m.GetPendingMigrations().Keys : Response.Write " " & k & vbCrLf : Next
Case Else
Response.Write "Unknown command: " & cmd & " (use up, down, status)" & vbCrLf
End Select
%>

+ 6
- 0
scripts/migrate.cmd View File

@@ -0,0 +1,6 @@
@echo off
rem Usage: scripts\migrate.cmd [up|down|status] (default: up)
rem Runs the migrator inside the running "axonasp" container.
set CMD=%1
if "%CMD%"=="" set CMD=up
docker exec -e SERVER_WEB_ROOT=/opt/axonasp/site -e MIGRATE=%CMD% axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/migrate.asp

+ 0
- 90
scripts/migrate_isbusiness_to_households.vbs View File

@@ -1,90 +0,0 @@
' migrate_isbusiness_to_households.vbs
' Moves IsBusiness from HouseholderNames to Households.
'
' Usage:
' cscript //nologo scripts\migrate_isbusiness_to_households.vbs "C:\path\to\myAccessFile.accdb"
'
' What it does:
' 1) Adds Households.IsBusiness (SMALLINT) if missing
' 2) Copies data: sets Households.IsBusiness=1 if any related HouseholderNames.IsBusiness<>0
' 3) Sets NULLs to 0
' 4) Drops HouseholderNames.IsBusiness if present
'
Option Explicit

Dim dbPath
If WScript.Arguments.Count < 1 Then
WScript.Echo "ERROR: missing db path."
WScript.Echo "Usage: cscript //nologo scripts\migrate_isbusiness_to_households.vbs ""C:\path\to\db.accdb"""
WScript.Quit 1
End If

dbPath = WScript.Arguments(0)

Dim conn
Set conn = CreateObject("ADODB.Connection")
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath & ";Persist Security Info=False;"

On Error Resume Next

If Not ColumnExists(conn, "Households", "IsBusiness") Then
Exec conn, "ALTER TABLE [Households] ADD COLUMN [IsBusiness] SMALLINT"
If Err.Number <> 0 Then
WScript.Echo "ERROR adding Households.IsBusiness: " & Err.Description
WScript.Quit 1
End If
WScript.Echo "Added Households.IsBusiness"
Else
WScript.Echo "Households.IsBusiness already exists"
End If

' Copy data (only if the old column exists)
If ColumnExists(conn, "HouseholderNames", "IsBusiness") Then
' Normalize all existing households first so the column is never left NULL.
Exec conn, "UPDATE [Households] SET [IsBusiness]=0"
If Err.Number <> 0 Then
WScript.Echo "ERROR initializing Households.IsBusiness: " & Err.Description
WScript.Quit 1
End If

' Promote households to business when any related name was previously marked as a business.
Exec conn, "UPDATE [Households] SET [IsBusiness]=1 WHERE [Id] IN (SELECT [HouseholdId] FROM [HouseholderNames] WHERE [IsBusiness]<>0)"
If Err.Number <> 0 Then
WScript.Echo "ERROR copying IsBusiness to Households: " & Err.Description
WScript.Quit 1
End If
WScript.Echo "Copied IsBusiness values to Households"

Exec conn, "ALTER TABLE [HouseholderNames] DROP COLUMN [IsBusiness]"
If Err.Number <> 0 Then
WScript.Echo "ERROR dropping HouseholderNames.IsBusiness: " & Err.Description
WScript.Quit 1
End If
WScript.Echo "Dropped HouseholderNames.IsBusiness"
Else
WScript.Echo "HouseholderNames.IsBusiness does not exist; nothing to drop"
End If

conn.Close
Set conn = Nothing
WScript.Echo "Done."

' --- helpers ---
Sub Exec(c, sql)
Err.Clear
c.Execute sql
End Sub

Function ColumnExists(c, tableName, colName)
Dim rs
ColumnExists = False
Err.Clear
Set rs = c.OpenSchema(4, Array(Empty, Empty, tableName, colName)) ' adSchemaColumns=4
If Err.Number <> 0 Then
Err.Clear
Exit Function
End If
If Not rs.EOF Then ColumnExists = True
rs.Close
Set rs = Nothing
End Function

+ 0
- 614
scripts/runMigrations.vbs View File

@@ -1,614 +0,0 @@
'=======================================================================================================================
' MIGRATION RUNNER (Standalone VBScript)
'=======================================================================================================================
' Runs database migrations directly via VBScript without requiring IIS/ASP.
'
' Usage:
' cscript //nologo scripts\runMigrations.vbs [command]
'
' Commands:
' up - Apply all pending migrations (default)
' down - Rollback the last migration
' status - Show migration status
' apply <file> - Apply a specific migration file
' rollback <file> - Rollback a specific migration file
'
' Examples:
' cscript //nologo scripts\runMigrations.vbs
' cscript //nologo scripts\runMigrations.vbs up
' cscript //nologo scripts\runMigrations.vbs down
' cscript //nologo scripts\runMigrations.vbs status
'

Option Explicit

Dim fso, scriptDir, projectRoot, webConfigPath, migrationsPath
Dim connectionString, command, argument

Set fso = CreateObject("Scripting.FileSystemObject")

' Get paths
scriptDir = fso.GetParentFolderName(WScript.ScriptFullName)
projectRoot = fso.GetAbsolutePathName(scriptDir & "\..")
webConfigPath = projectRoot & "\public\web.config"
migrationsPath = projectRoot & "\db\migrations"

' Parse arguments
command = "up" ' default command
If WScript.Arguments.Count > 0 Then
command = LCase(WScript.Arguments(0))
End If

If WScript.Arguments.Count > 1 Then
argument = WScript.Arguments(1)
End If

' Validate command
Select Case command
Case "up", "down", "status", "apply", "rollback"
' Valid command
Case Else
ShowUsage
WScript.Quit 1
End Select

' Load connection string from web.config
connectionString = GetConnectionString(webConfigPath)
If connectionString = "" Then
WScript.Echo "Error: Could not read connection string from web.config"
WScript.Quit 1
End If

' Execute the command
On Error Resume Next
Select Case command
Case "up"
ApplyAllPending
Case "down"
RollbackLast
Case "status"
ShowStatus
Case "apply"
If argument = "" Then
WScript.Echo "Error: No migration file specified"
WScript.Echo "Usage: cscript //nologo scripts\runMigrations.vbs apply <filename>"
WScript.Quit 1
End If
ApplyMigration argument
Case "rollback"
If argument = "" Then
WScript.Echo "Error: No migration file specified"
WScript.Echo "Usage: cscript //nologo scripts\runMigrations.vbs rollback <filename>"
WScript.Quit 1
End If
RollbackMigration argument
End Select

If Err.Number <> 0 Then
WScript.Echo ""
WScript.Echo "ERROR: " & Err.Description
WScript.Echo "Number: " & Err.Number
WScript.Echo "Source: " & Err.Source
WScript.Quit 1
End If

WScript.Quit 0

'=======================================================================================================================
' MIGRATION FUNCTIONS
'=======================================================================================================================

Sub ApplyAllPending()
WScript.Echo "=============================================================="
WScript.Echo "APPLYING PENDING MIGRATIONS"
WScript.Echo "=============================================================="
WScript.Echo ""

EnsureSchemaMigrationsTable

Dim pending, version, versions(), i, j, temp
Set pending = GetPendingMigrations()

If pending.Count = 0 Then
WScript.Echo "No pending migrations."
WScript.Echo ""
WScript.Echo "=============================================================="
WScript.Echo "DONE"
WScript.Echo "=============================================================="
Exit Sub
End If

' Sort versions
ReDim versions(pending.Count - 1)
i = 0
For Each version In pending.Keys
versions(i) = version
i = i + 1
Next

' Simple bubble sort (string comparison works for YYYYMMDDHHMMSS format)
For i = 0 To UBound(versions) - 1
For j = i + 1 To UBound(versions)
If versions(i) > versions(j) Then
temp = versions(i)
versions(i) = versions(j)
versions(j) = temp
End If
Next
Next

' Apply in order
For i = 0 To UBound(versions)
ApplyMigration pending(versions(i))
Next

WScript.Echo ""
WScript.Echo "=============================================================="
WScript.Echo "DONE"
WScript.Echo "=============================================================="
End Sub

Sub RollbackLast()
WScript.Echo "=============================================================="
WScript.Echo "ROLLING BACK LAST MIGRATION"
WScript.Echo "=============================================================="
WScript.Echo ""

EnsureSchemaMigrationsTable

Dim applied, available, version, lastVersion, filename
Set applied = GetAppliedMigrations()

If applied.Count = 0 Then
WScript.Echo "No migrations to rollback."
WScript.Echo ""
WScript.Echo "=============================================================="
WScript.Echo "DONE"
WScript.Echo "=============================================================="
Exit Sub
End If

' Find the last version (string comparison works for YYYYMMDDHHMMSS format)
lastVersion = ""
For Each version In applied.Keys
If lastVersion = "" Or version > lastVersion Then
lastVersion = version
End If
Next

' Find the filename
Set available = GetAvailableMigrations()
If available.Exists(lastVersion) Then
filename = available(lastVersion)
RollbackMigration filename
Else
WScript.Echo "Error: Migration file not found for version: " & lastVersion
WScript.Quit 1
End If

WScript.Echo ""
WScript.Echo "=============================================================="
WScript.Echo "DONE"
WScript.Echo "=============================================================="
End Sub

Sub ShowStatus()
WScript.Echo "=============================================================="
WScript.Echo "MIGRATION STATUS"
WScript.Echo "=============================================================="
WScript.Echo ""

EnsureSchemaMigrationsTable

Dim applied, pending, available, version
Set applied = GetAppliedMigrations()
Set pending = GetPendingMigrations()
Set available = GetAvailableMigrations()

WScript.Echo "Applied migrations: " & applied.Count
If applied.Count > 0 Then
For Each version In applied.Keys
If available.Exists(version) Then
WScript.Echo " [X] " & available(version)
Else
WScript.Echo " [X] " & version & " (file not found)"
End If
Next
End If

WScript.Echo ""
WScript.Echo "Pending migrations: " & pending.Count
If pending.Count > 0 Then
For Each version In pending.Keys
WScript.Echo " [ ] " & pending(version)
Next
End If

WScript.Echo ""
WScript.Echo "=============================================================="
End Sub

Sub ApplyMigration(filename)
Dim version
version = GetVersionFromFilename(filename)

If version = "" Then
Err.Raise vbObjectError + 1, "Migrator", "Invalid migration filename format: " & filename
End If

' Check if already applied
Dim applied
Set applied = GetAppliedMigrations()
If applied.Exists(version) Then
WScript.Echo "Migration " & version & " already applied. Skipping."
Exit Sub
End If

WScript.Echo "Applying migration: " & filename & "..."

' Execute the migration
' NOTE: Access/Jet does NOT support DDL (CREATE TABLE, etc.) inside transactions
' So we run without transaction wrapper and rely on error checking instead
Dim conn, migrationSuccess
Set conn = GetConnection()

On Error Resume Next
migrationSuccess = ExecuteMigrationFile(filename, "Up", conn)

If Err.Number <> 0 Then
WScript.Echo "ERROR: Migration failed - " & Err.Description
WScript.Echo "Error Number: " & Err.Number
conn.Close
Err.Raise vbObjectError + 2, "Migrator", "Migration failed: " & Err.Description
End If
On Error GoTo 0

' Check if migration had SQL errors
If Not migrationSuccess Then
WScript.Echo ""
WScript.Echo "ERROR: Migration failed due to SQL errors (see above)."
WScript.Echo "Migration NOT recorded. Please fix the migration and try again."
conn.Close
WScript.Quit 1
End If

' Record the migration
On Error Resume Next
Dim cmd
Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = conn
cmd.CommandText = "INSERT INTO schema_migrations (version, applied_at) VALUES (?, ?)"
cmd.Execute , Array(version, Now())

If Err.Number <> 0 Then
WScript.Echo "ERROR: Failed to record migration - " & Err.Description
conn.Close
Err.Raise vbObjectError + 3, "Migrator", "Failed to record migration: " & Err.Description
End If
On Error GoTo 0

conn.Close
WScript.Echo "Migration " & version & " applied successfully."
End Sub

Sub RollbackMigration(filename)
Dim version
version = GetVersionFromFilename(filename)

If version = "" Then
Err.Raise vbObjectError + 1, "Migrator", "Invalid migration filename format: " & filename
End If

' Check if applied
Dim applied
Set applied = GetAppliedMigrations()
If Not applied.Exists(version) Then
WScript.Echo "Migration " & version & " not applied. Skipping."
Exit Sub
End If

WScript.Echo "Rolling back migration: " & filename & "..."

' Execute the migration
' NOTE: Access/Jet does NOT support DDL (DROP TABLE, etc.) inside transactions
Dim conn, rollbackSuccess
Set conn = GetConnection()

On Error Resume Next
rollbackSuccess = ExecuteMigrationFile(filename, "Down", conn)

If Err.Number <> 0 Then
WScript.Echo "ERROR: Rollback failed - " & Err.Description
WScript.Echo "Error Number: " & Err.Number
conn.Close
Err.Raise vbObjectError + 4, "Migrator", "Rollback failed: " & Err.Description
End If
On Error GoTo 0

' Check if rollback had SQL errors
If Not rollbackSuccess Then
WScript.Echo ""
WScript.Echo "ERROR: Rollback failed due to SQL errors (see above)."
WScript.Echo "Migration record NOT removed. Please fix the issue manually."
conn.Close
WScript.Quit 1
End If

' Remove migration record
On Error Resume Next
Dim cmd
Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = conn
cmd.CommandText = "DELETE FROM schema_migrations WHERE version = ?"
cmd.Execute , Array(version)

If Err.Number <> 0 Then
WScript.Echo "ERROR: Failed to remove migration record - " & Err.Description
conn.Close
Err.Raise vbObjectError + 5, "Migrator", "Failed to remove migration record: " & Err.Description
End If
On Error GoTo 0

conn.Close
WScript.Echo "Migration " & version & " rolled back successfully."
End Sub

'=======================================================================================================================
' HELPER FUNCTIONS
'=======================================================================================================================

Sub ShowUsage()
WScript.Echo "Usage: cscript //nologo scripts\runMigrations.vbs [command]"
WScript.Echo ""
WScript.Echo "Commands:"
WScript.Echo " up - Apply all pending migrations (default)"
WScript.Echo " down - Rollback the last migration"
WScript.Echo " status - Show migration status"
WScript.Echo " apply <file> - Apply a specific migration file"
WScript.Echo " rollback <file> - Rollback a specific migration file"
WScript.Echo ""
WScript.Echo "Examples:"
WScript.Echo " cscript //nologo scripts\runMigrations.vbs"
WScript.Echo " cscript //nologo scripts\runMigrations.vbs up"
WScript.Echo " cscript //nologo scripts\runMigrations.vbs down"
WScript.Echo " cscript //nologo scripts\runMigrations.vbs status"
End Sub

Function GetConnectionString(configPath)
If Not fso.FileExists(configPath) Then
GetConnectionString = ""
Exit Function
End If

Dim xmlDoc, node
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.async = False
xmlDoc.load configPath

Set node = xmlDoc.selectSingleNode("//appSettings/add[@key='ConnectionString']/@value")
If node Is Nothing Then
GetConnectionString = ""
Else
GetConnectionString = node.text
End If
End Function

Function GetConnection()
Dim conn
Set conn = CreateObject("ADODB.Connection")
conn.Open connectionString
Set GetConnection = conn
End Function

Sub EnsureSchemaMigrationsTable()
Dim conn, rs
Set conn = GetConnection()

On Error Resume Next
Set rs = conn.Execute("SELECT TOP 1 version FROM schema_migrations")

If Err.Number <> 0 Then
' Table doesn't exist, create it
Err.Clear
On Error GoTo 0

conn.Execute "CREATE TABLE schema_migrations (" & _
"version VARCHAR(14) PRIMARY KEY, " & _
"applied_at DATETIME NOT NULL)"
Else
If Not rs Is Nothing Then
If Not rs.EOF Then rs.Close
End If
End If

conn.Close
On Error GoTo 0
End Sub

Function GetAppliedMigrations()
Dim conn, rs, versions, version
Set conn = GetConnection()
Set versions = CreateObject("Scripting.Dictionary")

Set rs = conn.Execute("SELECT version FROM schema_migrations ORDER BY version")

Do While Not rs.EOF
version = Trim(rs("version"))
versions.Add version, True
rs.MoveNext
Loop

rs.Close
conn.Close

Set GetAppliedMigrations = versions
End Function

Function GetAvailableMigrations()
Dim folder, files, file, migrations, version
Set migrations = CreateObject("Scripting.Dictionary")

If Not fso.FolderExists(migrationsPath) Then
Set GetAvailableMigrations = migrations
Exit Function
End If

Set folder = fso.GetFolder(migrationsPath)
Set files = folder.Files

For Each file In files
If LCase(fso.GetExtensionName(file.Name)) = "asp" Then
version = GetVersionFromFilename(file.Name)
If version <> "" Then
migrations.Add version, file.Name
End If
End If
Next

Set GetAvailableMigrations = migrations
End Function

Function GetPendingMigrations()
Dim applied, available, pending, version
Set applied = GetAppliedMigrations()
Set available = GetAvailableMigrations()
Set pending = CreateObject("Scripting.Dictionary")

For Each version In available.Keys
If Not applied.Exists(version) Then
pending.Add version, available(version)
End If
Next

Set GetPendingMigrations = pending
End Function

Function GetVersionFromFilename(filename)
Dim parts
parts = Split(filename, "_")

If UBound(parts) >= 0 Then
Dim version
version = parts(0)
' Validate it's a 14-digit timestamp
If Len(version) = 14 And IsNumeric(version) Then
GetVersionFromFilename = version
Exit Function
End If
End If

GetVersionFromFilename = ""
End Function

' Global variable to hold migration context for error checking
Dim g_migrationContext

Function ExecuteMigrationFile(filename, direction, conn)
Dim migrationPath, fileContent, migration
migrationPath = migrationsPath & "\" & filename

If Not fso.FileExists(migrationPath) Then
Err.Raise vbObjectError + 6, "Migrator", "Migration file not found: " & migrationPath
End If

' Create migration context
Set migration = New MigrationContext
Set migration.Connection = conn
Set g_migrationContext = migration ' Store globally for error checking

' Read and execute the migration file
Dim stream
Set stream = fso.OpenTextFile(migrationPath, 1)
fileContent = stream.ReadAll
stream.Close

' Remove ASP tags
fileContent = Replace(fileContent, "<%", "")
fileContent = Replace(fileContent, "%>", "")

' Execute the migration code
ExecuteGlobal fileContent

' Call the appropriate method
If direction = "Up" Then
Migration_Up migration
ElseIf direction = "Down" Then
Migration_Down migration
End If

' Return True if successful, False if error
ExecuteMigrationFile = Not migration.HasError
End Function

'=======================================================================================================================
' MIGRATION CONTEXT CLASS
'=======================================================================================================================
Class MigrationContext
Public Connection
Public HasError
Public LastErrorMessage
Public LastErrorNumber

Private Sub Class_Initialize()
HasError = False
LastErrorMessage = ""
LastErrorNumber = 0
End Sub

Public Sub ExecuteSQL(sql)
If HasError Then Exit Sub ' Skip if previous error occurred

On Error Resume Next
Connection.Execute sql
If Err.Number <> 0 Then
HasError = True
LastErrorNumber = Err.Number
LastErrorMessage = "SQL Error: " & Err.Description & " (Error " & Err.Number & ")" & vbCrLf & "SQL: " & sql
WScript.Echo " ERROR executing SQL: " & Err.Description
WScript.Echo " Error Number: " & Err.Number
WScript.Echo " SQL: " & sql
Err.Clear
End If
On Error GoTo 0
End Sub

Public Sub CreateTable(tableName, columns)
If HasError Then Exit Sub
WScript.Echo " Creating table: " & tableName
ExecuteSQL "CREATE TABLE " & tableName & " (" & columns & ")"
End Sub

Public Sub DropTable(tableName)
If HasError Then Exit Sub
WScript.Echo " Dropping table: " & tableName
ExecuteSQL "DROP TABLE " & tableName
End Sub

Public Sub AddColumn(tableName, columnName, columnType)
If HasError Then Exit Sub
WScript.Echo " Adding column: " & tableName & "." & columnName
ExecuteSQL "ALTER TABLE " & tableName & " ADD COLUMN " & columnName & " " & columnType
End Sub

Public Sub DropColumn(tableName, columnName)
If HasError Then Exit Sub
WScript.Echo " Dropping column: " & tableName & "." & columnName
ExecuteSQL "ALTER TABLE " & tableName & " DROP COLUMN " & columnName
End Sub

Public Sub CreateIndex(indexName, tableName, columns)
If HasError Then Exit Sub
WScript.Echo " Creating index: " & indexName & " on " & tableName
ExecuteSQL "CREATE INDEX " & indexName & " ON " & tableName & " (" & columns & ")"
End Sub

Public Sub DropIndex(indexName, tableName)
If HasError Then Exit Sub
WScript.Echo " Dropping index: " & indexName & " on " & tableName
ExecuteSQL "DROP INDEX " & indexName & " ON " & tableName
End Sub

Public Function DB()
Set DB = Me
End Function
End Class

+ 352
- 0
scripts/templates/Api.tpl.asp View File

@@ -0,0 +1,352 @@
<%
' Api{{TABLE}}Controller: JSON API for the {{TABLE}} table. No layout, no cookies/CSRF (stateless).
' Generated {{DATE}} by scripts\GenerateApi.vbs (scripts\gen.cmd api). Spec: public/api/{{ROUTE}}.openapi.json
'
' Routes (public/Default.asp):
' GET /api/{{ROUTE}} Index ?q= ?page= ?per_page= -> {"data":[...],"meta":{...}}
' GET /api/{{ROUTE}}/:id Show -> {"data":{...}}
' POST /api/{{ROUTE}} Create JSON body -> 201 + Location
' PUT /api/{{ROUTE}}/:id Update JSON body (full) -> 200
' PATCH /api/{{ROUTE}}/:id Update JSON body (only the fields sent change)
' DELETE /api/{{ROUTE}}/:id Delete -> 200 {"deleted":true}
'
' Errors: {"error":{"message":"...","details":["..."]}} with 400, 404, 405 or 422.
' Body fields:
{{DOC_FIELDS}}
Const {{CONST}}_PER_PAGE = 10
Const {{CONST}}_MAX_PER_PAGE = 100

Class Api{{TABLE}}Controller_Class
{{MEMBERS}}

' Dispatcher reads this to decide whether to wrap the output in the HTML layout
Public Property Get useLayout()
useLayout = False
End Property

Public Property Let useLayout(v)
End Property

'---------------------------------------------------------------
Public Sub Index()
Dim q, page, per_page, page_count, record_count, items, i, rowsJson
q = Trim("" & Request.QueryString("q"))
page = ToInt(Request.QueryString("page"), 1, 1, 1000000)
per_page = ToInt(Request.QueryString("per_page"), {{CONST}}_PER_PAGE, 1, {{CONST}}_MAX_PER_PAGE)
page_count = 1
record_count = 0
items = {{TABLE}}Repository().SearchTablePaged({{SEARCH_COLS}}, q, "{{ORDER_COL}}", per_page, page, page_count, record_count)

rowsJson = ""
For i = 0 To UBound(items)
If i > 0 Then
rowsJson = rowsJson & ","
End If
rowsJson = rowsJson & RowJson(items(i))
Next

SendRaw 200, "{""data"":[" & rowsJson & "],""meta"":{""page"":" & page & ",""per_page"":" & per_page & _
",""page_count"":" & page_count & ",""record_count"":" & record_count & "}}"
End Sub

Public Sub Show(id)
Dim rec
Set rec = LoadRecord(id)
If rec Is Nothing Then Exit Sub
SendRaw 200, "{""data"":" & RowJson(rec) & "}"
End Sub

Public Sub Create()
Dim text, rec, errs
If Not RequireMethod("POST") Then Exit Sub
text = ReadBodyText()
If IsEmpty(text) Then Exit Sub

errs = ParseFields(text, False)
If UBound(errs) >= 0 Then
SendErrors 422, "Validation failed.", errs
Exit Sub
End If
Set rec = New POBO_{{TABLE}}
{{NEW_DEFAULTS}}
ApplyFields rec

On Error Resume Next
{{TABLE}}Repository().AddNew rec
If Err.Number <> 0 Then
DbFailed Err.Number
Exit Sub
End If
On Error GoTo 0
Response.AddHeader "Location", "/api/{{ROUTE}}/" & rec.{{PK}}
SendRaw 201, "{""data"":" & RowJson(rec) & "}"
End Sub

Public Sub Update(id)
Dim text, rec, errs, partial, verb
verb = UCase(Request.ServerVariables("REQUEST_METHOD"))
If verb <> "PUT" And verb <> "PATCH" Then
SendError 405, "Method not allowed. Use PUT or PATCH."
Exit Sub
End If
text = ReadBodyText()
If IsEmpty(text) Then Exit Sub
partial = (verb = "PATCH")
errs = ParseFields(text, partial)
If UBound(errs) >= 0 Then
SendErrors 422, "Validation failed.", errs
Exit Sub
End If
Set rec = LoadRecord(id)
If rec Is Nothing Then Exit Sub
ApplyFields rec

{{UPDATE_STAMPS}}
On Error Resume Next
{{TABLE}}Repository().Update rec
If Err.Number <> 0 Then
DbFailed Err.Number
Exit Sub
End If
On Error GoTo 0
SendRaw 200, "{""data"":" & RowJson(rec) & "}"
End Sub

Public Sub Delete(id)
Dim rec
If Not RequireMethod("DELETE") Then Exit Sub
Set rec = LoadRecord(id)
If rec Is Nothing Then Exit Sub
On Error Resume Next
{{TABLE}}Repository().Delete rec.{{PK}}
If Err.Number <> 0 Then
DbFailed Err.Number
Exit Sub
End If
On Error GoTo 0
SendRaw 200, "{""deleted"":true,""id"":" & CLng(rec.{{PK}}) & "}"
End Sub

'===============================================================
' Helpers
'===============================================================
' JSON in/out uses core/lib.JsonLite.asp (pure VBScript). G3JSON dictionaries and G3DB interfered with each other
' under the AxonASP HTTP server, so no native JSON objects are used here (see AGENTS.md).
Private Sub SendRaw(status, jsonText)
Response.Clear
Response.Status = StatusLine(status)
Response.ContentType = "application/json"
Response.Charset = "utf-8"
Response.Write jsonText
End Sub

Private Sub SendError(status, message)
SendErrors status, message, Array()
End Sub

Private Sub SendErrors(status, message, details)
Dim i, list
list = ""
For i = 0 To UBound(details)
If i > 0 Then
list = list & ","
End If
list = list & JsonLite_Quote(details(i))
Next
SendRaw status, "{""error"":{""message"":" & JsonLite_Quote(message) & ",""details"":[" & list & "]}}"
End Sub

' A failed write becomes a JSON 500 (the dispatcher would otherwise swallow the error and return an empty 200).
' The detail is not sent to the client; log it if you need it.
Private Sub DbFailed(errNumber)
Err.Clear
On Error GoTo 0
SendError 500, "Database error (" & errNumber & "). The change was not saved."
End Sub

Private Function StatusLine(status)
Select Case status
Case 200: StatusLine = "200 OK"
Case 201: StatusLine = "201 Created"
Case 400: StatusLine = "400 Bad Request"
Case 404: StatusLine = "404 Not Found"
Case 405: StatusLine = "405 Method Not Allowed"
Case 422: StatusLine = "422 Unprocessable Entity"
Case 500: StatusLine = "500 Internal Server Error"
Case Else: StatusLine = status & " Error"
End Select
End Function

Private Function RequireMethod(verb)
RequireMethod = (UCase(Request.ServerVariables("REQUEST_METHOD")) = verb)
If Not RequireMethod Then
SendError 405, "Method not allowed. Use " & verb & "."
End If
End Function

Private Function ToInt(v, dflt, lo, hi)
Dim s
s = Trim("" & v)
ToInt = dflt
If Len(s) > 0 Then
If IsNumeric(s) Then
ToInt = CLng(s)
End If
End If
If ToInt < lo Then
ToInt = lo
End If
If ToInt > hi Then
ToInt = hi
End If
End Function

' Returns the record, or Nothing after sending a 404
Private Function LoadRecord(id)
Dim s
Set LoadRecord = Nothing
s = Trim("" & id)
If Len(s) = 0 Or Not IsNumeric(s) Then
SendError 404, "{{TABLE}} record not found."
Exit Function
End If

On Error Resume Next
Set LoadRecord = {{TABLE}}Repository().FindByID(CLng(s))
If Err.Number <> 0 Then
Err.Clear
Set LoadRecord = Nothing
On Error GoTo 0
SendError 404, "{{TABLE}} record not found."
Exit Function
End If
On Error GoTo 0
End Function

Private Function RowJson(rec)
RowJson = {{ROW_JSON}}
End Function

' Reads the raw request body as UTF-8 text and checks it is a JSON object. Sends 400 and returns False on failure.
' Only text crosses procedure boundaries: dictionaries passed between Subs/Functions were unreliable under the
' HTTP server (see AGENTS.md), so Apply parses the text itself.
Private Function ReadBodyText()
Dim n, text
ReadBodyText = Empty
n = Request.TotalBytes
If n = 0 Then
SendError 400, "Request body is empty. Send a JSON object."
Exit Function
End If
' AxonASP: BinaryRead returns one character per byte, so decode the UTF-8 by hand.
text = Utf8Decode(CStr(Request.BinaryRead(n)))

If JsonLite_Parse(text) Is Nothing Then
SendError 400, "Body must be a valid JSON object."
Exit Function
End If
ReadBodyText = text
End Function

' Decodes a string holding raw UTF-8 bytes (one byte per character) into real Unicode text.
Private Function Utf8Decode(ByVal s)
Dim i, n, c, cp, extra, out, k, ok, b
n = Len(s)
out = ""
i = 1
Do While i <= n
c = AscW(Mid(s, i, 1)) And 255
If c < 128 Then
out = out & Chr(c)
i = i + 1
Else
extra = -1
cp = 0
If c >= 240 And c <= 247 Then
extra = 3
cp = c And 7
ElseIf c >= 224 And c <= 239 Then
extra = 2
cp = c And 15
ElseIf c >= 194 And c <= 223 Then
extra = 1
cp = c And 31
End If
ok = (extra > 0 And i + extra <= n)
If ok Then
For k = 1 To extra
b = AscW(Mid(s, i + k, 1)) And 255
If b < 128 Or b > 191 Then
ok = False
Else
cp = cp * 64 + (b And 63)
End If
Next
End If
If ok And cp <= 1114111 Then
If cp >= 65536 Then
cp = cp - 65536
out = out & ChrW(55296 + Int(cp / 1024)) & ChrW(56320 + (cp Mod 1024))
Else
out = out & ChrW(cp)
End If
i = i + extra + 1
Else
out = out & ChrW(65533) ' invalid byte sequence -> replacement character
i = i + 1
End If
End If
Loop
Utf8Decode = out
End Function

' Parses and validates the JSON body into the f_* members. Returns an array of error messages.
' partial=True (PATCH): only fields present are validated/applied; required fields are enforced when partial=False.
' Each field is read from its column name ("Name") or its camelCase form ("name").
Private Function ParseFields(ByVal text, partial)
Dim input, errs, n, v, k
{{CLEAR_FIELDS}}
Set input = JsonLite_Parse(text)
ReDim errs(-1)
n = -1
{{PARSE_BODY}}
ParseFields = errs
End Function

' Copies the fields parsed by ParseFields onto the record (only the ones that were sent)
Private Sub ApplyFields(rec)
{{APPLY_BODY}}
End Sub

' Server-side timestamp for CreatedAt / UpdatedAt columns
Private Function NowStamp()
Dim d
d = Now()
NowStamp = Year(d) & "-" & Right("0" & Month(d), 2) & "-" & Right("0" & Day(d), 2) & " " & _
Right("0" & Hour(d), 2) & ":" & Right("0" & Minute(d), 2) & ":" & Right("0" & Second(d), 2)
End Function

' Date column -> JSON string or null
Private Function JsonDate(v)
If IsNull(v) Then
JsonDate = "null"
Else
If IsDate(v) Then
v = CDate(v)
JsonDate = JsonLite_Quote(Year(v) & "-" & Right("0" & Month(v), 2) & "-" & Right("0" & Day(v), 2) & " " & _
Right("0" & Hour(v), 2) & ":" & Right("0" & Minute(v), 2) & ":" & Right("0" & Second(v), 2))
Else
JsonDate = JsonLite_Quote(CStr(v))
End If
End If
End Function
End Class

Dim Api{{TABLE}}Controller_Class__Singleton
Function Api{{TABLE}}Controller()
If IsEmpty(Api{{TABLE}}Controller_Class__Singleton) Then
Set Api{{TABLE}}Controller_Class__Singleton = New Api{{TABLE}}Controller_Class
End If
Set Api{{TABLE}}Controller = Api{{TABLE}}Controller_Class__Singleton
End Function
%>

+ 26
- 0
scripts/templates/POBO.tpl.asp View File

@@ -0,0 +1,26 @@
<%
' Auto-generated POBO for table [{{TABLE}}]
' Generated on {{DATE}}
' Generator: GenerateRepo.vbs (AxonASP/G3DB edition)

Class POBO_{{TABLE}}
' Public array of all property names
Public Properties

{{FIELDS}}
Private Sub Class_Initialize()
{{DEFAULTS}}
Properties = Array({{PROPLIST}})
End Sub

Public Property Get PrimaryKey()
PrimaryKey = "{{PK}}"
End Property

Public Property Get TableName()
TableName = "{{TABLE}}"
End Property

{{PROPERTIES}}
End Class
%>

+ 211
- 0
scripts/templates/Repository.tpl.asp View File

@@ -0,0 +1,211 @@
<%
' Auto-generated Repository for table [{{TABLE}}]
' Generated on {{DATE}}
' Generator: GenerateRepo.vbs (AxonASP/G3DB edition)
'
' Dependencies:
' - core/lib.DAL.asp (DAL() singleton, backed by G3DB)
' - POBO_{{TABLE}}.asp
'
' Rows are mapped by column position (G3DB result sets do not expose column names), so the SELECT list below
' and Map() must stay in the same order. Re-run the generator after changing the table.
' All list-returning methods return a plain VBScript array of POBO_{{TABLE}} objects (UBound = -1 when empty).

Class {{TABLE}}Repository_Class

' Columns that may appear in WHERE / ORDER BY (guards against SQL injection through column names)
Private Function IsKnownColumn(name)
IsKnownColumn = (InStr(1, "|{{COLUMN_LIST}}|", "|" & CStr(name) & "|", vbTextCompare) > 0)
End Function

Private Function Q(name)
Q = Chr(34) & Replace(CStr(name), Chr(34), Chr(34) & Chr(34)) & Chr(34)
End Function

Private Function Map(rs)
Dim m
Set m = New POBO_{{TABLE}}
{{MAP_LINES}}
Set Map = m
End Function

Private Function Collect(rs)
Dim list(), n
n = -1
Do Until rs.EOF
n = n + 1
ReDim Preserve list(n)
Set list(n) = Map(rs)
rs.MoveNext
Loop
rs.Close
If n = -1 Then
Collect = Array()
Else
Collect = list
End If
End Function

' where_kvarray: Empty or Array("Col", value, "Col2", value2, ...). Conditions are ANDed.
Private Sub BuildWhere(where_kvarray, ByRef sqlWhere, ByRef params)
Dim i, n
sqlWhere = ""
params = Array()
If Not IsArray(where_kvarray) Then Exit Sub
If UBound(where_kvarray) < 1 Then Exit Sub
n = -1
For i = 0 To UBound(where_kvarray) - 1 Step 2
If Not IsKnownColumn(where_kvarray(i)) Then
Err.Raise 5, "{{TABLE}}Repository", "Unknown column in filter: " & where_kvarray(i)
End If
If n = -1 Then
sqlWhere = " WHERE "
Else
sqlWhere = sqlWhere & " AND "
End If
n = n + 1
ReDim Preserve params(n)
params(n) = where_kvarray(i + 1)
sqlWhere = sqlWhere & Q(where_kvarray(i)) & " = ?"
Next
End Sub

' orderArg: Empty, "Col", "Col DESC", or Array("Col", "Col2 DESC")
Private Function BuildOrderBy(orderArg)
Dim s, i, item, parts, colName, dir
If IsEmpty(orderArg) Or IsNull(orderArg) Then
BuildOrderBy = " ORDER BY " & Q("{{PK}}") & " ASC"
Exit Function
End If
If Not IsArray(orderArg) Then orderArg = Array(orderArg)
s = ""
For i = 0 To UBound(orderArg)
item = Trim(CStr(orderArg(i)))
If Len(item) > 0 Then
parts = Split(item, " ")
colName = parts(0)
dir = "ASC"
If UBound(parts) >= 1 Then
If UCase(parts(1)) = "DESC" Then dir = "DESC"
End If
If Not IsKnownColumn(colName) Then
Err.Raise 5, "{{TABLE}}Repository", "Unknown column in ORDER BY: " & colName
End If
If Len(s) > 0 Then s = s & ", "
s = s & Q(colName) & " " & dir
End If
Next
If Len(s) = 0 Then
BuildOrderBy = " ORDER BY " & Q("{{PK}}") & " ASC"
Else
BuildOrderBy = " ORDER BY " & s
End If
End Function

' Number of pages for total rows (always at least 1)
Private Function PagesFor(total, per_page)
If per_page < 1 Then
PagesFor = 1
Else
PagesFor = Int((total + per_page - 1) / per_page)
If PagesFor < 1 Then PagesFor = 1
End If
End Function

'-------------------------------------------------------------------------------------------------------------------
Public Function FindByID(id)
Dim rs
Set rs = DAL().Query("SELECT {{SELECT_LIST}} FROM {{QTABLE}} WHERE {{QPK}} = ?", id)
If rs.EOF Then
rs.Close
Err.Raise 1, "{{TABLE}}Repository", "{{TABLE}} record was not found with {{PK}} = '" & id & "'."
End If
Set FindByID = Map(rs)
rs.Close
End Function

Public Function GetAll(orderBy)
GetAll = Find(Empty, orderBy)
End Function

Public Function Find(where_kvarray, order_string_or_array)
Dim sqlWhere, params, rs
BuildWhere where_kvarray, sqlWhere, params
Set rs = DAL().Query("SELECT {{SELECT_LIST}} FROM {{QTABLE}}" & sqlWhere & BuildOrderBy(order_string_or_array), params)
Find = Collect(rs)
End Function

Public Function Count(where_kvarray)
Dim sqlWhere, params, rs
BuildWhere where_kvarray, sqlWhere, params
Set rs = DAL().Query("SELECT COUNT(*) FROM {{QTABLE}}" & sqlWhere, params)
Count = CLng(rs(0))
rs.Close
End Function

Public Function FindPaged(where_kvarray, order_string_or_array, per_page, page_num, ByRef page_count, ByRef record_count)
Dim sqlWhere, params, rs
BuildWhere where_kvarray, sqlWhere, params
record_count = Count(where_kvarray)
page_count = PagesFor(record_count, per_page)
Set rs = DAL().PagedQuery("SELECT {{SELECT_LIST}} FROM {{QTABLE}}" & sqlWhere & BuildOrderBy(order_string_or_array), params, per_page, page_num)
FindPaged = Collect(rs)
End Function

' Case-insensitive LIKE across columns_array (OR). Empty search_value returns everything.
Public Function SearchTablePaged(columns_array, search_value, order_string_or_array, per_page, page_num, ByRef page_count, ByRef record_count)
Dim sqlWhere, params(), i, n, rs, countRs
sqlWhere = ""
n = -1
If IsArray(columns_array) And Len(CStr(search_value)) > 0 Then
For i = 0 To UBound(columns_array)
If Not IsKnownColumn(columns_array(i)) Then
Err.Raise 5, "{{TABLE}}Repository", "Unknown column in search: " & columns_array(i)
End If
If n = -1 Then
sqlWhere = " WHERE ("
Else
sqlWhere = sqlWhere & " OR "
End If
n = n + 1
ReDim Preserve params(n)
params(n) = "%" & search_value & "%"
sqlWhere = sqlWhere & Q(columns_array(i)) & " LIKE ?"
Next
sqlWhere = sqlWhere & ")"
End If
If n = -1 Then ReDim params(-1)

Set countRs = DAL().Query("SELECT COUNT(*) FROM {{QTABLE}}" & sqlWhere, params)
record_count = CLng(countRs(0))
countRs.Close
page_count = PagesFor(record_count, per_page)

Set rs = DAL().PagedQuery("SELECT {{SELECT_LIST}} FROM {{QTABLE}}" & sqlWhere & BuildOrderBy(order_string_or_array), params, per_page, page_num)
SearchTablePaged = Collect(rs)
End Function

' Inserts the model and stores the new primary key back on it
Public Sub AddNew(ByRef model)
Dim res
Set res = DAL().Exec("INSERT INTO {{QTABLE}} ({{INSERT_COLS}}) VALUES ({{INSERT_PLACEHOLDERS}})", {{INSERT_PARAMS}})
model.{{PK}} = res.LastInsertId
End Sub

Public Sub Update(model)
DAL().Execute "UPDATE {{QTABLE}} SET {{UPDATE_SET}} WHERE {{QPK}} = ?", {{UPDATE_PARAMS}}
End Sub

Public Sub Delete(id)
DAL().Execute "DELETE FROM {{QTABLE}} WHERE {{QPK}} = ?", id
End Sub
End Class

Dim {{TABLE}}Repository__Singleton
Function {{TABLE}}Repository()
If IsEmpty({{TABLE}}Repository__Singleton) Then
Set {{TABLE}}Repository__Singleton = New {{TABLE}}Repository_Class
End If
Set {{TABLE}}Repository = {{TABLE}}Repository__Singleton
End Function
%>

+ 0
- 190
tests/PlainRunnerTheme.asp View File

@@ -1,190 +0,0 @@
<%
Class PlainRunnerTheme
Public Sub Render(ByRef objRunner)
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MVC-Starter Test Runner</title>
<style type="text/css">
body {
font-family: Arial, sans-serif;
margin: 24px;
color: #1f2933;
background: #f7fafc;
}

h1 {
margin-bottom: 8px;
}

.summary {
margin-bottom: 16px;
padding: 12px 16px;
background: #ffffff;
border: 1px solid #d9e2ec;
}

.page {
margin-bottom: 16px;
padding: 12px 16px;
border: 1px solid #bcccdc;
background: #ffffff;
}

.page.pass {
border-left: 6px solid #2f855a;
}

.page.fail {
border-left: 6px solid #c53030;
}

.module {
margin-top: 12px;
padding-top: 8px;
border-top: 1px solid #e2e8f0;
}

.test {
margin: 6px 0;
}

.pass-text {
color: #2f855a;
}

.fail-text {
color: #c53030;
}

code {
background: #edf2f7;
padding: 2px 4px;
}
</style>
</head>
<body>
<h1>MVC-Starter Test Runner</h1>
<p>Dev-only aspunit runner for the separate <code>tests/</code> IIS application.</p>

<div id="summary" class="summary">Running tests...</div>
<div id="results"></div>

<script type="text/javascript">
(function() {
var pages = [<%= GetPagesAsJSArray(objRunner.Pages) %>];
var summaryEl = document.getElementById("summary");
var resultsEl = document.getElementById("results");
var totals = { pages: 0, passedPages: 0, tests: 0, passedTests: 0 };

function escapeHtml(value) {
return String(value)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}

function renderModule(module) {
var testsHtml = module.tests.map(function(test) {
return '<div class="test ' + (test.passed ? 'pass-text' : 'fail-text') + '">' +
'<strong>' + escapeHtml(test.name) + ':</strong> ' +
escapeHtml(test.description || '') +
'</div>';
}).join("");

return '<div class="module">' +
'<div><strong>' + escapeHtml(module.name) + '</strong> (' + module.passCount + '/' + module.testCount + ')</div>' +
testsHtml +
'</div>';
}

function renderPage(page, data, error) {
var wrapper = document.createElement("div");
wrapper.className = "page " + (error || !data.passed ? "fail" : "pass");

if (error) {
wrapper.innerHTML =
'<div><strong>' + escapeHtml(page) + '</strong></div>' +
'<div class="fail-text">' + escapeHtml(error) + '</div>';
resultsEl.appendChild(wrapper);
return;
}

wrapper.innerHTML =
'<div><strong>' + escapeHtml(page) + '</strong> - ' +
(data.passed ? '<span class="pass-text">PASS</span>' : '<span class="fail-text">FAIL</span>') +
' (' + data.passCount + '/' + data.testCount + ')</div>' +
data.modules.map(renderModule).join("");

resultsEl.appendChild(wrapper);
}

function updateSummary(done) {
summaryEl.innerHTML =
'<strong>Pages:</strong> ' + totals.passedPages + '/' + totals.pages +
' &nbsp; <strong>Tests:</strong> ' + totals.passedTests + '/' + totals.tests +
(done ? '' : ' &nbsp; <em>Running...</em>');
}

function next(index) {
if (index >= pages.length) {
updateSummary(true);
return;
}

var page = pages[index];
fetch(page + '?task=test', { credentials: 'same-origin' })
.then(function(response) {
if (!response.ok) {
throw new Error('HTTP ' + response.status + ' while loading ' + page);
}
return response.json();
})
.then(function(data) {
totals.pages += 1;
totals.tests += data.testCount;
totals.passedTests += data.passCount;
if (data.passed) {
totals.passedPages += 1;
}

renderPage(page, data, null);
updateSummary(false);
next(index + 1);
})
.catch(function(error) {
totals.pages += 1;
renderPage(page, null, error.message);
updateSummary(false);
next(index + 1);
});
}

updateSummary(false);
next(0);
})();
</script>
</body>
</html>
<%
End Sub

Private Function GetPagesAsJSArray(ByRef pages)
Dim strReturn, i

strReturn = ""
For i = 0 To (pages.Count - 1)
strReturn = strReturn & """" & Replace(pages.Item(i), """", "\""") & """"
If i < (pages.Count - 1) Then
strReturn = strReturn & ", "
End If
Next

GetPagesAsJSArray = strReturn
End Function
End Class
%>

+ 0
- 21
tests/aspunit/LICENSE-MIT View File

@@ -1,21 +0,0 @@
The MIT License

Copyright (c) 2013 R. Peter Clark, Inc. http://www.rpeterclark.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

+ 0
- 12
tests/aspunit/Lib/ASPUnit.asp View File

@@ -1,12 +0,0 @@
<!-- #include file="classes/ASPUnitLibrary.asp" -->
<!-- #include file="classes/ASPUnitTester.asp" -->
<!-- #include file="classes/ASPUnitRunner.asp" -->
<!-- #include file="classes/ASPUnitUIModern.asp" -->
<!-- #include file="classes/ASPUnitJSONResponder.asp" -->

<%
Dim ASPUnit
Set ASPUnit = New ASPUnitLibrary

ASPUnit.Task = Request.QueryString("task")
%>

+ 0
- 123
tests/aspunit/Lib/classes/ASPUnitJSONResponder.asp View File

@@ -1,123 +0,0 @@
<%
Class ASPUnitJSONResponder
Private _
m_Serializer

Private Sub Class_Initialize()
Set m_Serializer = New ASPUnitScenarioSerializer
End Sub

Private Sub Class_Terminate()
Set m_Serializer = Nothing
End Sub

Public Property Set Serializer(objValue)
Set m_Serializer = objValue
End Property

Public Sub Respond(objModules)
Response.ContentType = "application/json"
Response.Write m_Serializer.ToJSON(objModules)
End Sub
End Class

' Private Classes

Class ASPUnitScenarioSerializer
Function ToJSON(objScenario)
Dim objStream, _
objModule, _
objTest, _
i, j, _
strReturn

Set objStream = Server.CreateObject("ADODB.Stream")

objStream.Type = 2 ' adTypeText
objStream.Mode = 3 ' adModeReadWrite
objStream.Open

Call objStream.WriteText("{")
Call objStream.WriteText(JSONNumberPair("testCount", objScenario.TestCount) & ",")
Call objStream.WriteText(JSONNumberPair("passCount", objScenario.PassCount) & ",")
Call objStream.WriteText(JSONBooleanPair("passed", objScenario.Passed) & ",")
Call objStream.WriteText(JSONString("modules") & ":[")
For i = 0 To (objScenario.Modules.Count - 1)
Set objModule = objScenario.Modules.Item(i)

Call objStream.WriteText("{")
Call objStream.WriteText(JSONStringPair("name", objModule.Name) & ",")
Call objStream.WriteText(JSONNumberPair("testCount", objModule.TestCount) & ",")
Call objStream.WriteText(JSONNumberPair("passCount", objModule.PassCount) & ",")
Call objStream.WriteText(JSONNumberPair("failCount", (objModule.FailCount)) & ",")
Call objStream.WriteText(JSONBooleanPair("passed", objModule.Passed) & ",")
Call objStream.WriteText(JSONNumberPair("duration", objModule.Duration) & ",")
Call objStream.WriteText(JSONString("tests") & ":[")
For j = 0 To (objModule.Tests.Count - 1)
Set objTest = objModule.Tests.Item(j)
Call objStream.WriteText("{")
Call objStream.WriteText(JSONStringPair("name", objTest.Name) & ",")
Call objStream.WriteText(JSONBooleanPair("passed", objTest.Passed) & ",")
Call objStream.WriteText(JSONStringPair("description", objTest.Description))
Call objStream.WriteText("}")

If j < (objModule.Tests.Count - 1) Then
Call objStream.WriteText(",")
End If

Set objTest = Nothing
Next
Call objStream.WriteText("]")
Call objStream.WriteText("}")

If i < (objScenario.Modules.Count - 1) Then
Call objStream.WriteText(",")
End If

Set objModule = Nothing
Next
Call objStream.WriteText("]")
Call objStream.WriteText("}")

objStream.Position = 0

strReturn = objStream.ReadText()

objStream.Close
Set objStream = Nothing

ToJSON = strReturn
End Function

Private Function JSONString(strValue)
JSONString = """" & JSONStringEscape(strValue) & """"
End Function

Private Function JSONStringPair(strName, strValue)
JSONStringPair = JSONString(strName) & ":" & JSONString(strValue)
End Function

Private Function JSONNumberPair(strName, varValue)
JSONNumberPair = JSONString(strName) & ":" & varValue
End Function

Private Function JSONBooleanPair(strName, blnValue)
JSONBooleanPair = JSONString(strName) & ":" & LCase(blnValue)
End Function

Private Function JSONStringEscape(strValue)
Dim strReturn

strReturn = strValue

strReturn = Replace(strReturn, "\", "\\")
strReturn = Replace(strReturn, """", "\""")
strReturn = Replace(strReturn, vbLf, "\n")
strReturn = Replace(strReturn, vbCr, "\n")
strReturn = Replace(strReturn, vbCrLf, "\n")
strReturn = Replace(strReturn, vbTab, "\t")

JSONStringEscape = strReturn
End Function
End Class
%>

+ 0
- 104
tests/aspunit/Lib/classes/ASPUnitLibrary.asp View File

@@ -1,104 +0,0 @@
<%
Class ASPUnitLibrary
Private _
m_Runner, _
m_Tester, _
m_Task

Public _
Version

Private Sub Class_Initialize()
Version = "0.1.0"

Set m_Runner = New ASPUnitRunner
Set m_Tester = New ASPUnitTester
End Sub

Private Sub Class_Terminate()
Set m_Runner = Nothing
Set m_Tester = Nothing
End Sub

Public Property Set Runner(ByRef objValue)
Set m_Runner = objValue
End Property

Public Property Set Tester(ByRef objValue)
Set m_Tester = objValue
End Property

Public Property Let Task(strTask)
m_Task = strTask
End Property

Public Sub Run()
Select Case UCase(m_Task)
Case "TEST"
Call m_Tester.Run()
Case Else
Call m_Runner.Run()
End Select
End Sub

' Test Service Facade

Public Property Set Responder(ByRef objValue)
Set m_Tester.Responder = objValue
End Property

Public Function CreateModule(strName, arrTests, objLifecycle)
Set CreateModule = m_Tester.CreateModule(strName, arrTests, objLifecycle)
End Function

Public Function CreateTest(strName)
Set CreateTest = m_Tester.CreateTest(strName)
End Function

Public Function CreateLifecycle(strSetup, strTeardown)
Set CreateLifecycle = m_Tester.CreateLifecycle(strSetup, strTeardown)
End Function

Public Sub AddModule(objModule)
Call m_Tester.AddModule(objModule)
End Sub

Public Sub AddModules(arrModules)
Call m_Tester.AddModules(arrModules)
End Sub

Public Function Ok(blnResult, strDescription)
Call m_Tester.Ok(blnResult, strDescription)
End Function

Public Function Equal(varActual, varExpected, strDescription)
Call m_Tester.Equal(varActual, varExpected, strDescription)
End Function

Public Function NotEqual(varActual, varExpected, strDescription)
Call m_Tester.NotEqual(varActual, varExpected, strDescription)
End Function

Public Function Same(varActual, varExpected, strDescription)
Call m_Tester.Same(varActual, varExpected, strDescription)
End Function

Public Function NotSame(varActual, varExpected, strDescription)
Call m_Tester.NotSame(varActual, varExpected, strDescription)
End Function

' UI Service Facade

Public Property Set Theme(ByRef objValue)
Set m_Runner.Theme = objValue
End Property

Public Sub AddPage(strPage)
Call m_Runner.AddPage(strPage)
End Sub

Public Sub AddPages(arrPages)
Call m_Runner.AddPages(arrPages)
End Sub
End Class
%>

+ 0
- 174
tests/aspunit/Lib/classes/ASPUnitRunner.asp View File

@@ -1,174 +0,0 @@
<%
Class ASPUnitRunner
Private _
m_Theme, _
m_Pages

Private Sub Class_Initialize()
Set m_Theme = New ASPUnitUIModern
Set m_Pages = Server.CreateObject("System.Collections.ArrayList")
End Sub

Private Sub Class_Terminate()
Set m_Pages = Nothing
Set m_Theme = Nothing
End Sub

Public Property Set Theme(ByRef objValue)
Set m_Theme = objValue
End Property

Public Property Get Pages
Set Pages = m_Pages
End Property

' Public methods to specify test pages

Public Sub AddPage(strPage)
Call m_Pages.Add(strPage)
End Sub

Public Sub AddPages(arrPages)
Dim i

For i = 0 To UBound(arrPages)
Call AddPage(arrPages(i))
Next
End Sub

' Method to run UI

Public Sub Run()
If m_Pages.Count = 0 Then
Call AddCurrentPage()
End If

Call m_Theme.Render(Me)
End Sub

Private Sub AddCurrentPage()
Call AddPage(Request.ServerVariables("URL"))
End Sub

Public Sub RenderJSLib() %>
<script>
var ASPUnit = function() {
'use strict';

var config = {
pages: [],
callbacks: {
onStart: [],
onStop: [],
onPageStart: [],
onPageSuccess: [],
onPageFail: [],
onPageFinish: [],
onFinish: [],
}
}

var getPageTimeout = null,
getPageXHR = null;

var status = {
pageIndex: 0,
pageCount: 0,
testCount: 0,
passCount: 0
};

function registerCallback(key, callback) {
config.callbacks[key].push(callback);
}

function callback(key, args) {
var callbacks = config.callbacks[key];
for (var i = 0, len = callbacks.length; i < len; i++) {
callbacks[i].call({}, args);
}
}

function getPage(page) {
callback('onPageStart', {page: page});

getPageXHR = $.getJSON(page + '?task=test')
.done(function(data) {
status.pageDoneCount++;
status.testCount += data.testCount;
status.passCount += data.passCount;

callback('onPageSuccess', $.extend({page: page}, data));
})
.fail(function(jqXHR, textStatus, errorThrown) {
callback('onPageFail', {
page: page,
error: errorThrown,
description: (jqXHR.status != 404) ? jqXHR.responseText : ''
});
})
.always(function() {
callback('onPageFinish', {
page: page,
status: status
});

if (status.pageIndex < (config.pages.length - 1)) {
getPageTimeout = setTimeout(function() {
getPage(config.pages[++status.pageIndex]);
}, 100);
} else {
callback('onFinish');
}
});
}

return {
load: function(pages) {
config.pages = pages;
status.pageCount = config.pages.length;
this.start();
},

start: function() {
callback('onStart');
getPage(config.pages[status.pageIndex]);
},

stop: function() {
getPageXHR.abort();
clearTimeout(getPageTimeout);
callback('onStop');
},

onStart: function(callback) { registerCallback('onStart', callback); },
onPageStart: function(callback) { registerCallback('onPageStart', callback); },
onPageSuccess: function(callback) { registerCallback('onPageSuccess', callback); },
onPageFail: function(callback) { registerCallback('onPageFail', callback); },
onPageFinish: function(callback) { registerCallback('onPageFinish', callback); },
onFinish: function(callback) { registerCallback('onFinish', callback); }
};
}();
</script> <%
End Sub

Public Sub RenderJSInit() %>
<script>$(function(){ASPUnit.load([<%= GetPagesAsJSString() %>])});</script> <%
End Sub

Private Function GetPagesAsJSString()
Dim strReturn, _
i

strReturn = ""
For i = 0 To (m_Pages.Count - 1)
strReturn = strReturn & "'" & m_Pages.Item(i) & "'"
If i < (m_Pages.Count - 1) Then
strReturn = strReturn & ", "
End If
Next

GetPagesAsJSString = strReturn
End Function
End Class
%>

+ 0
- 258
tests/aspunit/Lib/classes/ASPUnitTester.asp View File

@@ -1,258 +0,0 @@
<%
Class ASPUnitTester
Private _
m_Responder, _
m_Scenario

Private _
m_CurrentModule, _
m_CurrentTest

Private Sub Class_Initialize()
Set m_Responder = New ASPUnitJSONResponder
Set m_Scenario = New ASPUnitScenario
End Sub

Private Sub Class_Terminate()
Set m_Scenario = Nothing
Set m_Responder = Nothing
End Sub

Public Property Set Responder(ByRef objValue)
Set m_Responder = objValue
End Property

Public Property Get Modules()
Set Modules = m_Scenario.Modules
End Property

' Factory methods for private classes

Public Function CreateModule(strName, arrTests, objLifecycle)
Dim objReturn, _
i

Set objReturn = New ASPUnitModule
objReturn.Name = strName
For i = 0 To UBound(arrTests)
objReturn.Tests.Add(arrTests(i))
Next
Set objReturn.Lifecycle = objLifecycle

Set CreateModule = objReturn
End Function

Public Function CreateTest(strName)
Dim objReturn

Set objReturn = New ASPUnitTest
objReturn.Name = strName

Set CreateTest = objReturn
End Function

Public Function CreateLifecycle(strSetup, strTeardown)
Dim objReturn

Set objReturn = New ASPUnitTestLifecycle
objReturn.Setup = strSetup
objReturn.Teardown = strTeardown

Set CreateLifecycle = objReturn
End Function

' Public methods to add modules

Public Sub AddModule(objModule)
Call m_Scenario.Modules.Add(objModule)
End Sub

Public Sub AddModules(arrModules)
Dim i

For i = 0 To UBound(arrModules)
Call AddModule(arrModules(i))
Next
End Sub

' Assertion Methods

Private Function Assert(blnResult, strDescription)
If IsObject(m_CurrentTest) Then
m_CurrentTest.Passed = blnResult
m_CurrentTest.Description = strDescription
End If

Assert = blnResult
End Function

Public Function Ok(blnResult, strDescription)
Ok = Assert(blnResult, strDescription)
End Function

Public Function Equal(varActual, varExpected, strDescription)
Equal = Assert((varActual = varExpected), strDescription)
End Function

Public Function NotEqual(varActual, varExpected, strDescription)
NotEqual = Assert(Not (varActual = varExpected), strDescription)
End Function

Public Function Same(varActual, varExpected, strDescription)
Same = Assert((varActual Is varExpected), strDescription)
End Function

Public Function NotSame(varActual, varExpected, strDescription)
NotSame = Assert(Not (varActual Is varExpected), strDescription)
End Function

' Methods to run module tests

Public Sub Run()
Dim objModule, _
i

For i = 0 To (m_Scenario.Modules.Count - 1)
Set objModule = m_Scenario.Modules.Item(i)
Call RunModule(objModule)

m_Scenario.TestCount = m_Scenario.TestCount + objModule.TestCount
m_Scenario.PassCount = m_Scenario.PassCount + objModule.PassCount
m_Scenario.FailCount = m_Scenario.FailCount + objModule.FailCount

Set objModule = Nothing
Next

m_Responder.Respond(m_Scenario)
End Sub

Private Sub RunModule(ByRef objModule)
Dim intTimeStart, _
intTimeEnd, _
objTest, _
i

Set m_CurrentModule = objModule

intTimeStart = Timer
For i = 0 To (objModule.Tests.Count - 1)
Set objTest = objModule.Tests.Item(i)

Call RunTestModuleSetup(objModule)
Call RunModuleTest(objTest)
Call RunTestModuleTeardown(objModule)

If objTest.Passed Then
objModule.PassCount = objModule.PassCount + 1
End If

Set objTest = Nothing
Next
intTimeEnd = Timer

objModule.Duration = Round((intTimeEnd - intTimestart), 3)

Set m_CurrentModule = Nothing
End Sub

Private Sub RunModuleTest(ByRef objTest)
Set m_CurrentTest = objTest

On Error Resume Next
Call GetRef(objTest.Name)()

If Err.Number <> 0 Then
Call Assert(False, Err.Description)
End If

Err.Clear()
On Error Goto 0

Set m_CurrentTest = Nothing
End Sub

Private Sub RunTestModuleSetup(ByRef objModule)
If Not objModule.Lifecycle Is Nothing Then
If Not objModule.Lifecycle.Setup = Empty Then
Call GetRef(objModule.Lifecycle.Setup)()
End If
End If
End Sub

Private Sub RunTestModuleTeardown(ByRef objModule)
If Not objModule.Lifecycle Is Nothing Then
If Not objModule.Lifecycle.Teardown = Empty Then
Call GetRef(objModule.Lifecycle.Teardown)()
End If
End If
End Sub
End Class

' Private Classses

Class ASPUnitScenario
Public _
Modules, _
TestCount, _
PassCount, _
FailCount

Private Sub Class_Initialize()
Set Modules = Server.CreateObject("System.Collections.ArrayList")
PassCount = 0
TestCount = 0
FailCount = 0
End Sub

Private Sub Class_Terminate()
Set Modules = Nothing
End Sub

Public Property Get Passed
Passed = (PassCount = TestCount)
End Property
End Class

Class ASPUnitModule
Public _
Name, _
Tests, _
Lifecycle, _
Duration, _
PassCount

Private Sub Class_Initialize()
Set Tests = Server.CreateObject("System.Collections.ArrayList")
PassCount = 0
End Sub

Private Sub Class_Terminate()
Set Tests = Nothing
End Sub

Public Property Get TestCount
TestCount = Tests.Count()
End Property

Public Property Get FailCount
FailCount = (TestCount - PassCount)
End Property

Public Property Get Passed
Passed = (PassCount = TestCount)
End Property
End Class

Class ASPUnitTest
Public _
Name, _
Passed, _
Description
End Class

Class ASPUnitTestLifecycle
Public _
Setup, _
Teardown
End Class
%>

+ 0
- 395
tests/aspunit/Lib/classes/ASPUnitUIModern.asp View File

@@ -1,395 +0,0 @@
<%
Class ASPUnitUIModern
Public Sub Render(ByRef objRunner) %>
<html>
<head>
<title>ASPUnit</title>

<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet">
<link href='//fonts.googleapis.com/css?family=Open+Sans:400,600,700' rel='stylesheet' type='text/css'>

<style type="text/css">
body {
background-color: #ECF0F1;
padding-top: 280px;
font-family: 'Open Sans', sans-serif;
-webkit-font-smoothing: antialiased;
}

h1, h2, h3, h4, h5, h6 {
font-family: 'Open Sans', sans-serif;
}

a {
color: #95a5a6;
transition: all 0.25s;
}

a:hover {
color: #fff;
text-decoration: none;
}

.project-name {
color: #fff !important;
}

#footer .project-name {
margin-top: 0;
margin-bottom: 0;
}

#container {
position: relative;
height: auto;
min-height: 100%;
}

#header {
color: #ecf0f1;
background-color: #13202c;
transition: all 0.5s;
position: fixed;
left: 0;
right: 0;
top: 0;
z-index: 1000;
text-shadow: 0px 2px 1px #000;
}

#header a {
color: #ecf0f1;
}

#header a:active {
position: relative;
top: 1px;
text-shadow: 0px 1px 1px #000;
}

#header.affix {
padding-top: 0;
padding-bottom: 0.2em;
}

#main {
padding-bottom: 12em;
}

#footer {
position: absolute;
bottom: 0;
width: 100%;
padding-top: 2em;
padding-bottom: 2em;
margin-top: 4em;
color: #95a5a6;
background-color: #13202c;
}

.progress-loading {
box-shadow: 0 2px 6px RGBA(0,0,0,0.25);
border-bottom: 2px #444 solid;
border-radius: 0 0 2px 2px;
}

.pages-overview {
position: relative;
}

.pages-status {
display: inline-block;
}

.pages-options {
display: inline-block;
position: absolute;
right: 0;
}

.page-report .page-overview {
color: #7F8C8D;
}

.page-report .page-overview small {
color: #95A5A6;
}

.page-module {
margin-bottom: 1em;
box-shadow: 0 2px 6px RGBA(0,0,0,0.25);
}

.page-module .page-module-header {
color: #fff;
padding: 1em 2em;
}

.page-module-pass .page-module-header {
background-color: #2ECC71;
border: 1px #27AE60 solid;
}

.page-module-fail .page-module-header {
background-color: #E74C3C;
border: 1px #C0392B solid;
}

.page-module-name {
font-weight: bold;
margin: 0;
}

.page-module-tests {
border-left: 1px #95A5A6 solid;
border-right: 1px #95A5A6 solid;
border-bottom: 3px #95A5A6 solid;
border-radius: 0 0 3px 3px;
}

.page-module-test {
padding: 0.8em 2em;
background-color: #fff;
margin-bottom: 1px;
position: relative;
}

.page-module-test-icon {
position: absolute;
top: 0.5em;
left: -11px;
color: #fff;
width: 22px;
height: 22px;
padding: 3px 4px;
border-radius: 11px;
}

.page-module-test-icon-pass {
box-shadow: 0 3px 0 #27AE60, 0 6px 3px RGBA(0,0,0,0.25);
background-color: #2ECC71;
}

.page-module-test-icon-fail {
box-shadow: 0 3px 0 #C0392B, 0 6px 3px RGBA(0,0,0,0.25);
background-color: #E74C3C;
}

.page-module-test-name {
font-weight: bold;
}

.page-module-test-fail .page-module-test-name, .page-module-test-fail .page-module-test-description {
color: #C0392B;
}

@media (max-width: 768px) {
body {
padding-top: 260px;
}

#main {
padding-bottom: 15em;
}

.pages-options {
display: inline-block;
position: relative;
}
}
</style>
</head>
<body>
<div id="container">
<div id="header" class="jumbotron" data-spy="affix" data-offset-top="10">
<div class="container">
<h1 class="project-name"><strong>ASP</strong>Unit</h1>

<div class="pages-overview">
<div class="pages-status"></div>

<div class="pages-options">
<div class="pages-option-passed-tests">
<a href="#" class="action-hide-passed"><i class="glyphicon glyphicon-remove-sign"></i> Hide Passed Tests</a>
</div>
</div>

<div class="progress progress-striped progress-loading">
<div class="progress-bar progress-bar-success" role="progressbar"></div>
<div class="progress-bar progress-bar-danger" role="progressbar"></div>
</div>

<div class="alert alert-danger progress-error" style="display: none;"></div>
</div>
</div>
</div>

<div id="main">
<div class="page-reports"></div>
</div>

<div id="footer">
<div class="container">
<div class="row">
<div class="col-md-12">
<h3 class="project-name"><strong>ASP</strong>Unit</h3>
</div>
</div>
<div class="row">
<div class="col-md-4">
Classic ASP Unit Testing Library<br />
</div>
<div class="col-md-4">
<ul class="list-unstyled">
<li><a href="https://github.com/rpeterclark/aspunit/"><i class="icon-github"></i> GitHub Project</a></li>
<li><a href="https://github.com/rpeterclark/aspunit/wiki/"><i class="icon-book"></i> Documentation</a></li>
<li><a href="https://github.com/rpeterclark/aspunit/issues/"><i class="icon-bug"></i> Issues</a></li>
</ul>
</div>
<div class="col-md-4">
MIT Licensed
</div>
</div>
</div>
</div>
</div>

<script id="page-status-template" type="text/x-handlebars-template">
{{pageNumber}} of {{pageCount}} pages tested, {{passCount}} of {{testCount}} tests passed
</script>

<script id="page-report-template" type="text/x-handlebars-template">
<div class="page-report container">
<div class="page-overview">
<h3>{{page}} <small>{{passCount}} of {{testCount}} tests passed</small></h3>
</div>
{{#each modules}}
<div class="page-module page-module-{{#if passed}}pass{{else}}fail{{/if}}">
<div class="page-module-header">
<h4 class="page-module-name">{{name}}</h4>
{{passCount}} of {{testCount}} tests passed, {{failCount}} failed, completed in {{duration}} milliseconds
</div>

<div class="page-module-tests">
{{#each tests}}
<div class="page-module-test page-module-test-{{#if passed}}pass{{else}}fail{{/if}}">
{{#if passed}}
<i class="page-module-test-icon page-module-test-icon-pass glyphicon glyphicon-ok"></i>
{{else}}
<i class="page-module-test-icon page-module-test-icon-fail glyphicon glyphicon-remove"></i>
{{/if}}
<span class="page-module-test-name">{{name}}:</span>
<span class="page-module-test-description">{{description}}</span>
</div>
{{/each}}
</div>
</div>
{{/each}}
</div>
</script>

<script id="page-error-template" type="text/x-handlebars-template">
<div class="page-report container">
<div class="page-module page-module-fail">
<div class="page-module-header">
<h4 class="page-module-name">{{page}}</h4>
</div>

<div class="page-module-tests">
<div class="page-module-test page-module-test-fail">
<i class="page-module-test-icon page-module-test-icon-fail glyphicon glyphicon-remove"></i>
<span class="page-module-test-name">{{error}}{{#if description}}:{{/if}}</span>
<span class="page-module-test-description">{{description}}</span>
</div>
</div>
</div>
</div>
</div>
</script>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/js/bootstrap.min.js"></script>

<%= objRunner.RenderJSLib() %>

<script>
$(function() {
var successCount = 0;
var pageReportsContainer = $('.page-reports');
var pageReportTemplate = Handlebars.compile($('#page-report-template').html());
var pageErrorTemplate = Handlebars.compile($('#page-error-template').html());
var pageStatusContainer = $('.pages-status');
var pageStatusTemplate = Handlebars.compile($('#page-status-template').html());
var pageReportsProgress = $('.progress-loading');
var progressError = $('.progress-error');

ASPUnit.onStart(function() {
pageReportsProgress.addClass('active');
});

ASPUnit.onPageSuccess(function(details) {
successCount++;
$(pageReportTemplate(details)).appendTo(pageReportsContainer).hide().fadeIn();
});

ASPUnit.onPageFail(function(details) {
$(pageErrorTemplate(details)).appendTo(pageReportsContainer);
});

ASPUnit.onPageFinish(function(details) {
var status = $.extend(details.status, {pageNumber: (details.status.pageIndex + 1)});

pageStatusContainer.html(pageStatusTemplate(status));

var progressPct = (status.pageNumber / status.pageCount);
var passPct = (status.passCount / status.testCount) * (successCount / status.pageNumber);
var failPct = (1 - passPct);

pageReportsProgress.find('.progress-bar-success').css({"width": ((passPct * 100) * progressPct) + "%"})
pageReportsProgress.find('.progress-bar-danger').css({"width": ((failPct * 100) * progressPct) + "%"})
});

ASPUnit.onFinish(function() {
pageReportsProgress.removeClass('active');
});

$(document).on('click', '.action-hide-passed', function(e) {
e.preventDefault();

var $el = $(e.target);

if ($el.hasClass('active')) {
$el.removeClass('active').html('<i class="glyphicon glyphicon-remove-sign"></i> Hide Passed Tests</a>');
showPassedTests();
} else {
$el.addClass('active').html('<i class="glyphicon glyphicon-ok-sign"></i> Show Passed Tests</a>');
hidePassedTests();
}
});

function hidePassedTests() {
$('.page-report').each(function() {
if ($(this).find('.page-module-test-fail').length > 0) {
$(this).find('.page-module-pass').addClass('hidden');
$(this).find('.page-module-test-pass').addClass('hidden');
} else {
$(this).addClass('hidden');
}
});
}

function showPassedTests() {
$('.hidden').removeClass('hidden');
}
});
</script>

<%= objRunner.RenderJSInit() %>
</body>
</html> <%
End Sub
End Class
%>

+ 0
- 49
tests/bootstrap.asp View File

@@ -1,49 +0,0 @@
<!-- #include file="../core/helpers.asp" -->
<!-- #include file="../core/lib.ControllerRegistry.asp" -->

<%
Dim router

Function ResolveProjectPath(relativePath)
Dim fso, currentFolder, testsRoot, projectRoot

Set fso = Server.CreateObject("Scripting.FileSystemObject")
currentFolder = Server.MapPath(".")

If LCase(fso.GetFileName(currentFolder)) = "tests" Then
testsRoot = currentFolder
Else
testsRoot = fso.GetParentFolderName(currentFolder)
End If

projectRoot = fso.GetParentFolderName(testsRoot)
ResolveProjectPath = fso.BuildPath(projectRoot, relativePath)

Set fso = Nothing
End Function

Sub ResetTestRuntime()
On Error Resume Next
ControllerRegistry_Class__Singleton = Empty
Set router = Nothing
On Error GoTo 0
End Sub

Sub EnsureTestRouter()
If (Not IsObject(router)) Then
Set router = GetObject("script:" & ResolveProjectPath("core\\router.wsc"))
ElseIf router Is Nothing Then
Set router = GetObject("script:" & ResolveProjectPath("core\\router.wsc"))
End If
End Sub

Sub RegisterDefaultRoutes()
Call EnsureTestRouter()
Call router.AddRoute("GET", "/home", "homeController", "Index")
Call router.AddRoute("GET", "/", "homeController", "Index")
Call router.AddRoute("GET", "", "homeController", "Index")
Call router.AddRoute("GET", "/404", "ErrorController", "NotFound")
End Sub

Call ResetTestRuntime()
%>

+ 0
- 43
tests/component/TestHomeController.asp View File

@@ -1,43 +0,0 @@
<!-- #include file="../aspunit/Lib/ASPUnit.asp" -->
<!-- #include file="../bootstrap.asp" -->
<!-- #include file="../../app/controllers/HomeController.asp" -->

<%
Call ASPUnit.AddModule( _
ASPUnit.CreateModule( _
"Home Controller Component Tests", _
Array( _
ASPUnit.CreateTest("HomeControllerDefaultsToUsingLayout"), _
ASPUnit.CreateTest("HomeControllerDefaultTitleIsHome") _
), _
ASPUnit.CreateLifeCycle("SetupHomeController", "TeardownHomeController") _
) _
)

Call ASPUnit.Run()

Sub SetupHomeController()
Call ResetTestRuntime()
On Error Resume Next
HomeController_Class__Singleton = Empty
On Error GoTo 0
Call ExecuteGlobal("Dim objHomeController")
Set objHomeController = HomeController()
End Sub

Sub TeardownHomeController()
Set objHomeController = Nothing
On Error Resume Next
HomeController_Class__Singleton = Empty
On Error GoTo 0
Call ResetTestRuntime()
End Sub

Function HomeControllerDefaultsToUsingLayout()
Call ASPUnit.Ok(objHomeController.useLayout, "HomeController should default to layout-enabled rendering")
End Function

Function HomeControllerDefaultTitleIsHome()
Call ASPUnit.Equal(objHomeController.Title, "Home", "HomeController should expose the expected default title")
End Function
%>

+ 0
- 20
tests/component/web.config View File

@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="Environment" value="Development" />
<add key="Error404RedirectSeconds" value="5" />
<add key="CacheExpirationYear" value="2030" />
<add key="EnableCacheBusting" value="false" />
<add key="CacheBustParamName" value="v" />
<add key="ProductionAppBaseUrl" value="http://localhost:8081/" />
</appSettings>

<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="run-all.asp" />
</files>
</defaultDocument>
</system.webServer>
</configuration>

+ 0
- 41
tests/integration/TestConfigSettings.asp View File

@@ -1,41 +0,0 @@
<!-- #include file="../aspunit/Lib/ASPUnit.asp" -->
<!-- #include file="../bootstrap.asp" -->

<%
Call ASPUnit.AddModule( _
ASPUnit.CreateModule( _
"Config Integration Tests", _
Array( _
ASPUnit.CreateTest("NestedTestPageReadsMirroredConfigValue"), _
ASPUnit.CreateTest("MissingConfigKeyReturnsNothingSentinel"), _
ASPUnit.CreateTest("ProductionAppBaseUrlSupportsBlankOrConfiguredValue") _
), _
ASPUnit.CreateLifeCycle("SetupConfigIntegration", "TeardownConfigIntegration") _
) _
)

Call ASPUnit.Run()

Sub SetupConfigIntegration()
Call ResetTestRuntime()
End Sub

Sub TeardownConfigIntegration()
Call ResetTestRuntime()
End Sub

Function NestedTestPageReadsMirroredConfigValue()
Call ASPUnit.Equal(GetAppSetting("Error404RedirectSeconds"), "5", "Nested integration pages should read mirrored config values from their local web.config")
End Function

Function MissingConfigKeyReturnsNothingSentinel()
Call ASPUnit.Equal(GetAppSetting("DefinitelyMissingSetting"), "nothing", "Missing config keys should return the existing nothing sentinel")
End Function

Function ProductionAppBaseUrlSupportsBlankOrConfiguredValue()
Dim configuredUrl
configuredUrl = GetAppSetting("ProductionAppBaseUrl")

Call ASPUnit.Ok((configuredUrl = "" Or configuredUrl = "nothing" Or InStr(configuredUrl, "http://") = 1 Or InStr(configuredUrl, "https://") = 1), "ProductionAppBaseUrl should be either blank for host fallback or an explicit absolute URL")
End Function
%>

+ 0
- 80
tests/integration/TestMvcDispatch.asp View File

@@ -1,80 +0,0 @@
<!-- #include file="../aspunit/Lib/ASPUnit.asp" -->
<!-- #include file="../bootstrap.asp" -->
<!-- #include file="../../core/mvc.asp" -->

<%
Class TestDispatchController_Class
Private m_useLayout

Private Sub Class_Initialize()
m_useLayout = False
End Sub

Public Property Get useLayout
useLayout = m_useLayout
End Property

Public Property Let useLayout(value)
m_useLayout = value
End Property

Public Sub Smoke()
dispatchActionRan = True
End Sub
End Class

Dim TestDispatchController_Class__Singleton
Function TestDispatchController()
If IsEmpty(TestDispatchController_Class__Singleton) Then
Set TestDispatchController_Class__Singleton = New TestDispatchController_Class
End If
Set TestDispatchController = TestDispatchController_Class__Singleton
End Function

Call ASPUnit.AddModule( _
ASPUnit.CreateModule( _
"MVC Dispatch Smoke Tests", _
Array( _
ASPUnit.CreateTest("RootRouteResolvesToHomeController"), _
ASPUnit.CreateTest("KnownRouteDispatchCompletesWithoutLookupFailure") _
), _
ASPUnit.CreateLifeCycle("SetupMvcDispatch", "TeardownMvcDispatch") _
) _
)

Call ASPUnit.Run()

Sub SetupMvcDispatch()
Call ResetTestRuntime()
On Error Resume Next
MVC_Dispatcher_Class__Singleton = Empty
TestDispatchController_Class__Singleton = Empty
On Error GoTo 0
Call ExecuteGlobal("Dim dispatchActionRan")
dispatchActionRan = False
Call RegisterDefaultRoutes()
Call ControllerRegistry().RegisterController("testdispatchcontroller")
Call router.AddRoute("GET", "/dispatch-smoke", "testdispatchcontroller", "Smoke")
End Sub

Sub TeardownMvcDispatch()
On Error Resume Next
MVC_Dispatcher_Class__Singleton = Empty
TestDispatchController_Class__Singleton = Empty
Response.Status = "200 OK"
On Error GoTo 0
Call ResetTestRuntime()
End Sub

Function RootRouteResolvesToHomeController()
Dim routeArray
routeArray = router.Resolve("GET", "/")

Call ASPUnit.Ok((LCase(routeArray(0)) = "homecontroller" And LCase(routeArray(1)) = "index"), "Root route should resolve to HomeController.Index")
End Function

Function KnownRouteDispatchCompletesWithoutLookupFailure()
Call MVC().DispatchRequest("GET", "/dispatch-smoke")
Call ASPUnit.Ok(dispatchActionRan, "Dispatch should reach a registered controller action without whitelist or lookup failures")
End Function
%>

+ 0
- 52
tests/integration/TestRenderedOutput.asp View File

@@ -1,52 +0,0 @@
<!-- #include file="../aspunit/Lib/ASPUnit.asp" -->
<!-- #include file="../bootstrap.asp" -->
<!-- #include file="../support/HttpCaptureHelpers.asp" -->

<%
Call ASPUnit.AddModule( _
ASPUnit.CreateModule( _
"Rendered Output Capture Tests", _
Array( _
ASPUnit.CreateTest("HomePageReturnsWelcomeMarkup"), _
ASPUnit.CreateTest("NotFoundPageReturns404Markup") _
), _
ASPUnit.CreateLifeCycle("SetupRenderedOutput", "TeardownRenderedOutput") _
) _
)

Call ASPUnit.Run()

Sub SetupRenderedOutput()
Call ResetTestRuntime()
End Sub

Sub TeardownRenderedOutput()
Call ResetTestRuntime()
End Sub

Function HomePageReturnsWelcomeMarkup()
Dim responseData
Dim bodyContains, message
Set responseData = FetchPage("/")

bodyContains = (InStr(responseData.Item("body"), "Welcome to RouteKit Classic ASP") > 0)
message = "Home page request should return welcome markup. URL=" & responseData.Item("url") & "; Status=" & responseData.Item("status") & "; Snippet=" & Left(CStr(responseData.Item("body")), 160)

Call ASPUnit.Ok((responseData.Item("status") = 200 And bodyContains), message)

Set responseData = Nothing
End Function

Function NotFoundPageReturns404Markup()
Dim responseData
Dim bodyContains, message
Set responseData = FetchPage("/404")

bodyContains = (InStr(responseData.Item("body"), "404 - Page Not Found") > 0)
message = "404 request should return not-found markup. URL=" & responseData.Item("url") & "; Status=" & responseData.Item("status") & "; Snippet=" & Left(CStr(responseData.Item("body")), 160)

Call ASPUnit.Ok((responseData.Item("status") = 404 And bodyContains), message)

Set responseData = Nothing
End Function
%>

+ 0
- 51
tests/integration/TestRoutes.asp View File

@@ -1,51 +0,0 @@
<!-- #include file="../aspunit/Lib/ASPUnit.asp" -->
<!-- #include file="../bootstrap.asp" -->
<!-- #include file="../../core/lib.Routes.asp" -->

<%
Call ASPUnit.AddModule( _
ASPUnit.CreateModule( _
"Route Helper Integration Tests", _
Array( _
ASPUnit.CreateTest("RouteHelperReadsCacheBustingSettingFromConfig"), _
ASPUnit.CreateTest("UrlToBuildsLowercaseControllerActionPath"), _
ASPUnit.CreateTest("AssetUrlCanOverrideCacheBustingPerCall") _
), _
ASPUnit.CreateLifeCycle("SetupRouteHelper", "TeardownRouteHelper") _
) _
)

Call ASPUnit.Run()

Sub SetupRouteHelper()
Call ResetTestRuntime()
On Error Resume Next
Set Route_Helper__Singleton = Nothing
On Error GoTo 0
End Sub

Sub TeardownRouteHelper()
On Error Resume Next
Set Route_Helper__Singleton = Nothing
On Error GoTo 0
Call ResetTestRuntime()
End Sub

Function RouteHelperReadsCacheBustingSettingFromConfig()
Call ASPUnit.Ok((Not Routes().CacheBustingEnabled), "Routes helper should read disabled cache-busting from tests/web.config")
End Function

Function UrlToBuildsLowercaseControllerActionPath()
Dim url
url = Routes().UrlTo("HomeController", "Index", Array("id", "7"))

Call ASPUnit.Ok((InStr(LCase(url), "/homecontroller/index?id=7") > 0), "UrlTo should build a lowercase controller/action path with query parameters")
End Function

Function AssetUrlCanOverrideCacheBustingPerCall()
Dim url
url = Routes().AssetUrl("css/site.css", True)

Call ASPUnit.Ok((InStr(url, "css/site.css?v=") > 0), "AssetUrl should append the configured cache-bust parameter when override is true")
End Function
%>

+ 0
- 69
tests/integration/TestSharedLayout.asp View File

@@ -1,69 +0,0 @@
<!-- #include file="../aspunit/Lib/ASPUnit.asp" -->
<!-- #include file="../bootstrap.asp" -->
<!-- #include file="../support/HttpCaptureHelpers.asp" -->

<%
Call ASPUnit.AddModule( _
ASPUnit.CreateModule( _
"Shared Layout Render Tests", _
Array( _
ASPUnit.CreateTest("HomePageIncludesSharedHeaderAssets"), _
ASPUnit.CreateTest("HomePageUsesControllerTitleInLayout"), _
ASPUnit.CreateTest("NotFoundPageStillIncludesSharedLayoutChrome") _
), _
ASPUnit.CreateLifeCycle("SetupSharedLayout", "TeardownSharedLayout") _
) _
)

Call ASPUnit.Run()

Sub SetupSharedLayout()
Call ResetTestRuntime()
End Sub

Sub TeardownSharedLayout()
Call ResetTestRuntime()
End Sub

Function HomePageIncludesSharedHeaderAssets()
Dim responseData
Dim body

Set responseData = FetchPage("/")
body = responseData.Item("body")

Call ASPUnit.Ok((responseData.Item("status") = 200 And _
InStr(body, "navbar-brand rk-navbar-brand") > 0 And _
InStr(body, "/css/site.css") > 0 And _
InStr(body, "bootstrap.bundle.min.js") > 0), _
"Home page should include shared header and footer assets from the layout")

Set responseData = Nothing
End Function

Function HomePageUsesControllerTitleInLayout()
Dim responseData
Set responseData = FetchPage("/")

Call ASPUnit.Ok((InStr(LCase(responseData.Item("body")), "<title>home</title>") > 0), _
"Home page layout should render the controller title in the <title> tag")

Set responseData = Nothing
End Function

Function NotFoundPageStillIncludesSharedLayoutChrome()
Dim responseData
Dim body

Set responseData = FetchPage("/404")
body = responseData.Item("body")

Call ASPUnit.Ok((responseData.Item("status") = 404 And _
InStr(body, "404 - Page Not Found") > 0 And _
InStr(body, "navbar-brand rk-navbar-brand") > 0 And _
InStr(body, "bootstrap.bundle.min.js") > 0), _
"404 page should still render inside the shared layout chrome")

Set responseData = Nothing
End Function
%>

+ 0
- 20
tests/integration/web.config View File

@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="Environment" value="Development" />
<add key="Error404RedirectSeconds" value="5" />
<add key="CacheExpirationYear" value="2030" />
<add key="EnableCacheBusting" value="false" />
<add key="CacheBustParamName" value="v" />
<add key="ProductionAppBaseUrl" value="http://localhost:8081/" />
</appSettings>

<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="run-all.asp" />
</files>
</defaultDocument>
</system.webServer>
</configuration>

+ 0
- 9
tests/run-all.asp View File

@@ -1,9 +0,0 @@
<!-- #include file="aspunit/Lib/ASPUnit.asp" -->
<!-- #include file="PlainRunnerTheme.asp" -->
<!-- #include file="test-manifest.asp" -->

<%
Set ASPUnit.Theme = New PlainRunnerTheme
Call RegisterTestPages()
Call ASPUnit.Run()
%>

+ 0
- 21
tests/run-tests.cmd View File

@@ -1,21 +0,0 @@
@echo off
setlocal

set "SCRIPT_DIR=%~dp0"
set "RUNNER_URL=%~1"

if "%RUNNER_URL%"=="" set "RUNNER_URL=http://localhost/tests-dev/run-all.asp"

echo Syncing mirrored test web.config files...
cscript //nologo "%SCRIPT_DIR%sync-webconfigs.vbs"
if errorlevel 1 (
echo Failed to sync mirrored test web.config files.
exit /b 1
)

echo Opening test runner: %RUNNER_URL%
start "" "%RUNNER_URL%"

echo.
echo If your tests app is served from a different URL, pass it as the first argument:
echo tests\run-tests.cmd http://localhost:8085/run-all.asp

+ 0
- 48
tests/support/HttpCaptureHelpers.asp View File

@@ -1,48 +0,0 @@
<%
Function BuildRequestOrigin()
Dim protocol

protocol = "http://"
If LCase(Request.ServerVariables("HTTPS")) = "on" Then
protocol = "https://"
End If

BuildRequestOrigin = protocol & Request.ServerVariables("HTTP_HOST")
End Function

Function GetProductionBaseUrl()
Dim configuredUrl

configuredUrl = GetAppSetting("ProductionAppBaseUrl")
If configuredUrl = "nothing" Or Len(Trim(configuredUrl)) = 0 Then
GetProductionBaseUrl = BuildRequestOrigin() & "/"
Else
If Right(configuredUrl, 1) <> "/" Then
configuredUrl = configuredUrl & "/"
End If
GetProductionBaseUrl = configuredUrl
End If
End Function

Function FetchPage(path)
Dim http, result, targetUrl

targetUrl = GetProductionBaseUrl()
If Left(path, 1) = "/" Then
path = Mid(path, 2)
End If
targetUrl = targetUrl & path

Set http = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
http.Open "GET", targetUrl, False
http.Send

Set result = Server.CreateObject("Scripting.Dictionary")
result.Add "url", targetUrl
result.Add "status", http.Status
result.Add "body", http.responseText

Set FetchPage = result
Set http = Nothing
End Function
%>

+ 0
- 25
tests/sync-webconfigs.vbs View File

@@ -1,25 +0,0 @@
Option Explicit

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

Dim testsRoot
testsRoot = fso.GetParentFolderName(WScript.ScriptFullName)

Dim sourceFile
sourceFile = fso.BuildPath(testsRoot, "web.config")

If Not fso.FileExists(sourceFile) Then
WScript.Echo "Source config not found: " & sourceFile
WScript.Quit 1
End If

Call CopyConfig(sourceFile, fso.BuildPath(fso.BuildPath(testsRoot, "unit"), "web.config"))
Call CopyConfig(sourceFile, fso.BuildPath(fso.BuildPath(testsRoot, "component"), "web.config"))
Call CopyConfig(sourceFile, fso.BuildPath(fso.BuildPath(testsRoot, "integration"), "web.config"))

WScript.Echo "Mirrored test web.config files updated."

Sub CopyConfig(sourcePath, targetPath)
Call fso.CopyFile(sourcePath, targetPath, True)
End Sub

+ 0
- 14
tests/test-manifest.asp View File

@@ -1,14 +0,0 @@
<%
Sub RegisterTestPages()
Call ASPUnit.AddPages(Array( _
"unit/TestHelpers.asp", _
"unit/TestControllerRegistry.asp", _
"component/TestHomeController.asp", _
"integration/TestMvcDispatch.asp", _
"integration/TestRoutes.asp", _
"integration/TestConfigSettings.asp", _
"integration/TestRenderedOutput.asp", _
"integration/TestSharedLayout.asp" _
))
End Sub
%>

+ 0
- 48
tests/unit/TestControllerRegistry.asp View File

@@ -1,48 +0,0 @@
<!-- #include file="../aspunit/Lib/ASPUnit.asp" -->
<!-- #include file="../bootstrap.asp" -->

<%
Call ASPUnit.AddModule( _
ASPUnit.CreateModule( _
"Controller Registry Tests", _
Array( _
ASPUnit.CreateTest("RegisteredHomeControllerIsValid"), _
ASPUnit.CreateTest("RegisteredErrorControllerIsValid"), _
ASPUnit.CreateTest("InvalidControllerFormatIsRejected"), _
ASPUnit.CreateTest("InvalidActionFormatIsRejected"), _
ASPUnit.CreateTest("UnknownControllerIsRejected") _
), _
ASPUnit.CreateLifeCycle("SetupControllerRegistry", "TeardownControllerRegistry") _
) _
)

Call ASPUnit.Run()

Sub SetupControllerRegistry()
Call ResetTestRuntime()
End Sub

Sub TeardownControllerRegistry()
Call ResetTestRuntime()
End Sub

Function RegisteredHomeControllerIsValid()
Call ASPUnit.Ok(ControllerRegistry().IsValidController("homecontroller"), "HomeController should be present in the whitelist")
End Function

Function RegisteredErrorControllerIsValid()
Call ASPUnit.Ok(ControllerRegistry().IsValidController("errorcontroller"), "ErrorController should be present in the whitelist")
End Function

Function InvalidControllerFormatIsRejected()
Call ASPUnit.Ok((Not ControllerRegistry().IsValidControllerFormat("home-controller")), "Controller names with dashes should be rejected")
End Function

Function InvalidActionFormatIsRejected()
Call ASPUnit.Ok((Not ControllerRegistry().IsValidActionFormat("show-item")), "Action names with dashes should be rejected")
End Function

Function UnknownControllerIsRejected()
Call ASPUnit.Ok((Not ControllerRegistry().IsValidController("missingcontroller")), "Unknown controllers should not pass whitelist checks")
End Function
%>

+ 0
- 65
tests/unit/TestHelpers.asp View File

@@ -1,65 +0,0 @@
<!-- #include file="../aspunit/Lib/ASPUnit.asp" -->
<!-- #include file="../bootstrap.asp" -->

<%
Call ASPUnit.AddModule( _
ASPUnit.CreateModule( _
"Helper Function Tests", _
Array( _
ASPUnit.CreateTest("TrimQueryParamsStripsQuestionString"), _
ASPUnit.CreateTest("TrimQueryParamsStripsAmpersandSuffix"), _
ASPUnit.CreateTest("TrimQueryParamsLeavesPathWithoutDelimiters"), _
ASPUnit.CreateTest("SurroundStringInArrayWrapsStringValues"), _
ASPUnit.CreateTest("SurroundStringInArrayLeavesNumericValuesUntouched"), _
ASPUnit.CreateTest("SurroundStringInArrayLeavesArraysWithoutStringsUntouched") _
), _
ASPUnit.CreateLifeCycle("SetupHelpers", "TeardownHelpers") _
) _
)

Call ASPUnit.Run()

Sub SetupHelpers()
Call ResetTestRuntime()
End Sub

Sub TeardownHelpers()
Call ResetTestRuntime()
End Sub

Function TrimQueryParamsStripsQuestionString()
Call ASPUnit.Equal(TrimQueryParams("/home?id=7"), "/home", "TrimQueryParams should remove query string values after ?")
End Function

Function TrimQueryParamsStripsAmpersandSuffix()
Call ASPUnit.Equal(TrimQueryParams("/home&debug=true"), "/home", "TrimQueryParams should remove suffix values after &")
End Function

Function TrimQueryParamsLeavesPathWithoutDelimiters()
Call ASPUnit.Equal(TrimQueryParams("/home"), "/home", "TrimQueryParams should leave clean paths unchanged")
End Function

Function SurroundStringInArrayWrapsStringValues()
Dim arr
arr = Array("alpha", 2)
arr = SurroundStringInArray(arr)

Call ASPUnit.Equal(arr(0), """alpha""", "SurroundStringInArray should wrap string items in double quotes")
End Function

Function SurroundStringInArrayLeavesNumericValuesUntouched()
Dim arr
arr = Array("alpha", 2)
arr = SurroundStringInArray(arr)

Call ASPUnit.Equal(arr(1), 2, "SurroundStringInArray should leave non-string items unchanged")
End Function

Function SurroundStringInArrayLeavesArraysWithoutStringsUntouched()
Dim arr
arr = Array(1, 2)
arr = SurroundStringInArray(arr)

Call ASPUnit.Ok((arr(0) = 1 And arr(1) = 2), "SurroundStringInArray should leave arrays without string members unchanged")
End Function
%>

+ 0
- 20
tests/unit/web.config View File

@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="Environment" value="Development" />
<add key="Error404RedirectSeconds" value="5" />
<add key="CacheExpirationYear" value="2030" />
<add key="EnableCacheBusting" value="false" />
<add key="CacheBustParamName" value="v" />
<add key="ProductionAppBaseUrl" value="http://localhost:8081/" />
</appSettings>

<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="run-all.asp" />
</files>
</defaultDocument>
</system.webServer>
</configuration>

+ 0
- 20
tests/web.config View File

@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="Environment" value="Development" />
<add key="Error404RedirectSeconds" value="5" />
<add key="CacheExpirationYear" value="2030" />
<add key="EnableCacheBusting" value="false" />
<add key="CacheBustParamName" value="v" />
<add key="ProductionAppBaseUrl" value="http://localhost:8081/" />
</appSettings>

<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="run-all.asp" />
</files>
</defaultDocument>
</system.webServer>
</configuration>

Loading…
Cancel
Save

Powered by TurnKey Linux.