diff --git a/.gitignore b/.gitignore index 5226c14..9f6c746 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ /_bmad /_bmad* /.agents -/.github \ No newline at end of file +/.github +# SQLite database (created by the first migration run; never commit data) +/db/*.sqlite +/db/*.sqlite-* diff --git a/README.md b/README.md index 9f06761..3c79b77 100644 --- a/README.md +++ b/README.md @@ -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/ Controller.asp (HTML), ApiController.asp (JSON), autoload_controllers.asp + models/ POBO_.asp,
Repository.asp (generated), autoload_models.asp + views/ / 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. diff --git a/TESTING.md b/TESTING.md deleted file mode 100644 index bb217cc..0000000 --- a/TESTING.md +++ /dev/null @@ -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. diff --git a/app/controllers/DocsController.asp b/app/controllers/DocsController.asp new file mode 100644 index 0000000..a76bf64 --- /dev/null +++ b/app/controllers/DocsController.asp @@ -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() +%> + +<% + 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 +%> diff --git a/app/controllers/ErrorController.asp b/app/controllers/ErrorController.asp index 12cb8a9..d071fb6 100644 --- a/app/controllers/ErrorController.asp +++ b/app/controllers/ErrorController.asp @@ -21,7 +21,7 @@ Class ErrorController_Class Public Sub NotFound() Response.Status = "404 Not Found" %> - + <% End Sub diff --git a/app/controllers/autoload_controllers.asp b/app/controllers/autoload_controllers.asp index 425e8a9..76b3c7d 100644 --- a/app/controllers/autoload_controllers.asp +++ b/app/controllers/autoload_controllers.asp @@ -1,2 +1,3 @@ - \ No newline at end of file + + diff --git a/app/models/autoload_models.asp b/app/models/autoload_models.asp new file mode 100644 index 0000000..80c56a2 --- /dev/null +++ b/app/models/autoload_models.asp @@ -0,0 +1 @@ +<% ' POBO and repository includes are appended here by scripts/gen.cmd (repo | api) %> diff --git a/app/views/Docs/index.asp b/app/views/Docs/index.asp new file mode 100644 index 0000000..e4e2627 --- /dev/null +++ b/app/views/Docs/index.asp @@ -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 %> +
+ No API specs yet. Generate one for a table with scripts\gen.cmd api /table:<Table> /pk:Id + (it writes public/api/<table>.openapi.json), then reload this page. +
+<% Else %> + +
+ + + +<% End If %> diff --git a/app/views/shared/header.asp b/app/views/shared/header.asp index 03fce57..dc98193 100644 --- a/app/views/shared/header.asp +++ b/app/views/shared/header.asp @@ -63,15 +63,13 @@ If Len(pageTitle) = 0 Then pageTitle = "Classic ASP Starter Template" + - ' Right-side area (e.g., user info / login) - ' You can wire this up to your auth later. - + <%' Right-side area (e.g., user info / login). Wire this up to your auth later. %> + diff --git a/applicationhost.config b/applicationhost.config deleted file mode 100644 index 8d6b56d..0000000 --- a/applicationhost.config +++ /dev/null @@ -1,1030 +0,0 @@ - - - - - - - - -
-
-
-
-
-
-
-
- - - -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
- -
-
-
-
-
-
- -
-
-
-
-
- -
-
-
- -
-
- -
-
- -
-
-
- - -
-
-
-
-
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/core/autoload_core.asp b/core/autoload_core.asp index 6b406b8..220a9b1 100644 --- a/core/autoload_core.asp +++ b/core/autoload_core.asp @@ -1,23 +1,19 @@ - - - - - - - -<% Dim router : Set router = GetObject("script:"& Server.MapPath("../Core/router.wsc") & "") %> - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + diff --git a/core/databaseConnection.asp b/core/databaseConnection.asp deleted file mode 100644 index 7d5e297..0000000 --- a/core/databaseConnection.asp +++ /dev/null @@ -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 -%> diff --git a/core/helpers.asp b/core/helpers.asp index ca87a1e..32d242e 100644 --- a/core/helpers.asp +++ b/core/helpers.asp @@ -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 "
" +Sub puts_ + puts "
" 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 = "" diff --git a/core/lib.CDOEmail.asp b/core/lib.CDOEmail.asp deleted file mode 100644 index e55a55f..0000000 --- a/core/lib.CDOEmail.asp +++ /dev/null @@ -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 & "
" - 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 - -%> diff --git a/core/lib.Collections.asp b/core/lib.Collections.asp index 60ad607..1db82fc 100644 --- a/core/lib.Collections.asp +++ b/core/lib.Collections.asp @@ -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 & "
" + puts key & " => " & val & "
" 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 diff --git a/core/lib.ControllerRegistry.asp b/core/lib.ControllerRegistry.asp index 0b563d8..cd86a92 100644 --- a/core/lib.ControllerRegistry.asp +++ b/core/lib.ControllerRegistry.asp @@ -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() diff --git a/core/lib.Data.asp b/core/lib.Data.asp index 4750c85..bec5d8f 100644 --- a/core/lib.Data.asp +++ b/core/lib.Data.asp @@ -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: ":", 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 ':' (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 -%> \ No newline at end of file + + 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 +%> diff --git a/core/lib.Flash.asp b/core/lib.Flash.asp index fbd1968..661cc4e 100644 --- a/core/lib.Flash.asp +++ b/core/lib.Flash.asp @@ -63,9 +63,9 @@ Class Flash_Class dim ary, i ary = Errors for i = 0 to ubound(ary) - put "
  • " - put H(ary(i)) - put "
  • " + puts "
  • " + puts H(ary(i)) + puts "
  • " next %> diff --git a/core/lib.HTML.Security.asp b/core/lib.HTML.Security.asp index 871ae90..1c74ce6 100644 --- a/core/lib.HTML.Security.asp +++ b/core/lib.HTML.Security.asp @@ -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 '--------------------------------------------------------------------------------------------------------------------- diff --git a/core/lib.JsonLite.asp b/core/lib.JsonLite.asp new file mode 100644 index 0000000..9ebd631 --- /dev/null +++ b/core/lib.JsonLite.asp @@ -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 +%> diff --git a/core/lib.Migrations.asp b/core/lib.Migrations.asp index 8f92694..75c1697 100644 --- a/core/lib.Migrations.asp +++ b/core/lib.Migrations.asp @@ -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 diff --git a/core/lib.Router.asp b/core/lib.Router.asp new file mode 100644 index 0000000..93e9ec6 --- /dev/null +++ b/core/lib.Router.asp @@ -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() +%> diff --git a/core/lib.Upload.asp b/core/lib.Upload.asp deleted file mode 100644 index 7cf583c..0000000 --- a/core/lib.Upload.asp +++ /dev/null @@ -1,405 +0,0 @@ - - - -<% -' 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:
    " - aKeys = FormElements.Keys - For i = 0 To FormElements.Count -1 ' Iterate the array - response.write aKeys(i) & " = " & FormElements.Item(aKeys(i)) & "
    " - Next - response.write "Uploaded Files:
    " - For Each f In UploadedFiles.Items - response.write "Name: " & f.FileName & "
    " - response.write "Type: " & f.ContentType & "
    " - response.write "Start: " & f.Start & "
    " - response.write "Size: " & f.Length & "
    " - 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 "

    System reported this error:

    " - response.write Err.Description & "

    " - response.write "The most likely cause for this error is the incorrect setup of AspMaxRequestEntityAllowed in IIS MetaBase. Please see instructions in the requirements page of freeaspupload.net.

    " - 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 requirements page of freeaspupload.net.

    " - 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 -%> \ No newline at end of file diff --git a/core/lib.ad.auth.asp b/core/lib.ad.auth.asp deleted file mode 100644 index edb615c..0000000 --- a/core/lib.ad.auth.asp +++ /dev/null @@ -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 -%> diff --git a/core/lib.crypto.helper.asp b/core/lib.crypto.helper.asp index e6bdd54..3e3787d 100644 --- a/core/lib.crypto.helper.asp +++ b/core/lib.crypto.helper.asp @@ -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 -%> \ No newline at end of file +%> diff --git a/core/lib.json.asp b/core/lib.json.asp deleted file mode 100644 index 38bef36..0000000 --- a/core/lib.json.asp +++ /dev/null @@ -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 - - - -%> \ No newline at end of file diff --git a/core/mvc.asp b/core/mvc.asp index 0bbf373..a770538 100644 --- a/core/mvc.asp +++ b/core/mvc.asp @@ -1,4 +1,5 @@ - + + <% ' 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 - %> <% + %> <% End If ' Prepare parameters @@ -82,7 +83,7 @@ Class MVC_Dispatcher_Class ' Include footer if layout is used If eval(controllerName & ".useLayout") Then - %> <% + %> <% End If On Error GoTo 0 End Sub diff --git a/db/migrations/.gitkeep b/db/migrations/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/db/migrations/20260324110000_add_do_not_call_fields_to_households.asp b/db/migrations/20260324110000_add_do_not_call_fields_to_households.asp deleted file mode 100644 index f187469..0000000 --- a/db/migrations/20260324110000_add_do_not_call_fields_to_households.asp +++ /dev/null @@ -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 -%> diff --git a/db/webdata.accdb b/db/webdata.accdb deleted file mode 100644 index b24c06f..0000000 Binary files a/db/webdata.accdb and /dev/null differ diff --git a/docs/AGENTS.md b/docs/AGENTS.md deleted file mode 100644 index ae946db..0000000 --- a/docs/AGENTS.md +++ /dev/null @@ -1,1543 +0,0 @@ -# AGENTS.md - -## Purpose - -This file defines the development rules, architecture standards, safety requirements, and agent behavior for this project. - -All AI coding agents working in this repository must read this file before making changes. - -The primary development environment is: - -- ASP Classic -- VBScript -- ADODB -- IIS -- HTML/CSS/JavaScript -- SQL Server, Microsoft Access, SQLite, or another configured database - -VBScript provides limited compile-time validation, weak typing, limited object-oriented features, and minimal runtime safeguards. - -AI agents must compensate for these limitations through: - -- strict conventions -- defensive programming -- architectural boundaries -- validation -- testing -- code inspection -- documentation -- controlled self-improvement - ---- - -# 1. Core Principle - -The AI agent must behave as more than a code generator. - -It must act as: - -- developer -- architect -- static analyzer -- compiler substitute -- security reviewer -- code reviewer -- documentation maintainer -- test author -- project historian - -The agent must actively look for problems that VBScript itself may not catch. - ---- - -# 2. Instruction Priority - -When instructions conflict, follow this priority: - -1. Explicit user instructions -2. Security and data protection requirements -3. This AGENTS.md file -4. Project architecture documentation -5. Existing project conventions -6. Existing implementation patterns -7. Agent preferences - -Never weaken security, validation, or data integrity simply to match poor legacy code. - -If legacy code conflicts with these standards, preserve compatibility where required while gradually improving the implementation. - ---- - -# 3. Mandatory VBScript Rules - -## 3.1 Option Explicit - -Every ASP, VBS, and applicable WSC script must use: - -```vbscript -Option Explicit -``` - -No undeclared variables are permitted. - -Before finishing a task, inspect all changed code for undeclared or misspelled identifiers. - ---- - -## 3.2 Variable Declaration - -All variables must be explicitly declared using an appropriate declaration: - -```vbscript -Dim -Private -Public -Const -``` - -Avoid excessive variable reuse. - -Prefer descriptive names. - -Bad: - -```vbscript -Dim x -Dim y -``` - -Better: - -```vbscript -Dim customerId -Dim orderTotal -``` - ---- - -## 3.3 Variant Safety - -VBScript uses Variants extensively. - -Do not assume that a value has the expected type. - -External values must be normalized near application boundaries. - -Use explicit conversion where appropriate: - -```vbscript -CStr() -CLng() -CInt() -CDbl() -CBool() -CDate() -``` - -Never convert unvalidated input blindly. - -Validate first when conversion can fail. - ---- - -# 4. Null, Empty, and Nothing - -These are different states and must not be treated as equivalent. - -Use: - -```vbscript -IsNull(value) -IsEmpty(value) -object Is Nothing -``` - -Database values may contain `Null`. - -Uninitialized Variants may contain `Empty`. - -Object references may contain `Nothing`. - -Code must explicitly account for the state that is expected. - -Do not rely on accidental VBScript coercion. - ---- - -# 5. Request Data Is Untrusted - -Treat all external input as untrusted, including: - -- Request.Form -- Request.QueryString -- Request.Cookies -- Request.ServerVariables -- HTTP headers -- uploaded files -- JSON payloads -- XML payloads -- API data -- database data originating from users -- Session values derived from user input - -External data must pass through: - -```text -Input - ↓ -Validation - ↓ -Normalization - ↓ -Authorization - ↓ -Business Logic -``` - -Never pass raw Request values directly into database or business operations. - ---- - -# 6. SQL Rules - -## 6.1 Parameterization Is Mandatory - -User-controlled data must never be concatenated into SQL. - -Prohibited: - -```vbscript -sql = "SELECT * FROM Users WHERE Email = '" & email & "'" -``` - -Required: - -```vbscript -Set cmd = Server.CreateObject("ADODB.Command") - -Set cmd.ActiveConnection = conn - -cmd.CommandText = _ - "SELECT UserId, Email " & _ - "FROM Users " & _ - "WHERE Email = ?" - -cmd.Parameters.Append _ - cmd.CreateParameter("@Email", adVarWChar, adParamInput, 255, email) -``` - -Use parameters for: - -- SELECT -- INSERT -- UPDATE -- DELETE -- stored procedure calls - ---- - -## 6.2 Dynamic SQL - -When identifiers such as table names or sort columns must be dynamic, they cannot normally be parameterized. - -In such cases, use a whitelist. - -Example: - -```vbscript -Select Case sortField - Case "Name", "CreatedDate", "Status" - ' allowed - Case Else - sortField = "CreatedDate" -End Select -``` - -Never accept arbitrary table names, column names, or SQL fragments from users. - ---- - -# 7. Output Encoding - -HTML output must be encoded by default. - -Prefer: - -```vbscript -Server.HTMLEncode(value) -``` - -or a centralized helper such as: - -```vbscript -Function H(value) - If IsNull(value) Then - H = "" - Else - H = Server.HTMLEncode(CStr(value)) - End If -End Function -``` - -Raw HTML output should only be used when the value is explicitly trusted and intentionally contains HTML. - -Do not assume database data is safe to output without encoding. - ---- - -# 8. Error Handling - -## 8.1 On Error Resume Next - -Broad use of: - -```vbscript -On Error Resume Next -``` - -is prohibited. - -It may only be used around the smallest practical operation requiring error interception. - -Required pattern: - -```vbscript -On Error Resume Next - -Set rs = cmd.Execute() - -If Err.Number <> 0 Then - errorNumber = Err.Number - errorDescription = Err.Description - - Err.Clear - On Error GoTo 0 - - LogError errorNumber, errorDescription - - Err.Raise _ - vbObjectError + 1000, _ - "CustomerRepository.GetCustomer", _ - "Database operation failed." -End If - -On Error GoTo 0 -``` - -Always restore normal error handling. - ---- - -## 8.2 Never Hide Failures - -Do not silently ignore: - -- failed database operations -- failed file operations -- invalid conversions -- failed COM object creation -- authorization failures -- missing required configuration - -Failures must either: - -- be handled intentionally, or -- be logged and propagated appropriately - ---- - -# 9. Architecture - -The preferred application flow is: - -```text -HTTP Request - ↓ -Router - ↓ -Controller - ↓ -Service - ↓ -Repository - ↓ -Database -``` - -Views receive prepared data from controllers or ViewModels. - ---- - -# 10. Controller Rules - -Controllers may: - -- read Request data -- invoke validation -- invoke services -- prepare ViewModels -- redirect -- select views -- set HTTP status codes -- write responses through response abstractions - -Controllers must not: - -- contain SQL -- implement significant business logic -- directly manage recordsets -- duplicate validation rules -- construct complex HTML -- hide application failures - -Keep controllers thin. - ---- - -# 11. Service Rules - -Services contain application and business logic. - -Services may: - -- coordinate repositories -- enforce business rules -- perform calculations -- enforce workflow rules -- call domain-specific collaborators - -Services must not: - -- access Request directly -- access Response directly -- generate HTML -- contain raw SQL -- depend unnecessarily on ASP global state - -Prefer dependency injection through explicit initialization. - ---- - -# 12. Repository Rules - -Repositories own persistence logic. - -Repositories may: - -- execute ADODB commands -- map records to models -- create parameterized queries -- manage database-specific concerns - -Repositories must not: - -- access Request -- access Response -- generate HTML -- contain UI rules - ---- - -# 13. View Rules - -Views may: - -- render HTML -- display ViewModel data -- use simple formatting helpers - -Views must not: - -- execute SQL -- create database connections -- contain major business logic -- make authorization decisions -- perform complex data transformations - -Encode dynamic output by default. - ---- - -# 14. Models and ViewModels - -Models should represent application or domain data. - -ViewModels should represent data specifically prepared for a view. - -Do not pass ADODB.Recordset objects directly into views unless the existing architecture explicitly requires it and refactoring is not currently practical. - -Prefer converting recordsets into application-friendly structures. - ---- - -# 15. Dependency Management - -VBScript does not provide modern dependency injection. - -Use explicit initialization. - -Example: - -```vbscript -Class CustomerService - - Private m_repository - Private m_logger - - Public Sub Init(repository, logger) - Set m_repository = repository - Set m_logger = logger - End Sub - -End Class -``` - -Dependencies should be visible. - -Avoid hidden global dependencies where practical. - ---- - -# 16. Composition Over Inheritance - -VBScript has limited inheritance capabilities. - -Prefer composition. - -Instead of designing deep pseudo-inheritance systems, compose objects from smaller collaborators. - -Example: - -```text -CustomerService - ├── CustomerRepository - ├── CustomerValidator - └── Logger -``` - ---- - -# 17. Interface Conventions - -VBScript cannot formally declare interfaces. - -When interchangeable implementations are needed, define a documented contract. - -Example: - -```text -IUserRepository - -Required members: - -GetById(userId) -GetByEmail(email) -Create(user) -Update(user) -Delete(userId) -``` - -Agents must verify that implementations satisfy documented contracts. - ---- - -# 18. Object Initialization - -Use `Class_Initialize` only for safe initialization that requires no external dependencies. - -Use an explicit method such as: - -```vbscript -Public Sub Init(...) -``` - -for dependency injection. - -Classes should not secretly fetch dependencies from globals when explicit injection is practical. - ---- - -# 19. Session and Application State - -Avoid storing custom COM objects, recordsets, service instances, or application classes in: - -```vbscript -Session -Application -``` - -Prefer primitive values: - -```vbscript -Session("UserId") = CLng(userId) -Session("Username") = CStr(username) -``` - -Use Application state carefully and protect shared writes appropriately. - ---- - -# 20. ADODB Resource Management - -Explicitly close database resources. - -Example: - -```vbscript -If Not rs Is Nothing Then - If rs.State <> 0 Then - rs.Close - End If - - Set rs = Nothing -End If -``` - -Connections must also be closed when owned by the current operation. - -Do not leave recordsets or connections open unnecessarily. - ---- - -# 21. Connection Ownership - -The project should clearly define who owns a database connection. - -A method that opens a connection is normally responsible for closing it. - -Do not close a connection owned by another component unless the contract explicitly states that responsibility. - ---- - -# 22. Small Functions - -Prefer small cohesive procedures. - -Target guideline: - -```text -Function: -10–40 lines where practical - -Class: -100–300 lines where practical - -Controller: -preferably under 200 lines -``` - -These are guidelines, not absolute limits. - -When code becomes difficult to understand, split it by responsibility. - ---- - -# 23. Naming Conventions - -Use consistent naming because VBScript is case-insensitive and offers limited compiler assistance. - -Preferred examples: - -```text -customerId -customerName -orderRepository -customerService -isValid -hasPermission -``` - -Class names: - -```text -CustomerService -CustomerRepository -CustomerValidator -OrderController -``` - -Private fields may use: - -```text -m_repository -m_logger -m_customerId -``` - -Follow established project conventions if they are consistent and clear. - ---- - -# 24. Boolean Naming - -Prefer names that read naturally: - -```text -isValid -isActive -hasAccess -hasPermission -canDelete -shouldRetry -``` - -Avoid ambiguous names such as: - -```text -flag -value1 -test -status2 -``` - ---- - -# 25. Magic Values - -Avoid unexplained magic values. - -Bad: - -```vbscript -If status = 4 Then -``` - -Better: - -```vbscript -Const STATUS_COMPLETED = 4 -``` - -Use constants or centralized configuration where appropriate. - ---- - -# 26. Configuration - -Environment-specific settings must not be scattered throughout application code. - -Centralize: - -- connection strings -- filesystem paths -- URLs -- email settings -- feature flags -- API keys -- environment names - -Secrets must not be committed to source control. - ---- - -# 27. Logging - -Important errors should be logged with useful context. - -Prefer structured information such as: - -```text -Timestamp -RequestId -UserId if appropriate -Component -Operation -Error number -Error description -Relevant safe context -``` - -Never log: - -- passwords -- authentication tokens -- full credit card data -- secret keys -- highly sensitive personal data unless explicitly necessary and protected - ---- - -# 28. Authentication and Authorization - -Authentication answers: - -```text -Who is this user? -``` - -Authorization answers: - -```text -Is this user allowed to perform this operation? -``` - -They are not interchangeable. - -Authorization must be enforced server-side. - -Never rely solely on hidden buttons, JavaScript, or UI restrictions. - ---- - -# 29. CSRF Protection - -State-changing requests should use CSRF protection where practical. - -This includes: - -- POST -- PUT-like actions -- DELETE-like actions -- administrative operations - -Do not perform destructive actions solely through unprotected GET requests. - ---- - -# 30. HTTP Method Semantics - -Prefer: - -```text -GET → retrieve data -POST → create/change state -``` - -Avoid state-changing GET endpoints unless required by legacy compatibility. - ---- - -# 31. Redirect Safety - -Do not redirect to arbitrary user-provided URLs. - -Validate redirects against: - -- known internal routes -- allowed hosts -- approved paths - ---- - -# 32. File Handling - -Uploaded files must be treated as untrusted. - -Validate: - -- filename -- extension -- actual content where practical -- size -- target path -- permissions - -Prevent path traversal. - -Never construct filesystem paths directly from arbitrary user input. - ---- - -# 33. Include File Discipline - -Includes are dependencies, not architecture. - -Avoid large global include chains. - -Prefer explicit grouped includes such as: - -```text -/config -/framework -/app/controllers -/app/services -/app/repositories -/app/models -/app/views -``` - -Before adding a new include, check whether the functionality belongs in an existing component. - ---- - -# 34. Shared Utilities - -Before creating a utility function, search for an existing implementation. - -Common shared helpers may include: - -```text -HtmlEncode -JsonEncode -JsonEscape -Nz -ToInteger -ToLong -ToBoolean -ToDate -ValidateEmail -ExecuteScalar -ExecuteNonQuery -Logger -UrlEncode -GenerateGuid -``` - -Do not create duplicate helpers with slightly different behavior. - ---- - -# 35. JSON - -Do not build complex JSON through unsafe string concatenation. - -Use the project's JSON serializer or centralized JSON utilities. - -Escape: - -- quotes -- backslashes -- control characters -- line breaks - -Ensure output is valid JSON. - ---- - -# 36. JavaScript Boundaries - -Server-side validation is mandatory even when client-side validation exists. - -JavaScript validation is for user experience. - -VBScript validation is for correctness and security. - -Never trust browser-side validation alone. - ---- - -# 37. Testing Expectations - -Every significant change should be evaluated for testability. - -Where practical, create tests for: - -- validation -- business rules -- conversions -- repositories -- security-sensitive logic -- regressions - -Business logic should be separated from ASP globals so it can be tested independently. - ---- - -# 38. Regression Prevention - -When fixing a bug: - -1. understand the root cause -2. identify the violated invariant -3. fix the underlying problem -4. add or update a test where practical -5. search for similar occurrences elsewhere -6. update documentation if the rule was previously unclear - -Do not patch symptoms repeatedly. - ---- - -# 39. Agent Pre-Change Procedure - -Before modifying code, the agent should: - -1. Read this AGENTS.md. -2. Read CLAUDE.md if present. -3. Inspect the relevant project files. -4. Search for existing implementations. -5. Understand the dependency direction. -6. Identify security implications. -7. Determine whether tests exist. -8. Avoid creating duplicate abstractions. - -For small changes, do this proportionally. - ---- - -# 40. Agent Post-Change Review - -Before declaring work complete, review changed code for: - -- missing Option Explicit -- undeclared variables -- misspelled identifiers -- missing Set statements -- incorrect parameter counts -- Null handling -- Empty handling -- Nothing handling -- unsafe implicit conversion -- SQL injection -- unparameterized SQL -- XSS -- missing HTML encoding -- unsafe redirects -- path traversal -- authorization bypass -- broad On Error Resume Next -- swallowed errors -- open recordsets -- open database connections -- excessive global state -- duplicate utilities -- architectural boundary violations -- unreachable code -- dead code -- missing cleanup -- poor naming - ---- - -# 41. Missing Set Check - -VBScript requires `Set` for object assignment. - -Agents must specifically inspect object assignments. - -Incorrect: - -```vbscript -repo = New CustomerRepository -``` - -Correct: - -```vbscript -Set repo = New CustomerRepository -``` - -This should be part of every static review. - ---- - -# 42. Return Value Check - -VBScript functions return values by assigning to the function name. - -Example: - -```vbscript -Function AddNumbers(a, b) - AddNumbers = a + b -End Function -``` - -Agents must verify all execution paths return the expected value when a return value is required. - ---- - -# 43. ByRef Awareness - -VBScript parameters are `ByRef` by default. - -This can unintentionally mutate caller values. - -Prefer explicitly declaring intent. - -Use: - -```vbscript -Function ValidateCustomer(ByVal customer) -``` - -when modification of the caller's variable is not intended. - -Use `ByRef` intentionally. - ---- - -# 44. Parentheses and Call Syntax - -VBScript procedure-call syntax can be confusing. - -Agents must generate syntactically valid VBScript calls. - -Be especially careful with: - -- `Call` -- parentheses -- functions used for return values -- Subs invoked without `Call` - -Prefer simple consistent calling patterns. - ---- - -# 45. Date Handling - -Do not assume date string formats. - -Prefer true Date values internally. - -Validate and convert input explicitly. - -Be aware of: - -- server locale -- database date formats -- regional settings - -Use parameterized database values rather than embedding formatted date strings in SQL. - ---- - -# 46. Numeric Handling - -Do not assume values from Request are numeric. - -Validate before conversion. - -Example logic: - -```text -Read input -↓ -Trim -↓ -Check required/optional -↓ -Validate numeric format -↓ -Convert -``` - -Handle overflow and invalid values appropriately. - ---- - -# 47. Database Null Mapping - -When mapping database records to models, define expected behavior for Null fields. - -Do not allow arbitrary Null propagation unless the domain explicitly permits it. - -Consider centralized helpers. - ---- - -# 48. Performance - -ASP Classic is synchronous. - -Avoid unnecessary: - -- database round trips -- repeated queries inside loops -- filesystem calls -- external HTTP requests -- COM object creation -- large Session values - -Watch for N+1 query patterns. - -Prefer set-based SQL. - ---- - -# 49. Caching - -Caching may be used where appropriate but must have: - -- clear ownership -- expiration behavior -- invalidation rules -- concurrency awareness - -Never cache sensitive per-user data globally without proper separation. - ---- - -# 50. Application State Concurrency - -ASP `Application` state can be shared across requests. - -When modifying shared Application values, consider: - -```vbscript -Application.Lock -Application.Unlock -``` - -Keep locked regions minimal. - ---- - -# 51. Backward Compatibility - -When modifying legacy code: - -1. identify existing behavior -2. determine whether other code depends on it -3. preserve public contracts where practical -4. avoid unrelated rewrites -5. improve internals incrementally - -Do not modernize code purely for style if it introduces unnecessary risk. - ---- - -# 52. Refactoring Rule - -Refactoring should preserve observable behavior unless changing behavior is an explicit goal. - -Separate: - -```text -behavior change -``` - -from: - -```text -structural cleanup -``` - -where practical. - ---- - -# 53. Documentation Rule - -When introducing: - -- a new architecture convention -- a new shared component -- a new security requirement -- a new dependency -- a new recurring coding pattern - -update relevant documentation. - -Do not leave important architectural knowledge only in source code. - ---- - -# 54. Self-Improvement System - -This file is allowed to evolve. - -Agents may propose or make updates to AGENTS.md when project experience reveals that the instructions are: - -- incomplete -- outdated -- ambiguous -- repeatedly violated -- causing bugs -- missing an important security rule -- missing an architectural convention -- inconsistent with the actual project -- superseded by a better proven pattern - -Self-improvement must be controlled. - ---- - -# 55. When the Agent Should Update AGENTS.md - -Consider updating this file when: - -1. the same mistake occurs more than once -2. a bug reveals a missing development rule -3. a new framework component establishes a reusable pattern -4. a new security requirement becomes necessary -5. project architecture materially changes -6. a repeated manual review step can become an explicit rule -7. a legacy convention is officially replaced -8. new infrastructure becomes standard -9. a user explicitly establishes a permanent project rule - -Do not update this file for trivial one-time implementation details. - ---- - -# 56. Self-Update Safety - -An agent must never silently weaken these core protections: - -- parameterized SQL -- output encoding -- authorization -- input validation -- controlled error handling -- explicit variable declarations -- Option Explicit -- resource cleanup -- security boundaries - -Changes affecting these protections require explicit justification. - ---- - -# 57. Rule Classification - -Rules may be considered: - -```text -CORE -PROJECT -ADVISORY -TEMPORARY -``` - -CORE rules should rarely change. - -Examples: - -```text -CORE: -SQL parameterization -Option Explicit -server-side authorization -output encoding - -PROJECT: -folder structure -repository naming -routing conventions - -ADVISORY: -function length guidelines - -TEMPORARY: -migration-specific compatibility rules -``` - -When adding an important rule, identify its conceptual category if useful. - ---- - -# 58. Learning From Bugs - -After fixing a significant bug, ask: - -```text -Could a rule have prevented this? -``` - -If yes: - -- update AGENTS.md, or -- update a specialized project document, or -- add a test, or -- improve a framework abstraction - -Prefer systemic prevention over repeated manual correction. - ---- - -# 59. Learning From Code Review - -If a code review repeatedly identifies the same problem, convert the feedback into: - -- an explicit agent rule -- a reusable helper -- a test -- an architectural constraint - -The goal is continuous reduction of repeated mistakes. - ---- - -# 60. Update History - -Meaningful changes to AGENTS.md should be recorded below. - -Keep entries concise. - -Format: - -```text -YYYY-MM-DD -- Added rule: -- Reason: -``` - -Example: - -```text -2026-09-02 -- Added explicit ByVal guidance. -- Reason: VBScript defaults to ByRef and accidental mutations were difficult to detect. -``` - ---- - -# 61. Do Not Turn This File Into a Dumping Ground - -AGENTS.md should contain durable development knowledge. - -Do not store: - -- task-specific notes -- temporary debugging output -- one-time TODOs -- credentials -- secrets -- personal information -- giant code examples - -Move specialized guidance into focused files when this file becomes too large. - ---- - -# 62. Specialized Skills - -As the project grows, agents may create focused guidance such as: - -```text -/docs/architecture.md -/docs/security.md -/docs/database.md -/docs/testing.md - -/skills/asp-classic.md -/skills/adodb.md -/skills/security.md -/skills/testing.md -``` - -AGENTS.md remains the central index and policy authority. - ---- - -# 63. Creating New Skills - -Agents may create a new skill or focused guidance document when: - -- a task is repeated frequently -- the knowledge is specialized -- the instructions are too detailed for AGENTS.md -- the process can be reused -- consistent execution would materially improve quality - -A new skill should state: - -```text -Purpose -When to use it -Inputs -Procedure -Rules -Validation -Common failure modes -Output expectations -``` - ---- - -# 64. Updating Existing Skills - -When project behavior changes, update the existing relevant skill instead of creating a duplicate. - -Before creating a new document, search for an existing location for that knowledge. - ---- - -# 65. Agent Decision Journal - -For major architectural changes, record concise rationale in the appropriate documentation. - -Document: - -```text -Decision -Context -Alternatives -Reason selected -Consequences -``` - -Do not record private chain-of-thought. - -Record only useful engineering rationale. - ---- - -# 66. Definition of Done - -A task is not complete merely because the code runs. - -A change is complete when appropriate checks have been performed for: - -```text -Correctness -Security -Architecture -Compatibility -Validation -Error handling -Resource cleanup -Testing -Documentation -Maintainability -``` - ---- - -# 67. Final Agent Checklist - -Before finishing a coding task, answer internally: - -```text -[ ] Did I read the relevant instructions? -[ ] Did I inspect existing code before creating new code? -[ ] Did I preserve architecture boundaries? -[ ] Is all external input validated? -[ ] Is SQL parameterized? -[ ] Is dynamic HTML encoded? -[ ] Is authorization enforced server-side? -[ ] Are errors handled intentionally? -[ ] Are database resources cleaned up? -[ ] Are object assignments using Set? -[ ] Did I account for Null, Empty, and Nothing? -[ ] Did I account for ByRef behavior? -[ ] Did I avoid unnecessary global state? -[ ] Did I avoid duplicating utilities? -[ ] Did I update tests where appropriate? -[ ] Did I update documentation if a durable rule changed? -[ ] Did this task reveal something the agent rules should learn? -``` - ---- - -# 68. Guiding Philosophy - -Do not fight VBScript. - -Compensate for its weaknesses. - -Prefer simple, explicit, understandable code over clever abstractions. - -The desired result is: - -```text -Classic ASP simplicity - + -strict engineering discipline - + -AI-assisted static review - + -modern security practices - = -maintainable ASP Classic applications -``` - ---- - -# Update History - -2026-09-02 -- Initial ASP Classic/VBScript AI development policy created. -- Added controlled self-improvement rules. -- Added architecture, security, validation, ADODB, error handling, testing, and agent review requirements. diff --git a/docs/CLAUDE.md b/docs/CLAUDE.md deleted file mode 100644 index c19f92d..0000000 --- a/docs/CLAUDE.md +++ /dev/null @@ -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. diff --git a/docs/Windows scripting secrets.pdf b/docs/Windows scripting secrets.pdf deleted file mode 100644 index b066c64..0000000 Binary files a/docs/Windows scripting secrets.pdf and /dev/null differ diff --git a/docs/api-contracts-mvc-starter.md b/docs/api-contracts-mvc-starter.md deleted file mode 100644 index 655f436..0000000 --- a/docs/api-contracts-mvc-starter.md +++ /dev/null @@ -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. diff --git a/docs/architecture-patterns.md b/docs/architecture-patterns.md deleted file mode 100644 index bc5d275..0000000 --- a/docs/architecture-patterns.md +++ /dev/null @@ -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. diff --git a/docs/architecture.md b/docs/architecture.md deleted file mode 100644 index ad5a6b6..0000000 --- a/docs/architecture.md +++ /dev/null @@ -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. diff --git a/docs/component-inventory.md b/docs/component-inventory.md deleted file mode 100644 index cc5e19c..0000000 --- a/docs/component-inventory.md +++ /dev/null @@ -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. diff --git a/docs/comprehensive-analysis-mvc-starter.md b/docs/comprehensive-analysis-mvc-starter.md deleted file mode 100644 index c3ce8cd..0000000 --- a/docs/comprehensive-analysis-mvc-starter.md +++ /dev/null @@ -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. diff --git a/docs/critical-folders-summary.md b/docs/critical-folders-summary.md deleted file mode 100644 index f53b4d5..0000000 --- a/docs/critical-folders-summary.md +++ /dev/null @@ -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 diff --git a/docs/data-models-mvc-starter.md b/docs/data-models-mvc-starter.md deleted file mode 100644 index 408e980..0000000 --- a/docs/data-models-mvc-starter.md +++ /dev/null @@ -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_

    .asp` - - `
    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. diff --git a/docs/deployment-configuration.md b/docs/deployment-configuration.md deleted file mode 100644 index 51186d4..0000000 --- a/docs/deployment-configuration.md +++ /dev/null @@ -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 -\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 `\releases\\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. diff --git a/docs/deployment-guide.md b/docs/deployment-guide.md deleted file mode 100644 index 1ffd3a3..0000000 --- a/docs/deployment-guide.md +++ /dev/null @@ -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 `\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\ - \ - 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 `.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 `\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 `\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. diff --git a/docs/development-guide.md b/docs/development-guide.md deleted file mode 100644 index 2e519fd..0000000 --- a/docs/development-guide.md +++ /dev/null @@ -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/` diff --git a/docs/development-instructions.md b/docs/development-instructions.md deleted file mode 100644 index 042163c..0000000 --- a/docs/development-instructions.md +++ /dev/null @@ -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`. diff --git a/docs/existing-documentation-inventory.md b/docs/existing-documentation-inventory.md deleted file mode 100644 index 934832c..0000000 --- a/docs/existing-documentation-inventory.md +++ /dev/null @@ -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. diff --git a/docs/ideas.md b/docs/ideas.md deleted file mode 100644 index b564e19..0000000 --- a/docs/ideas.md +++ /dev/null @@ -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 - diff --git a/docs/index.md b/docs/index.md deleted file mode 100644 index 550e377..0000000 --- a/docs/index.md +++ /dev/null @@ -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`. diff --git a/docs/project-overview.md b/docs/project-overview.md deleted file mode 100644 index e306799..0000000 --- a/docs/project-overview.md +++ /dev/null @@ -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) diff --git a/docs/project-parts.json b/docs/project-parts.json deleted file mode 100644 index c68ffc7..0000000 --- a/docs/project-parts.json +++ /dev/null @@ -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" - ] - } - ] -} diff --git a/docs/project-scan-report.json b/docs/project-scan-report.json deleted file mode 100644 index 368fbe0..0000000 --- a/docs/project-scan-report.json +++ /dev/null @@ -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."} diff --git a/docs/project-structure.md b/docs/project-structure.md deleted file mode 100644 index 93b69fd..0000000 --- a/docs/project-structure.md +++ /dev/null @@ -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. diff --git a/docs/source-tree-analysis.md b/docs/source-tree-analysis.md deleted file mode 100644 index 806d0bb..0000000 --- a/docs/source-tree-analysis.md +++ /dev/null @@ -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. diff --git a/docs/state-management-patterns-mvc-starter.md b/docs/state-management-patterns-mvc-starter.md deleted file mode 100644 index 7f31ad4..0000000 --- a/docs/state-management-patterns-mvc-starter.md +++ /dev/null @@ -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. diff --git a/docs/technology-stack.md b/docs/technology-stack.md deleted file mode 100644 index cba95e2..0000000 --- a/docs/technology-stack.md +++ /dev/null @@ -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. diff --git a/docs/ui-component-inventory-mvc-starter.md b/docs/ui-component-inventory-mvc-starter.md deleted file mode 100644 index 15f2b15..0000000 --- a/docs/ui-component-inventory-mvc-starter.md +++ /dev/null @@ -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. diff --git a/docs/user-provided-context.md b/docs/user-provided-context.md deleted file mode 100644 index 422d801..0000000 --- a/docs/user-provided-context.md +++ /dev/null @@ -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 diff --git a/public/Default.asp b/public/Default.asp index 61c5a91..fd65121 100644 --- a/public/Default.asp +++ b/public/Default.asp @@ -1,4 +1,4 @@ - + <% ' 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() %> diff --git a/public/web.config b/public/web.config index b917900..a145dd7 100644 --- a/public/web.config +++ b/public/web.config @@ -3,12 +3,11 @@ - + @@ -50,18 +49,18 @@ - + - + - + diff --git a/run_site.cmd b/run_site.cmd deleted file mode 100644 index 2f87205..0000000 --- a/run_site.cmd +++ /dev/null @@ -1,4 +0,0 @@ -@echo off -setlocal -set "ASPC_STARTER_ROOT=%~dp0" -"C:\Program Files\IIS Express\iisexpress.exe" /config:"%~dp0applicationhost.config" \ No newline at end of file diff --git a/scripts/GenerateApi.vbs b/scripts/GenerateApi.vbs new file mode 100644 index 0000000..a33c5e6 --- /dev/null +++ b/scripts/GenerateApi.vbs @@ -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
    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/
    added +' public/api/
    .openapi.json OpenAPI spec (shows up in the /api/docs Swagger UI) +' api-tests/
    .http sample requests (VS Code REST Client) +' +' Notes: a JSON null is not accepted for a field (omit it instead). Needs app/models/POBO_
    .asp and
    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: /pk:" + 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", "" +AppendIfMissing "/app/models/autoload_models.asp", tableName & "Repository.asp", "" +AppendIfMissing "/app/controllers/autoload_controllers.asp", "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 diff --git a/scripts/GenerateRepo.vbs b/scripts/GenerateRepo.vbs index 258cd9c..cbde714 100644 --- a/scripts/GenerateRepo.vbs +++ b/scripts/GenerateRepo.vbs @@ -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 , -' discovers [table] schema, and generates: -' � POBO_
    .asp (Classic ASP class with typed Property Lets) -' �
    Repository.asp (parameterized CRUD + paging + search) +' Reads the connection string from public\web.config ( ConnectionString = ":"), +' discovers the table schema, and generates into app/models/: +' POBO_
    .asp (class with typed Property Let/Get) +'
    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: /pk: [/cs:] [/config:]" + WScript.Echo "Usage: scripts\gen.cmd repo /table: /pk:" 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 ':'. 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_
    .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
    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 " " +WScript.Echo " " + 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 diff --git a/scripts/_cli.vbs b/scripts/_cli.vbs new file mode 100644 index 0000000..30cbc97 --- /dev/null +++ b/scripts/_cli.vbs @@ -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 +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 diff --git a/scripts/deploy-iis-git.ps1 b/scripts/deploy-iis-git.ps1 deleted file mode 100644 index 71910bd..0000000 --- a/scripts/deploy-iis-git.ps1 +++ /dev/null @@ -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 } -} diff --git a/scripts/gen.cmd b/scripts/gen.cmd new file mode 100644 index 0000000..805ae99 --- /dev/null +++ b/scripts/gen.cmd @@ -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 +rem scripts\gen.cmd controller Index "Show(id)" NewForm Create "Edit(id)" "Update(id)" "Delete(id)" +rem scripts\gen.cmd repo /table:
    /pk: +rem scripts\gen.cmd api /table:
    /pk: (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 diff --git a/scripts/generateController.vbs b/scripts/generateController.vbs index 91cc703..4395e52 100644 Binary files a/scripts/generateController.vbs and b/scripts/generateController.vbs differ diff --git a/scripts/generateMigration.vbs b/scripts/generateMigration.vbs index 613ed3a..0874a54 100644 --- a/scripts/generateMigration.vbs +++ b/scripts/generateMigration.vbs @@ -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 diff --git a/scripts/install-iis-release.ps1 b/scripts/install-iis-release.ps1 deleted file mode 100644 index 77bbef9..0000000 --- a/scripts/install-iis-release.ps1 +++ /dev/null @@ -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 \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 -} diff --git a/scripts/migrate.asp b/scripts/migrate.asp new file mode 100644 index 0000000..c318eb6 --- /dev/null +++ b/scripts/migrate.asp @@ -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" +%> + +<% +Dim m : Set m = Migrator() +m.MigrationsPath = Server.MapPath("/db/migrations") ' requires SERVER_WEB_ROOT= +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 +%> diff --git a/scripts/migrate.cmd b/scripts/migrate.cmd new file mode 100644 index 0000000..fe99885 --- /dev/null +++ b/scripts/migrate.cmd @@ -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 diff --git a/scripts/migrate_isbusiness_to_households.vbs b/scripts/migrate_isbusiness_to_households.vbs deleted file mode 100644 index 5f0a8b9..0000000 --- a/scripts/migrate_isbusiness_to_households.vbs +++ /dev/null @@ -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 diff --git a/scripts/runMigrations.vbs b/scripts/runMigrations.vbs deleted file mode 100644 index cc25d64..0000000 --- a/scripts/runMigrations.vbs +++ /dev/null @@ -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 - Apply a specific migration file -' rollback - 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 " - 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 " - 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 - Apply a specific migration file" - WScript.Echo " rollback - 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 diff --git a/scripts/templates/Api.tpl.asp b/scripts/templates/Api.tpl.asp new file mode 100644 index 0000000..47fdbce --- /dev/null +++ b/scripts/templates/Api.tpl.asp @@ -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 +%> diff --git a/scripts/templates/POBO.tpl.asp b/scripts/templates/POBO.tpl.asp new file mode 100644 index 0000000..a016800 --- /dev/null +++ b/scripts/templates/POBO.tpl.asp @@ -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 +%> diff --git a/scripts/templates/Repository.tpl.asp b/scripts/templates/Repository.tpl.asp new file mode 100644 index 0000000..7a273d9 --- /dev/null +++ b/scripts/templates/Repository.tpl.asp @@ -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 +%> diff --git a/tests/PlainRunnerTheme.asp b/tests/PlainRunnerTheme.asp deleted file mode 100644 index da9198a..0000000 --- a/tests/PlainRunnerTheme.asp +++ /dev/null @@ -1,190 +0,0 @@ -<% -Class PlainRunnerTheme - Public Sub Render(ByRef objRunner) -%> - - - - - MVC-Starter Test Runner - - - -

    MVC-Starter Test Runner

    -

    Dev-only aspunit runner for the separate tests/ IIS application.

    - -
    Running tests...
    -
    - - - - -<% - 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 -%> diff --git a/tests/aspunit/LICENSE-MIT b/tests/aspunit/LICENSE-MIT deleted file mode 100644 index df2f8a6..0000000 --- a/tests/aspunit/LICENSE-MIT +++ /dev/null @@ -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. \ No newline at end of file diff --git a/tests/aspunit/Lib/ASPUnit.asp b/tests/aspunit/Lib/ASPUnit.asp deleted file mode 100644 index ef96c9b..0000000 --- a/tests/aspunit/Lib/ASPUnit.asp +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - -<% - Dim ASPUnit - Set ASPUnit = New ASPUnitLibrary - - ASPUnit.Task = Request.QueryString("task") -%> \ No newline at end of file diff --git a/tests/aspunit/Lib/classes/ASPUnitJSONResponder.asp b/tests/aspunit/Lib/classes/ASPUnitJSONResponder.asp deleted file mode 100644 index f95c685..0000000 --- a/tests/aspunit/Lib/classes/ASPUnitJSONResponder.asp +++ /dev/null @@ -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 -%> \ No newline at end of file diff --git a/tests/aspunit/Lib/classes/ASPUnitLibrary.asp b/tests/aspunit/Lib/classes/ASPUnitLibrary.asp deleted file mode 100644 index 9c89a33..0000000 --- a/tests/aspunit/Lib/classes/ASPUnitLibrary.asp +++ /dev/null @@ -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 -%> \ No newline at end of file diff --git a/tests/aspunit/Lib/classes/ASPUnitRunner.asp b/tests/aspunit/Lib/classes/ASPUnitRunner.asp deleted file mode 100644 index 974895c..0000000 --- a/tests/aspunit/Lib/classes/ASPUnitRunner.asp +++ /dev/null @@ -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() %> - <% - End Sub - - Public Sub RenderJSInit() %> - <% - 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 -%> \ No newline at end of file diff --git a/tests/aspunit/Lib/classes/ASPUnitTester.asp b/tests/aspunit/Lib/classes/ASPUnitTester.asp deleted file mode 100644 index 887e9f2..0000000 --- a/tests/aspunit/Lib/classes/ASPUnitTester.asp +++ /dev/null @@ -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 -%> \ No newline at end of file diff --git a/tests/aspunit/Lib/classes/ASPUnitUIModern.asp b/tests/aspunit/Lib/classes/ASPUnitUIModern.asp deleted file mode 100644 index d09f06a..0000000 --- a/tests/aspunit/Lib/classes/ASPUnitUIModern.asp +++ /dev/null @@ -1,395 +0,0 @@ -<% - Class ASPUnitUIModern - Public Sub Render(ByRef objRunner) %> - - - ASPUnit - - - - - - - - -
    - - -
    -
    -
    - - -
    - - - - - - - - - - - - - <%= objRunner.RenderJSLib() %> - - - - <%= objRunner.RenderJSInit() %> - - <% - End Sub - End Class -%> \ No newline at end of file diff --git a/tests/bootstrap.asp b/tests/bootstrap.asp deleted file mode 100644 index 809d47f..0000000 --- a/tests/bootstrap.asp +++ /dev/null @@ -1,49 +0,0 @@ - - - -<% -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() -%> diff --git a/tests/component/TestHomeController.asp b/tests/component/TestHomeController.asp deleted file mode 100644 index bd84754..0000000 --- a/tests/component/TestHomeController.asp +++ /dev/null @@ -1,43 +0,0 @@ - - - - -<% -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 -%> diff --git a/tests/component/web.config b/tests/component/web.config deleted file mode 100644 index 3bf406c..0000000 --- a/tests/component/web.config +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/tests/integration/TestConfigSettings.asp b/tests/integration/TestConfigSettings.asp deleted file mode 100644 index 60089d6..0000000 --- a/tests/integration/TestConfigSettings.asp +++ /dev/null @@ -1,41 +0,0 @@ - - - -<% -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 -%> diff --git a/tests/integration/TestMvcDispatch.asp b/tests/integration/TestMvcDispatch.asp deleted file mode 100644 index 9a8d803..0000000 --- a/tests/integration/TestMvcDispatch.asp +++ /dev/null @@ -1,80 +0,0 @@ - - - - -<% -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 -%> diff --git a/tests/integration/TestRenderedOutput.asp b/tests/integration/TestRenderedOutput.asp deleted file mode 100644 index fc76c54..0000000 --- a/tests/integration/TestRenderedOutput.asp +++ /dev/null @@ -1,52 +0,0 @@ - - - - -<% -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 -%> diff --git a/tests/integration/TestRoutes.asp b/tests/integration/TestRoutes.asp deleted file mode 100644 index 56b9cc5..0000000 --- a/tests/integration/TestRoutes.asp +++ /dev/null @@ -1,51 +0,0 @@ - - - - -<% -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 -%> diff --git a/tests/integration/TestSharedLayout.asp b/tests/integration/TestSharedLayout.asp deleted file mode 100644 index b5645b6..0000000 --- a/tests/integration/TestSharedLayout.asp +++ /dev/null @@ -1,69 +0,0 @@ - - - - -<% -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")), "home") > 0), _ - "Home page layout should render the controller title in the 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 -%> diff --git a/tests/integration/web.config b/tests/integration/web.config deleted file mode 100644 index 3bf406c..0000000 --- a/tests/integration/web.config +++ /dev/null @@ -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> diff --git a/tests/run-all.asp b/tests/run-all.asp deleted file mode 100644 index 0abc77e..0000000 --- a/tests/run-all.asp +++ /dev/null @@ -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() -%> diff --git a/tests/run-tests.cmd b/tests/run-tests.cmd deleted file mode 100644 index 9a692b4..0000000 --- a/tests/run-tests.cmd +++ /dev/null @@ -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 diff --git a/tests/support/HttpCaptureHelpers.asp b/tests/support/HttpCaptureHelpers.asp deleted file mode 100644 index 6140c30..0000000 --- a/tests/support/HttpCaptureHelpers.asp +++ /dev/null @@ -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 -%> diff --git a/tests/sync-webconfigs.vbs b/tests/sync-webconfigs.vbs deleted file mode 100644 index a56f47f..0000000 --- a/tests/sync-webconfigs.vbs +++ /dev/null @@ -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 diff --git a/tests/test-manifest.asp b/tests/test-manifest.asp deleted file mode 100644 index fcededa..0000000 --- a/tests/test-manifest.asp +++ /dev/null @@ -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 -%> diff --git a/tests/unit/TestControllerRegistry.asp b/tests/unit/TestControllerRegistry.asp deleted file mode 100644 index 2ec905f..0000000 --- a/tests/unit/TestControllerRegistry.asp +++ /dev/null @@ -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 -%> diff --git a/tests/unit/TestHelpers.asp b/tests/unit/TestHelpers.asp deleted file mode 100644 index 1144cdb..0000000 --- a/tests/unit/TestHelpers.asp +++ /dev/null @@ -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 -%> diff --git a/tests/unit/web.config b/tests/unit/web.config deleted file mode 100644 index 3bf406c..0000000 --- a/tests/unit/web.config +++ /dev/null @@ -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> diff --git a/tests/web.config b/tests/web.config deleted file mode 100644 index 3bf406c..0000000 --- a/tests/web.config +++ /dev/null @@ -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>