| @@ -0,0 +1,7 @@ | |||||
| /_bmad | |||||
| /_bmad* | |||||
| /.agents | |||||
| /.github | |||||
| # SQLite database (created by the first migration run; never commit data) | |||||
| /db/*.sqlite | |||||
| /db/*.sqlite-* | |||||
| @@ -0,0 +1,60 @@ | |||||
| # RouteKit Classic ASP - MVC Starter (AxonASP) | |||||
| 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. | |||||
| No sample modules are included: the first table you add is yours. | |||||
| ## Quick start | |||||
| Requires Docker. | |||||
| ``` | |||||
| cd deploy | |||||
| docker compose up -d --build | |||||
| ``` | |||||
| Open http://localhost:8801. The compose file mounts this folder into the container and serves `public/`. | |||||
| After editing ASP code, restart the container so cached scripts are recompiled: `docker restart axonasp`. | |||||
| ## Project structure | |||||
| ``` | |||||
| public/ web root: Default.asp (front controller + routes), web.config (rewrite, settings) | |||||
| core/ framework: mvc.asp, router, DAL (G3DB), migrations, JsonLite, helpers, lib.*.asp | |||||
| app/ | |||||
| controllers/ <Name>Controller.asp (HTML), Api<Name>Controller.asp (JSON), autoload_controllers.asp | |||||
| models/ POBO_<Table>.asp, <Table>Repository.asp (generated), autoload_models.asp | |||||
| views/ <Name>/ views; shared/ layout (header, footer); Home, Error, Docs | |||||
| db/ | |||||
| migrations/ YYYYMMDDHHMMSS_name.asp (Migration_Up / Migration_Down) | |||||
| app.sqlite created by the first migration run (git-ignored) | |||||
| scripts/ gen.cmd (generators), migrate.cmd, templates/ | |||||
| (deploy/ with the Dockerfile and docker-compose.yml currently sits next to this folder, outside this git repo) | |||||
| ``` | |||||
| ## Adding a feature | |||||
| 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). | |||||
| 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. | |||||
| The Swagger UI at http://localhost:8801/api/docs lists every generated API spec and lets you call the endpoints. | |||||
| ## Included | |||||
| - **HomeController**: welcome page at `/` | |||||
| - **ErrorController**: 404 page | |||||
| - **DocsController**: Swagger UI at `/api/docs` | |||||
| ## Configuration | |||||
| - `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`). | |||||
| ## Rules for developers and AI agents | |||||
| See [AGENTS.md](../AGENTS.md) at the repository root: language rules, AxonASP quirks verified in this project, security checklist and working rules. | |||||
| @@ -0,0 +1,29 @@ | |||||
| <% | |||||
| ' DocsController: interactive API docs (Swagger UI) for the JSON API. The spec is public/api/openapi.json. | |||||
| Class DocsController_Class | |||||
| Public Property Get useLayout() | |||||
| useLayout = True | |||||
| End Property | |||||
| Public Property Let useLayout(v) | |||||
| End Property | |||||
| Public Property Get Title() | |||||
| Title = "API docs" | |||||
| End Property | |||||
| Public Sub Index() | |||||
| %> | |||||
| <!--#include file="../views/Docs/index.asp" --> | |||||
| <% | |||||
| End Sub | |||||
| End Class | |||||
| Dim DocsController_Class__Singleton | |||||
| Function DocsController() | |||||
| If IsEmpty(DocsController_Class__Singleton) Then | |||||
| Set DocsController_Class__Singleton = New DocsController_Class | |||||
| End If | |||||
| Set DocsController = DocsController_Class__Singleton | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,37 @@ | |||||
| <% | |||||
| Class ErrorController_Class | |||||
| Private m_useLayout | |||||
| Private Sub Class_Initialize() | |||||
| m_useLayout = True | |||||
| End Sub | |||||
| Public Property Get useLayout | |||||
| useLayout = m_useLayout | |||||
| End Property | |||||
| Public Property Let useLayout(v) | |||||
| m_useLayout = v | |||||
| End Property | |||||
| Public Sub Index() | |||||
| Response.Write "Index called" | |||||
| End Sub | |||||
| Public Sub NotFound() | |||||
| Response.Status = "404 Not Found" | |||||
| %> | |||||
| <!--#include file="../views/Error/NotFound.asp" --> | |||||
| <% | |||||
| End Sub | |||||
| End Class | |||||
| Dim ErrorController_Class__Singleton | |||||
| Function ErrorController() | |||||
| If IsEmpty(ErrorController_Class__Singleton) Then | |||||
| Set ErrorController_Class__Singleton = New ErrorController_Class | |||||
| End If | |||||
| Set ErrorController = ErrorController_Class__Singleton | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,42 @@ | |||||
| <% | |||||
| Class HomeController_Class | |||||
| Private m_useLayout | |||||
| Private m_title | |||||
| Private Sub Class_Initialize() | |||||
| m_useLayout = True | |||||
| m_title = "Home" | |||||
| End Sub | |||||
| Public Property Get useLayout | |||||
| useLayout = m_useLayout | |||||
| End Property | |||||
| Public Property Let useLayout(v) | |||||
| m_useLayout = v | |||||
| End Property | |||||
| Public Property Get Title | |||||
| Title = m_title | |||||
| End Property | |||||
| Public Property Let Title(v) | |||||
| m_title = v | |||||
| End Property | |||||
| Public Sub index() | |||||
| %> | |||||
| <!--#include file="../views/Home/index.asp" --> | |||||
| <% | |||||
| End Sub | |||||
| End Class | |||||
| Dim HomeController_Class__Singleton | |||||
| Function HomeController() | |||||
| If IsEmpty(HomeController_Class__Singleton) Then | |||||
| Set HomeController_Class__Singleton = New HomeController_Class | |||||
| End If | |||||
| Set HomeController = HomeController_Class__Singleton | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,3 @@ | |||||
| <!--#include file="HomeController.asp" --> | |||||
| <!--#include file="ErrorController.asp" --> | |||||
| <!--#include file="DocsController.asp" --> | |||||
| @@ -0,0 +1 @@ | |||||
| <% ' POBO and repository includes are appended here by scripts/gen.cmd (repo | api) %> | |||||
| @@ -0,0 +1,39 @@ | |||||
| <% | |||||
| ' One Swagger UI dropdown entry per public/api/*.openapi.json (scripts/gen.cmd api writes one per table) | |||||
| Dim specFso, specFolder, specFile, specUrls, specName | |||||
| Set specFso = Server.CreateObject("Scripting.FileSystemObject") | |||||
| specUrls = "" | |||||
| If specFso.FolderExists(Server.MapPath("/api")) Then | |||||
| Set specFolder = specFso.GetFolder(Server.MapPath("/api")) | |||||
| For Each specFile In specFolder.Files | |||||
| If LCase(Right(specFile.Name, 13)) = ".openapi.json" Then | |||||
| specName = Left(specFile.Name, Len(specFile.Name) - 13) | |||||
| If Len(specUrls) > 0 Then | |||||
| specUrls = specUrls & "," | |||||
| End If | |||||
| specUrls = specUrls & "{url:""/api/" & Server.HTMLEncode(specFile.Name) & """,name:""" & Server.HTMLEncode(specName) & """}" | |||||
| End If | |||||
| Next | |||||
| End If | |||||
| %> | |||||
| <% If Len(specUrls) = 0 Then %> | |||||
| <div class="alert alert-info"> | |||||
| No API specs yet. Generate one for a table with <code>scripts\gen.cmd api /table:<Table> /pk:Id</code> | |||||
| (it writes <code>public/api/<table>.openapi.json</code>), then reload this page. | |||||
| </div> | |||||
| <% Else %> | |||||
| <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" /> | |||||
| <div id="swagger-ui"></div> | |||||
| <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js"></script> | |||||
| <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js"></script> | |||||
| <script> | |||||
| window.ui = SwaggerUIBundle({ | |||||
| urls: [<%= specUrls %>], | |||||
| presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset], | |||||
| layout: "StandaloneLayout", // the spec dropdown (urls) only works with the standalone layout | |||||
| dom_id: "#swagger-ui", | |||||
| deepLinking: true, | |||||
| tryItOutEnabled: true | |||||
| }); | |||||
| </script> | |||||
| <% End If %> | |||||
| @@ -0,0 +1,55 @@ | |||||
| <div class="main-content"> | |||||
| <div class="d-flex align-items-center justify-content-center min-vh-100 bg-light"> | |||||
| <div class="card shadow-sm border-0 text-center p-4 p-md-5 error-card"> | |||||
| <div class="mb-3"> | |||||
| <i class="bi bi-exclamation-triangle-fill display-3 text-warning"></i> | |||||
| </div> | |||||
| <h1 class="h3 mb-3">404 - Page Not Found</h1> | |||||
| <p class="text-muted mb-3"> | |||||
| The page you’re looking for could not be found. It may have been moved, deleted, | |||||
| or the address might be incorrect. | |||||
| </p> | |||||
| <% | |||||
| Dim redirectSeconds : redirectSeconds = GetAppSetting("Error404RedirectSeconds") | |||||
| If redirectSeconds = "nothing" Or Not IsNumeric(redirectSeconds) Then redirectSeconds = 5 | |||||
| %> | |||||
| <p class="text-muted mb-3"> | |||||
| You'll be redirected to the homepage in | |||||
| <span id="countdown"><%= redirectSeconds %></span> seconds. | |||||
| </p> | |||||
| <a href="/" class="btn btn-primary mt-2"> | |||||
| Go to Homepage Now | |||||
| </a> | |||||
| </div> | |||||
| </div> | |||||
| </div> | |||||
| <style> | |||||
| .error-card { | |||||
| max-width: 540px; | |||||
| border-radius: 1rem; | |||||
| } | |||||
| .error-card .bi { | |||||
| line-height: 1; | |||||
| } | |||||
| </style> | |||||
| <script> | |||||
| (function () { | |||||
| let seconds = <%= redirectSeconds %>; | |||||
| const countdown = document.getElementById('countdown'); | |||||
| const timer = setInterval(function () { | |||||
| seconds--; | |||||
| if (countdown) { | |||||
| countdown.textContent = seconds; | |||||
| } | |||||
| if (seconds <= 0) { | |||||
| clearInterval(timer); | |||||
| window.location.href = '/'; | |||||
| } | |||||
| }, 1000); | |||||
| })(); | |||||
| </script> | |||||
| @@ -0,0 +1,85 @@ | |||||
| <div class="row mb-4"> | |||||
| <div class="col-lg-8"> | |||||
| <div class="card shadow-sm mb-3"> | |||||
| <div class="card-body"> | |||||
| <h1 class="h3 mb-3">Welcome to RouteKit Classic ASP</h1> | |||||
| <p class="text-muted"> | |||||
| Your lightweight, opinionated MVC-style framework for Classic ASP. | |||||
| </p> | |||||
| <p> | |||||
| This <code>Home.Index</code> view is using the shared | |||||
| <code>Header.asp</code> and <code>Footer.asp</code> layout files. | |||||
| </p> | |||||
| <p class="mb-0"> | |||||
| Start by wiring up your controllers, repositories, and views — this page is just a | |||||
| friendly placeholder so you know everything is hooked up correctly. | |||||
| </p> | |||||
| </div> | |||||
| </div> | |||||
| </div> | |||||
| <div class="col-lg-4"> | |||||
| <div class="card border-0 bg-light mb-3"> | |||||
| <div class="card-body"> | |||||
| <h2 class="h5 mb-3">Quick info</h2> | |||||
| <ul class="list-unstyled mb-0 small"> | |||||
| <li class="mb-1"> | |||||
| <strong>View:</strong> | |||||
| <code>app/Views/Home.Index.asp</code> | |||||
| </li> | |||||
| <li class="mb-1"> | |||||
| <strong>Layout:</strong> | |||||
| <code>Shared/Header.asp</code> & <code>Shared/Footer.asp</code> | |||||
| </li> | |||||
| <li class="mb-1"> | |||||
| <strong>Default route:</strong> | |||||
| typically <code>/Home/Index</code> or <code>/</code> via the dispatcher. | |||||
| </li> | |||||
| </ul> | |||||
| </div> | |||||
| </div> | |||||
| </div> | |||||
| </div> | |||||
| <div class="row gy-3"> | |||||
| <div class="col-md-4"> | |||||
| <div class="card h-100 shadow-sm"> | |||||
| <div class="card-body"> | |||||
| <h2 class="h5">Next step: Controllers</h2> | |||||
| <p class="small text-muted"> | |||||
| Use your <code>generateController.vbs</code> script to scaffold new controllers. | |||||
| </p> | |||||
| <pre class="small mb-0"><code>cscript //nologo Scripts\generateController.vbs ^ | |||||
| Home "Index"</code></pre> | |||||
| </div> | |||||
| </div> | |||||
| </div> | |||||
| <div class="col-md-4"> | |||||
| <div class="card h-100 shadow-sm"> | |||||
| <div class="card-body"> | |||||
| <h2 class="h5">POBO & Repository</h2> | |||||
| <p class="small text-muted"> | |||||
| Generate strongly-typed POBOs and repositories from your Access/SQL schema. | |||||
| </p> | |||||
| <pre class="small mb-0"><code>cscript //nologo Scripts\GenerateRepo.vbs ^ | |||||
| /table:Users /pk:UserId</code></pre> | |||||
| </div> | |||||
| </div> | |||||
| </div> | |||||
| <div class="col-md-4"> | |||||
| <div class="card h-100 shadow-sm"> | |||||
| <div class="card-body"> | |||||
| <h2 class="h5">Where to put stuff</h2> | |||||
| <ul class="small mb-0"> | |||||
| <li><code>/core/</code> – framework libs (DAL, routing, helpers)</li> | |||||
| <li><code>/app/Views/</code> – pages like this one</li> | |||||
| <li><code>/public/</code> – IIS root (Default.asp, web.config)</li> | |||||
| </ul> | |||||
| </div> | |||||
| </div> | |||||
| </div> | |||||
| </div> | |||||
| @@ -0,0 +1,8 @@ | |||||
| </div> | |||||
| </main> | |||||
| <!-- Bootstrap bundle (with Popper) --> | |||||
| <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script> | |||||
| </body> | |||||
| </html> | |||||
| @@ -0,0 +1,81 @@ | |||||
| <!doctype html> | |||||
| <% | |||||
| Response.Charset = "utf-8" | |||||
| Response.CodePage = 65001 | |||||
| ' Safe title resolution | |||||
| Dim pageTitle | |||||
| If IsObject(CurrentController) Then | |||||
| On Error Resume Next | |||||
| pageTitle = CurrentController.Title | |||||
| If Err.Number <> 0 Then | |||||
| pageTitle = "RouteKit Classic ASP" | |||||
| Err.Clear | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| End If | |||||
| If Len(pageTitle) = 0 Then pageTitle = "Classic ASP Starter Template" | |||||
| %> | |||||
| <html lang="en"> | |||||
| <head> | |||||
| <meta charset="utf-8" /> | |||||
| <title><%= pageTitle %></title> | |||||
| <meta name="viewport" content="width=device-width, initial-scale=1" /> | |||||
| <!-- Bootstrap CSS --> | |||||
| <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" /> | |||||
| <!-- Bootstrap Icons (optional) --> | |||||
| <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet" /> | |||||
| <!-- App CSS --> | |||||
| <link href="/css/site.css" rel="stylesheet" /> | |||||
| <style> | |||||
| body { | |||||
| background-color: #f5f5f5; | |||||
| } | |||||
| .rk-navbar-brand { | |||||
| font-weight: 600; | |||||
| letter-spacing: 0.03em; | |||||
| } | |||||
| main.routekit-main { | |||||
| padding-top: 1.5rem; | |||||
| padding-bottom: 2rem; | |||||
| } | |||||
| </style> | |||||
| </head> | |||||
| <body> | |||||
| <!-- Top navbar --> | |||||
| <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> | |||||
| <div class="container-fluid"> | |||||
| <a class="navbar-brand rk-navbar-brand" href="/"> | |||||
| Classic ASP | |||||
| <span class="text-secondary small">Starter</span> | |||||
| </a> | |||||
| <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#rkMainNav" aria-controls="rkMainNav" aria-expanded="false" aria-label="Toggle navigation"> | |||||
| <span class="navbar-toggler-icon"></span> | |||||
| </button> | |||||
| <div class="collapse navbar-collapse" id="rkMainNav"> | |||||
| <ul class="navbar-nav me-auto mb-2 mb-lg-0"> | |||||
| <li class="nav-item"> | |||||
| <a class="nav-link" href="/home">Home</a> | |||||
| </li> | |||||
| <li class="nav-item"> | |||||
| <a class="nav-link" href="/api/docs">API</a> | |||||
| </li> | |||||
| </ul> | |||||
| <%' Right-side area (e.g., user info / login). Wire this up to your auth later. %> | |||||
| <ul class="navbar-nav mb-2 mb-lg-0"></ul> | |||||
| </div> | |||||
| </div> | |||||
| </nav> | |||||
| <!-- Main container for views --> | |||||
| <main class="routekit-main"> | |||||
| <div class="container"> | |||||
| <% Flash().ShowErrorsIfPresent : Flash().ShowSuccessIfPresent %> | |||||
| @@ -0,0 +1,19 @@ | |||||
| <!--#include file="../core/helpers.asp"--> | |||||
| <!--#include file="../core/lib.ErrorHandler.asp"--> | |||||
| <!--#include file="../core/lib.ControllerRegistry.asp"--> | |||||
| <!--#include file="../core/mvc.asp"--> | |||||
| <!--#include file="../core/lib.DAL.asp"--> | |||||
| <!--#include file="../core/lib.Data.asp"--> | |||||
| <!--#include file="../core/lib.Migrations.asp"--> | |||||
| <!--#include file="../core/lib.Router.asp"--> | |||||
| <!--#include file="../core/lib.Collections.asp"--> | |||||
| <!--#include file="../core/lib.HTML.asp"--> | |||||
| <!--#include file="../core/lib.Routes.asp"--> | |||||
| <!--#include file="../core/lib.Flash.asp"--> | |||||
| <!--#include file="../core/lib.FormCache.asp"--> | |||||
| <!--#include file="../core/lib.HTML.Security.asp"--> | |||||
| <!--#include file="../core/lib.Automapper.asp"--> | |||||
| <!--#include file="../core/lib.helpers.asp"--> | |||||
| <!--#include file="../core/lib.crypto.helper.asp"--> | |||||
| <!--#include file="../core/lib.Enumerable.asp"--> | |||||
| <!--#include file="../core/lib.JsonLite.asp"--> | |||||
| @@ -0,0 +1,552 @@ | |||||
| <% | |||||
| Function QuoteValue(val) | |||||
| if IsWrappedInSingleQuotes(val) then | |||||
| QuoteValue = val | |||||
| Exit Function | |||||
| end if | |||||
| Select Case VarType(val) | |||||
| Case vbString | |||||
| QuoteValue = "'" & Replace(val, "'", "''") & "'" | |||||
| Case vbDate | |||||
| ' 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 | |||||
| ' Return boolean values without quotes | |||||
| QuoteValue = "'" & CStr(val) & "'" | |||||
| Case Else | |||||
| If IsNumeric(val) Then | |||||
| QuoteValue = CLng(val) | |||||
| Else | |||||
| QuoteValue = CStr(val) | |||||
| End If | |||||
| End Select | |||||
| End Function | |||||
| Public Function GetAppSetting(key) | |||||
| Dim cacheKey, xml, nodes, node, i | |||||
| cacheKey = "AppSetting_" & key | |||||
| ' Check Application cache first for performance | |||||
| If Not IsEmpty(Application(cacheKey)) Then | |||||
| GetAppSetting = Application(cacheKey) | |||||
| Exit Function | |||||
| End If | |||||
| ' Load from web.config only if not cached | |||||
| Set xml = Server.CreateObject("Microsoft.XMLDOM") | |||||
| ' 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) | |||||
| If node.getAttribute("key") = key Then | |||||
| GetAppSetting = node.getAttribute("value") | |||||
| ' Cache the value for subsequent requests | |||||
| Application.Lock | |||||
| Application(cacheKey) = GetAppSetting | |||||
| Application.Unlock | |||||
| Exit Function | |||||
| End If | |||||
| Next | |||||
| GetAppSetting = "nothing" | |||||
| End Function | |||||
| Public Sub ShowServerVariables | |||||
| Dim varName, htmlTable | |||||
| htmlTable = "<table border='1' cellspacing='0' cellpadding='5'>" | |||||
| htmlTable = htmlTable & "<thead><tr><th>Variable Name</th><th>Value</th></tr></thead><tbody>" | |||||
| ' Loop through all server variables | |||||
| For Each varName In Request.ServerVariables | |||||
| htmlTable = htmlTable & "<tr>" | |||||
| htmlTable = htmlTable & "<td>" & Server.HTMLEncode(varName) & "</td>" | |||||
| htmlTable = htmlTable & "<td>" & Server.HTMLEncode(Request.ServerVariables(varName)) & "</td>" | |||||
| htmlTable = htmlTable & "</tr>" | |||||
| Next | |||||
| htmlTable = htmlTable & "</tbody></table>" | |||||
| ' Output the HTML table | |||||
| Response.Write(htmlTable) | |||||
| End Sub | |||||
| '------------------------------------------------------------------------------ | |||||
| ' Utility: IIf Function for VBScript | |||||
| ' Usage: result = IIf(condition, trueValue, falseValue) | |||||
| '------------------------------------------------------------------------------ | |||||
| Function IIf(condition, trueValue, falseValue) | |||||
| On Error Resume Next | |||||
| If CBool(condition) Then | |||||
| IIf = trueValue | |||||
| Else | |||||
| IIf = falseValue | |||||
| End If | |||||
| If Err.Number <> 0 Then | |||||
| ' Optional: handle or log error in conversion/evaluation | |||||
| Err.Clear | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| End Function | |||||
| '----------------------------- | |||||
| ' Utility: Generic Error Reporter | |||||
| '----------------------------- | |||||
| Public Sub ErrorCheck(context) | |||||
| If Err.Number <> 0 Then | |||||
| Dim errHtml | |||||
| errHtml = "<div style='padding:10px; border:2px solid red; background:#fdd; font-family:Verdana; font-size:12px;'>" | |||||
| errHtml = errHtml & "<strong>Error occurred" & IIf(Not IsEmpty(context) And context <> "", ": " & context, "") & "</strong><br />" | |||||
| errHtml = errHtml & "<em>Time:</em> " & Now() & "<br />" | |||||
| errHtml = errHtml & "<em>Number:</em> " & Err.Number & "<br />" | |||||
| errHtml = errHtml & "<em>Description:</em> " & Server.HTMLEncode(Err.Description) & "<br />" | |||||
| If Len(Err.Source) > 0 Then | |||||
| errHtml = errHtml & "<em>Source:</em> " & Server.HTMLEncode(Err.Source) & "<br />" | |||||
| End If | |||||
| errHtml = errHtml & "</div>" | |||||
| Response.Write errHtml | |||||
| Err.Clear | |||||
| End If | |||||
| End Sub | |||||
| '------------------------------------------------------------------------------ | |||||
| ' Utility: TrimQueryParams | |||||
| ' Removes everything from the first "?" or "&" onward. | |||||
| ' Usage: | |||||
| ' CleanPath = TrimQueryParams(rawPath) | |||||
| '------------------------------------------------------------------------------ | |||||
| Function TrimQueryParams(rawPath) | |||||
| Dim posQ, posA, cutPos | |||||
| rawPath = "" & rawPath | |||||
| ' find the first occurrences of "?" and "&" | |||||
| posQ = InStr(rawPath, "?") | |||||
| posA = InStr(rawPath, "&") | |||||
| ' determine the earliest cut position (>0) | |||||
| If posQ > 0 And posA > 0 Then | |||||
| If posQ < posA Then | |||||
| cutPos = posQ | |||||
| Else | |||||
| cutPos = posA | |||||
| End If | |||||
| ElseIf posQ > 0 Then | |||||
| cutPos = posQ | |||||
| ElseIf posA > 0 Then | |||||
| cutPos = posA | |||||
| Else | |||||
| cutPos = 0 | |||||
| End If | |||||
| ' if found, return up to just before that char | |||||
| If cutPos > 0 Then | |||||
| TrimQueryParams = Left(rawPath, cutPos - 1) | |||||
| Else | |||||
| 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 | |||||
| on error resume next | |||||
| o.close | |||||
| on error goto 0 | |||||
| set o = nothing | |||||
| end if | |||||
| end if | |||||
| End Sub | |||||
| Sub puts(v) | |||||
| Select Case typename(v) | |||||
| Case "LinkedList_Class" : response.write join(v.TO_Array, ", ") | |||||
| Case "DynamicArray_Class" : response.write JoinList(v) | |||||
| Case "Variant()" : response.write join(v, ", ") | |||||
| Case else : response.write v | |||||
| End Select | |||||
| End Sub | |||||
| Sub puts_ | |||||
| puts "<br>" | |||||
| End Sub | |||||
| Sub putl(v) | |||||
| puts v | |||||
| puts_ | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| 'Wrapper for Server.HTMLEncode() -- makes it easier on the eyes when reading the HTML code | |||||
| Function H(s) | |||||
| If Not IsEmpty(s) and Not IsNull(s) then | |||||
| H = Server.HTMLEncode(s) | |||||
| Else | |||||
| H = "" | |||||
| End If | |||||
| End Function | |||||
| '======================================================================================================================= | |||||
| ' Adapted from Tolerable library | |||||
| '======================================================================================================================= | |||||
| ' This subroutine allows us to ignore the difference | |||||
| ' between object and primitive assignments. This is | |||||
| ' essential for many parts of the engine. | |||||
| Public Sub Assign(ByRef var, ByVal val) | |||||
| If IsObject(val) Then | |||||
| Set var = val | |||||
| Else | |||||
| var = val | |||||
| End If | |||||
| End Sub | |||||
| ' This is similar to the ? : operator of other languages. | |||||
| ' Unfortunately, both the if_true and if_false "branches" | |||||
| ' will be evalauted before the condition is even checked. So, | |||||
| ' you'll only want to use this for simple expressions. | |||||
| Public Function Choice(ByVal cond, ByVal if_true, ByVal if_false) | |||||
| If cond Then | |||||
| Assign Choice, if_true | |||||
| Else | |||||
| Assign Choice, if_false | |||||
| End If | |||||
| End Function | |||||
| ' Allows single-quotes to be used in place of double-quotes. | |||||
| ' Basically, this is a cheap trick that can make it easier | |||||
| ' to specify Lambdas. | |||||
| Public Function Q(ByVal input) | |||||
| Q = Replace(input, "'", """") | |||||
| End Function | |||||
| Function SurroundString(inputVar) | |||||
| If VarType(inputVar) = vbString Then | |||||
| SurroundString = """" & inputVar & """" | |||||
| Else | |||||
| SurroundString = inputVar | |||||
| End If | |||||
| End Function | |||||
| Function SurroundStringInArray(arr) | |||||
| Dim i | |||||
| For i = LBound(arr) To UBound(arr) | |||||
| If IsString(arr(i)) Then | |||||
| ' 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 | |||||
| End Function | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| 'Boolean type checkers | |||||
| 'Don't forget IsArray is built-in! | |||||
| Function IsString(value) | |||||
| IsString = Choice(typename(value) = "String", true, false) | |||||
| End Function | |||||
| Function IsDict(value) | |||||
| IsDict = Choice(typename(value) = "Dictionary", true, false) | |||||
| End Function | |||||
| Function IsRecordset(value) | |||||
| IsRecordset = Choice(typename(value) = "Recordset", true, false) | |||||
| End Function | |||||
| Function IsLinkedList(value) | |||||
| IsLinkedList = Choice(typename(value) = "LinkedList_Class", true, false) | |||||
| End Function | |||||
| Function IsArray(value) | |||||
| IsArray = Choice(typename(value) = "Variant()", true, false) | |||||
| End Function | |||||
| '-------------------------------------------------------------------- | |||||
| ' Returns True when the named key is present in Session.Contents | |||||
| ' • Handles scalars (String, Integer, etc.), objects, Empty, and Null | |||||
| '-------------------------------------------------------------------- | |||||
| Function SessionHasKey(keyName) | |||||
| 'Loop over the existing keys—Session.Contents is like a dictionary | |||||
| Dim k | |||||
| For Each k In Session.Contents | |||||
| If StrComp(k, keyName, vbTextCompare) = 0 Then | |||||
| SessionHasKey = True | |||||
| Exit Function | |||||
| End If | |||||
| Next | |||||
| SessionHasKey = False 'not found | |||||
| End Function | |||||
| Function RenderObjectsAsTable(arr,boolUseTabulator) | |||||
| Dim html, propNames, i, j, obj, val, pkName, isPk | |||||
| If IsEmpty(arr) Or Not IsArray(arr) Then | |||||
| RenderObjectsAsTable = "<!-- no data -->" | |||||
| Exit Function | |||||
| End If | |||||
| Set obj = arr(0) | |||||
| On Error Resume Next | |||||
| propNames = obj.Properties | |||||
| pkName = obj.PrimaryKey | |||||
| On Error GoTo 0 | |||||
| If IsEmpty(propNames) Or Len(pkName) = 0 Then | |||||
| RenderObjectsAsTable = "<!-- missing properties or primary key -->" | |||||
| Exit Function | |||||
| End If | |||||
| html = "<div class='table-wrapper'>" & vbCrLf | |||||
| html = html & "<table class='pobo-table' id='pobo-table'>" & vbCrLf | |||||
| html = html & " <thead><tr>" & vbCrLf | |||||
| For i = 0 To UBound(propNames) | |||||
| html = html & " <th>" & Server.HTMLEncode(propNames(i)) & "</th>" & vbCrLf | |||||
| Next | |||||
| html = html & " </tr></thead>" & vbCrLf | |||||
| html = html & " <tbody>" & vbCrLf | |||||
| For j = 0 To UBound(arr) | |||||
| Set obj = arr(j) | |||||
| html = html & " <tr>" & vbCrLf | |||||
| For i = 0 To UBound(propNames) | |||||
| val = GetDynamicProperty(obj, propNames(i)) | |||||
| isPk = (StrComp(propNames(i), pkName, vbTextCompare) = 0) | |||||
| If IsNull(val) Or IsEmpty(val) Then | |||||
| val = " " | |||||
| ElseIf IsDate(val) Then | |||||
| val = FormatDateTime(val, vbShortDate) | |||||
| ElseIf VarType(val) = vbBoolean Then | |||||
| val = IIf(val, "True", "False") | |||||
| Else | |||||
| val = CStr(val) | |||||
| Dim maxLen : maxLen = CInt(GetAppSetting("TableCellMaxLength")) | |||||
| If maxLen <= 0 Then maxLen = 90 | |||||
| If Len(val) > maxLen Then | |||||
| val = Left(val, maxLen - 3) & "..." | |||||
| End If | |||||
| val = Server.HTMLEncode(val) | |||||
| End If | |||||
| If isPk and boolUseTabulator = False Then | |||||
| val = "<a href=""" & obj.Tablename & "/edit/" & GetDynamicProperty(obj, pkName) & """ class=""table-link"">" & val & "</a>" | |||||
| End If | |||||
| html = html & " <td>" & val & "</td>" & vbCrLf | |||||
| Next | |||||
| html = html & " </tr>" & vbCrLf | |||||
| Next | |||||
| html = html & " </tbody>" & vbCrLf & "</table>" & vbCrLf & "</div>" | |||||
| RenderObjectsAsTable = html | |||||
| End Function | |||||
| Function RenderFormFromObject(obj) | |||||
| Dim html, propNames, i, name, val, inputType | |||||
| Dim pkName, tableName, checkedAttr | |||||
| On Error Resume Next | |||||
| propNames = obj.Properties | |||||
| pkName = obj.PrimaryKey | |||||
| tableName = obj.TableName | |||||
| On Error GoTo 0 | |||||
| If IsEmpty(propNames) Or Len(pkName) = 0 Then | |||||
| RenderFormFromObject = "<!-- Invalid object -->" | |||||
| Exit Function | |||||
| End If | |||||
| html = "<form method='post' action='/" & tableName & "/save' class='article-content'>" & vbCrLf | |||||
| For i = 0 To UBound(propNames) | |||||
| name = propNames(i) | |||||
| val = GetDynamicProperty(obj, name) | |||||
| ' Handle nulls | |||||
| If IsNull(val) Then val = "" | |||||
| ' Primary key → hidden input | |||||
| If StrComp(name, pkName, vbTextCompare) = 0 Then | |||||
| html = html & " <input type='hidden' name='" & name & "' value='" & Server.HTMLEncode(val) & "' />" & vbCrLf | |||||
| 'Continue For | |||||
| End If | |||||
| html = html & " <div class='form-group'>" & vbCrLf | |||||
| html = html & " <label for='" & name & "'>" & name & "</label>" & vbCrLf | |||||
| Select Case True | |||||
| Case VarType(val) = vbBoolean | |||||
| checkedAttr = "" | |||||
| If val = True Then checkedAttr = " checked" | |||||
| html = html & " <input type='checkbox' class='form-check-input' name='" & name & "' id='" & name & "' value='true'" & checkedAttr & " />" & vbCrLf | |||||
| Case IsDate(val) | |||||
| html = html & " <input type='date' class='form-control' name='" & name & "' id='" & name & "' value='" & FormatDateForInput(val) & "' />" & vbCrLf | |||||
| Case IsNumeric(val) | |||||
| html = html & " <input type='number' class='form-control' name='" & name & "' id='" & name & "' value='" & val & "' />" & vbCrLf | |||||
| Case Len(val) > CInt(GetAppSetting("FormTextareaThreshold")) | |||||
| html = html & " <textarea class='form-control' name='" & name & "' id='" & name & "' rows='6'>" & Server.HTMLEncode(val) & "</textarea>" & vbCrLf | |||||
| Case Else | |||||
| html = html & " <input type='text' class='form-control' name='" & name & "' id='" & name & "' value='" & Server.HTMLEncode(val) & "' />" & vbCrLf | |||||
| End Select | |||||
| html = html & " </div>" & vbCrLf | |||||
| Next | |||||
| html = html & " <button type='submit' class='btn btn-primary btn-lg'>Save</button>" & vbCrLf | |||||
| html = html & "</form>" & vbCrLf | |||||
| RenderFormFromObject = html | |||||
| End Function | |||||
| Function GetDynamicProperty(obj, propName) | |||||
| On Error Resume Next | |||||
| Dim result | |||||
| Execute "result = obj." & propName | |||||
| If Err.Number <> 0 Then | |||||
| result = "" | |||||
| Err.Clear | |||||
| End If | |||||
| GetDynamicProperty = result | |||||
| On Error GoTo 0 | |||||
| End Function | |||||
| Function FormatDateForInput(val) | |||||
| If IsDate(val) Then | |||||
| Dim yyyy, mm, dd | |||||
| yyyy = Year(val) | |||||
| mm = Right("0" & Month(val), 2) | |||||
| dd = Right("0" & Day(val), 2) | |||||
| FormatDateForInput = yyyy & "-" & mm & "-" & dd | |||||
| Else | |||||
| FormatDateForInput = "" | |||||
| End If | |||||
| End Function | |||||
| '------------------------------------------------------------- | |||||
| ' Returns obj.<propName> for any public VBScript class property | |||||
| '------------------------------------------------------------- | |||||
| Function GetObjProp(o, pName) | |||||
| Dim tmp | |||||
| ' Build a tiny statement like: tmp = o.UserID | |||||
| Execute "tmp = o." & pName | |||||
| GetObjProp = tmp | |||||
| End Function | |||||
| Function GenerateSlug(title) | |||||
| Dim slug | |||||
| slug = LCase(title) ' Convert to lowercase | |||||
| slug = Replace(slug, "&", "and") ' Replace ampersands | |||||
| slug = Replace(slug, "'", "") ' Remove apostrophes | |||||
| slug = Replace(slug, """", "") ' Remove quotes | |||||
| slug = Replace(slug, "–", "-") ' Replace en dash | |||||
| slug = Replace(slug, "—", "-") ' Replace em dash | |||||
| slug = Replace(slug, "/", "-") ' Replace slashes | |||||
| slug = Replace(slug, "\", "-") ' Replace backslashes | |||||
| ' Remove all non-alphanumeric and non-hyphen/space characters | |||||
| Dim i, ch, clean | |||||
| clean = "" | |||||
| For i = 1 To Len(slug) | |||||
| ch = Mid(slug, i, 1) | |||||
| If (ch >= "a" And ch <= "z") Or (ch >= "0" And ch <= "9") Or ch = " " Or ch = "-" Then | |||||
| clean = clean & ch | |||||
| End If | |||||
| Next | |||||
| ' Replace multiple spaces or hyphens with single hyphen | |||||
| Do While InStr(clean, " ") > 0 | |||||
| clean = Replace(clean, " ", " ") | |||||
| Loop | |||||
| clean = Replace(clean, " ", "-") | |||||
| Do While InStr(clean, "--") > 0 | |||||
| clean = Replace(clean, "--", "-") | |||||
| Loop | |||||
| ' Trim leading/trailing hyphens | |||||
| Do While Left(clean, 1) = "-" | |||||
| clean = Mid(clean, 2) | |||||
| Loop | |||||
| Do While Right(clean, 1) = "-" | |||||
| clean = Left(clean, Len(clean) - 1) | |||||
| Loop | |||||
| GenerateSlug = clean | |||||
| End Function | |||||
| Function GetRawJsonFromRequest() | |||||
| Dim stream, rawJson | |||||
| Set stream = Server.CreateObject("ADODB.Stream") | |||||
| stream.Type = 1 ' adTypeBinary | |||||
| stream.Open | |||||
| stream.Write Request.BinaryRead(Request.TotalBytes) | |||||
| stream.Position = 0 | |||||
| stream.Type = 2 ' adTypeText | |||||
| stream.Charset = "utf-8" | |||||
| rawJson = stream.ReadText | |||||
| stream.Close | |||||
| Set stream = Nothing | |||||
| GetRawJsonFromRequest = rawJson | |||||
| End Function | |||||
| Function Active(controllerName) | |||||
| On Error Resume Next | |||||
| If Replace(Lcase(GetRouter().Resolve(Request.ServerVariables("REQUEST_METHOD"), GetRequestPath())(0)),"controller","") = LCase(controllerName) Then | |||||
| Active = "active" | |||||
| Else | |||||
| Active = "" | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| End Function | |||||
| '==================================================================== | |||||
| ' FormatDateForSql | |||||
| ' Converts a VBScript Date to a SQL Server-compatible string | |||||
| ' Output: 'YYYY-MM-DD HH:MM:SS' | |||||
| '==================================================================== | |||||
| Function FormatDateForSql(vbDate) | |||||
| If IsNull(vbDate) Or vbDate = "" Then | |||||
| FormatDateForSql = "NULL" | |||||
| Exit Function | |||||
| End If | |||||
| ' Ensure vbDate is a valid date | |||||
| If Not IsDate(vbDate) Then | |||||
| Err.Raise vbObjectError + 1000, "FormatDateForSql", "Invalid date: " & vbDate | |||||
| End If | |||||
| Dim yyyy, mm, dd, hh, nn, ss | |||||
| yyyy = Year(vbDate) | |||||
| mm = Right("0" & Month(vbDate), 2) | |||||
| dd = Right("0" & Day(vbDate), 2) | |||||
| hh = Right("0" & Hour(vbDate), 2) | |||||
| nn = Right("0" & Minute(vbDate), 2) | |||||
| ss = Right("0" & Second(vbDate), 2) | |||||
| ' Construct SQL Server datetime literal | |||||
| FormatDateForSql = "'" & yyyy & "-" & mm & "-" & dd & " " & hh & ":" & nn & ":" & ss & "'" | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,159 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' AUTOMAPPER CLASS | |||||
| '======================================================================================================================= | |||||
| 'Side Effects: Since src and target are passed ByRef to reduce unnecessary copying, if src is a recordset then the | |||||
| ' current record pointer is modified using src.MoveFirst and src.MoveNext. The end result is the current | |||||
| ' record pointer ends the operation at src.EOF. | |||||
| Class Automapper_Class | |||||
| Private m_src | |||||
| Private m_target | |||||
| Private m_statements | |||||
| Private m_statements_count | |||||
| Private Property Get Src : set Src = m_src : End Property | |||||
| Private Property Get Target : set Target = m_target : End Property | |||||
| Private Sub Class_Initialize | |||||
| m_statements_count = -1 | |||||
| ReDim m_statements(-1) | |||||
| End Sub | |||||
| Private Sub ResetState | |||||
| m_statements_count = -1 | |||||
| ReDim m_statements(-1) | |||||
| Set m_src = Nothing | |||||
| Set m_target = Nothing | |||||
| End Sub | |||||
| 'Maps all rs or object fields to corresponding fields in the specified class. | |||||
| Public Function AutoMap(src_obj, target_obj) | |||||
| Set AutoMap = FlexMap(src_obj, target_obj, empty) | |||||
| End Function | |||||
| 'Only maps fields specified in the field_names array (array of strings). | |||||
| 'If field_names is empty, attempts to map all fields from the passed rs or object. | |||||
| Public Function FlexMap(src_obj, target_obj, field_names) | |||||
| Set FlexMap = DynMap(src_obj, target_obj, field_names, empty) | |||||
| End Function | |||||
| 'Only maps fields specified in the field_names array (array of strings). | |||||
| 'If field_names is empty then src MUST be a recordset as it attempts to map all fields from the recordset. | |||||
| 'Since there is no reflection in vbscript, there is no way around this short of pseudo-reflection. | |||||
| Public Function DynMap(src_obj, target_obj, field_names, exprs) | |||||
| SetSource src_obj | |||||
| SetTarget target_obj | |||||
| dim field_name | |||||
| dim field_idx 'loop counter | |||||
| if IsEmpty(field_names) then 'map everything | |||||
| if typename(src_obj) = "Recordset" then | |||||
| for field_idx = 0 to src_obj.Fields.Count - 1 | |||||
| field_name = src_obj.Fields.Item(field_idx).Name | |||||
| 'AddStatement field_name | |||||
| AddStatement BuildStatement(field_name) | |||||
| next | |||||
| elseif InStr(typename(src_obj), "Dictionary") > 0 then 'enables Scripting.Dictionary and IRequestDictionary for Request.Querystring and Request.Form | |||||
| for each field_name in src_obj | |||||
| AddStatement BuildStatement(field_name) | |||||
| next | |||||
| elseif not IsEmpty(src_obj.Class_Get_Properties) then | |||||
| dim props : props = src_obj.Class_Get_Properties | |||||
| for field_idx = 0 to ubound(props) | |||||
| field_name = props(field_idx) | |||||
| 'AddStatement field_name | |||||
| AddStatement BuildStatement(field_name) | |||||
| next | |||||
| else 'some invalid type of object | |||||
| Err.Raise 9, "Automapper.DynMap", "Cannot automatically map this source object. Expected recordset or object implementing Class_Get_Properties reflection, got: " & typename(src_obj) | |||||
| end if | |||||
| else 'map only specified fields | |||||
| for field_idx = lbound(field_names) to ubound(field_names) | |||||
| field_name = field_names(field_idx) | |||||
| 'AddStatement field_name | |||||
| AddStatement BuildStatement(field_name) | |||||
| next | |||||
| end if | |||||
| dim exprs_idx | |||||
| if not IsEmpty(exprs) then | |||||
| if typename(exprs) = "Variant()" then | |||||
| for exprs_idx = lbound(exprs) to ubound(exprs) | |||||
| 'field_name = exprs(exprs_idx) | |||||
| 'AddStatement field_name | |||||
| AddStatement exprs(exprs_idx) | |||||
| next | |||||
| else 'assume string or string-like default value | |||||
| AddStatement exprs | |||||
| end if | |||||
| end if | |||||
| 'Can't pre-join the statements because if one fails the rest of them fail too... :( | |||||
| 'dim joined_statements : joined_statements = Join(m_statements, " : ") | |||||
| 'put joined_statements | |||||
| 'suspend errors to prevent failing when attempting to map a field that does not exist in the class | |||||
| on error resume next | |||||
| dim stmt_idx | |||||
| for stmt_idx = 0 to ubound(m_statements) | |||||
| Execute m_statements(stmt_idx) | |||||
| next | |||||
| on error goto 0 | |||||
| set DynMap = m_target | |||||
| ResetState | |||||
| End Function | |||||
| Private Sub SetSource(ByVal src_obj) | |||||
| set m_src = src_obj | |||||
| End Sub | |||||
| Private Sub SetTarget(ByVal target_obj) | |||||
| if typename(target_obj) = "String" then | |||||
| set m_target = eval("new " & target_obj) | |||||
| else | |||||
| set m_target = target_obj | |||||
| end if | |||||
| End Sub | |||||
| 'Builds a statement and adds it to the internal statements array | |||||
| Private Sub AddStatement(ByVal stmt) | |||||
| m_statements_count = m_statements_count + 1 | |||||
| ReDim Preserve m_statements(m_statements_count) | |||||
| m_statements(m_statements_count) = stmt | |||||
| End Sub | |||||
| Private Function BuildStatement(ByVal field_name) | |||||
| dim result | |||||
| if typename(m_src) = "Recordset" or InStr(typename(m_src), "Dictionary") > 0 then | |||||
| result = "m_target." & field_name & " = m_src(""" & field_name & """)" | |||||
| else | |||||
| 'Funky magic... | |||||
| 'If src.field_name is an object, ensure the set statement is used | |||||
| if IsObject(eval("m_src." & field_name)) then | |||||
| result = "set " | |||||
| else | |||||
| 'result = "m_target." & field_name & " = m_src." & field_name | |||||
| end if | |||||
| result = result & " m_target." & field_name & " = m_src." & field_name | |||||
| end if | |||||
| BuildStatement = result | |||||
| End Function | |||||
| End Class | |||||
| Function Automapper() | |||||
| Set Automapper = new Automapper_Class | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,914 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' KVArray | |||||
| ' Relatively painless implementation of key/value pair arrays without requiring a full Scripting.Dictionary COM instance. | |||||
| ' A KVArray is a standard array where element i is the key and element i+1 is the value. Loops must step by 2. | |||||
| '======================================================================================================================= | |||||
| 'given a KVArray and key index, returns the key and value | |||||
| 'pre: kv_array has at least key_idx and key_idx + 1 values | |||||
| 'post: key and val are populated | |||||
| Sub KeyVal(kv_array, key_idx, ByRef key, ByRef val) | |||||
| if (key_idx + 1 > ubound(kv_array)) then err.raise 1, "KeyVal", "expected key_idx < " & ubound(kv_array) - 1 & ", got: " & key_idx | |||||
| key = kv_array(key_idx) | |||||
| val = kv_array(key_idx + 1) | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| 'Given a KVArray, a key and a value, appends the key and value to the end of the KVArray | |||||
| Sub KVAppend(ByRef kv_array, key, val) | |||||
| dim i : i = ubound(kv_array) | |||||
| redim preserve kv_array(i + 2) | |||||
| kv_array(i + 1) = key | |||||
| kv_array(i + 2) = val | |||||
| End Sub | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| 'Given a KVArray and two variants, populates the first variant with all keys and the second variant with all values. | |||||
| 'If | |||||
| 'Pre: kv_array has at least key_idx and key_idx + 1 values | |||||
| 'Post: key_array contains all keys in kvarray. | |||||
| ' val_array contains all values in kvarray. | |||||
| ' key_array and val_array values are in corresponding order, i.e. key_array(i) corresponds to val_array(i). | |||||
| Sub KVUnzip(kv_array, key_array, val_array) | |||||
| dim kv_array_size : kv_array_size = ubound(kv_array) | |||||
| dim num_pairs : num_pairs = (kv_array_size + 1) / 2 | |||||
| dim result_array_size : result_array_size = num_pairs - 1 | |||||
| 'Extend existing key_array or create new array to hold the keys | |||||
| If IsArray(key_array) then | |||||
| redim preserve key_array(ubound(key_array) + result_array_size) | |||||
| Else | |||||
| key_array = Array() | |||||
| redim key_array(result_array_size) | |||||
| End If | |||||
| 'Extend existing val array or create new array to hold the values | |||||
| If IsArray(val_array) then | |||||
| redim preserve val_array(ubound(val_array) + result_array_size) | |||||
| Else | |||||
| val_array = Array() | |||||
| redim val_array(num_pairs - 1) | |||||
| End If | |||||
| 'Unzip the KVArray into the two output arrays | |||||
| dim i, key, val | |||||
| dim key_val_arrays_idx : key_val_arrays_idx = 0 ' used to sync loading the key_array and val_array | |||||
| For i = 0 to ubound(kv_array) step 2 | |||||
| KeyVal kv_array, i, key, val | |||||
| key_array(key_val_arrays_idx) = key | |||||
| val_array(key_val_arrays_idx) = val | |||||
| key_val_arrays_idx = key_val_arrays_idx + 1 ' increment by 1 because loop goes to next pair in kv_array | |||||
| Next | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| 'Given a KVArray, dumps it to the screen. Useful for debugging purposes. | |||||
| Sub DumpKVArray(kv_array) | |||||
| dim i, key, val | |||||
| For i = 0 to ubound(kv_array) step 2 | |||||
| KeyVal kv_array, i, key, val | |||||
| puts key & " => " & val & "<br>" | |||||
| Next | |||||
| End Sub | |||||
| '======================================================================================================================= | |||||
| ' Pair Class | |||||
| ' Holds a pair of values, i.e. a key value pair, recordset field name/value pair, etc. | |||||
| ' Similar to the C++ STL std::pair class. Useful for some iteration and the like. | |||||
| ' | |||||
| ' This was an interesting idea but so far has not really been used, oh well...... | |||||
| '======================================================================================================================= | |||||
| Class Pair_Class | |||||
| Private m_first, m_second | |||||
| Public Property Get First : First = m_first : End Property | |||||
| Public Property Get [Second] : [Second] = m_second : End Property | |||||
| Public Default Property Get TO_String | |||||
| TO_String = First & " " & [Second] | |||||
| End Property | |||||
| Public Sub Initialize(ByVal firstval, ByVal secondval) | |||||
| Assign m_first, firstval | |||||
| Assign m_second, secondval | |||||
| End Sub | |||||
| 'Swaps the two values | |||||
| Public Sub Swap | |||||
| dim tmp | |||||
| Assign tmp, m_second | |||||
| Assign m_second, m_first | |||||
| Assign m_first, tmp | |||||
| End Sub | |||||
| End Class | |||||
| Function MakePair(ByVal firstval, ByVal secondval) | |||||
| dim P : set P = new Pair_Class | |||||
| P.Initialize firstval, secondval | |||||
| set MakePair = P | |||||
| End Function | |||||
| '======================================================================================================================= | |||||
| ' Linked List - From the Tolerable lib | |||||
| '======================================================================================================================= | |||||
| ' This is just here for reference | |||||
| Class Iterator_Class | |||||
| Public Function HasNext() | |||||
| End Function | |||||
| Public Function PeekNext() | |||||
| End Function | |||||
| Public Function GetNext() | |||||
| End Function | |||||
| Public Function HasPrev() | |||||
| End Function | |||||
| Public Function PeekPrev() | |||||
| End Function | |||||
| Public Function GetPrev() | |||||
| End Function | |||||
| End Class | |||||
| Class Enumerator_Source_Iterator_Class | |||||
| Private m_iter | |||||
| Public Sub Initialize(ByVal iter) | |||||
| Set m_iter = iter | |||||
| End Sub | |||||
| Private Sub Class_Terminate() | |||||
| Set m_iter = Nothing | |||||
| End Sub | |||||
| Public Sub GetNext(ByRef retval, ByRef successful) | |||||
| If m_iter.HasNext Then | |||||
| Assign retval, m_iter.GetNext | |||||
| successful = True | |||||
| Else | |||||
| successful = False | |||||
| End If | |||||
| End Sub | |||||
| End Class | |||||
| Public Function En_Iterator(ByVal iter) | |||||
| Dim retval | |||||
| Set retval = New Enumerator_Source_Iterator_Class | |||||
| retval.Initialize iter | |||||
| Set En_Iterator = Enumerator(retval) | |||||
| End Function | |||||
| Class LinkedList_Node_Class | |||||
| Public m_prev | |||||
| Public m_next | |||||
| Public m_value | |||||
| Private Sub Class_Initialize() | |||||
| Set m_prev = Nothing | |||||
| Set m_next = Nothing | |||||
| End Sub | |||||
| Private Sub Class_Terminate() | |||||
| Set m_prev = Nothing | |||||
| Set m_next = Nothing | |||||
| Set m_value = Nothing | |||||
| End Sub | |||||
| Public Sub SetValue(ByVal value) | |||||
| Assign m_value, value | |||||
| End Sub | |||||
| End Class | |||||
| Class Iterator_LinkedList_Class | |||||
| Private m_left | |||||
| Private m_right | |||||
| Public Sub Initialize(ByVal r) | |||||
| Set m_left = Nothing | |||||
| Set m_right = r | |||||
| End Sub | |||||
| Private Sub Class_Terminate() | |||||
| Set m_Left = Nothing | |||||
| Set m_Right = Nothing | |||||
| End Sub | |||||
| Public Function HasNext() | |||||
| HasNext = Not(m_right Is Nothing) | |||||
| End Function | |||||
| Public Function PeekNext() | |||||
| Assign PeekNext, m_right.m_value | |||||
| End Function | |||||
| Public Function GetNext() | |||||
| Assign GetNext, m_right.m_value | |||||
| Set m_left = m_right | |||||
| Set m_right = m_right.m_next | |||||
| End Function | |||||
| Public Function HasPrev() | |||||
| HasPrev = Not(m_left Is Nothing) | |||||
| End Function | |||||
| Public Function PeekPrev() | |||||
| Assign PeekPrev, m_left.m_value | |||||
| End Function | |||||
| Public Function GetPrev() | |||||
| Assign GetPrev, m_left.m_value | |||||
| Set m_right = m_left | |||||
| Set m_left = m_left.m_prev | |||||
| End Function | |||||
| End Class | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| Class LinkedList_Class | |||||
| Private m_first | |||||
| Private m_last | |||||
| Private m_size | |||||
| Private Sub Class_Initialize() | |||||
| Me.Reset | |||||
| End Sub | |||||
| Private Sub Class_Terminate() | |||||
| Me.Reset | |||||
| End Sub | |||||
| Public Function Clear() | |||||
| Set m_first = Nothing | |||||
| Set m_last = Nothing | |||||
| m_size = 0 | |||||
| Set Clear = Me | |||||
| End Function | |||||
| Private Function NewNode(ByVal value) | |||||
| Dim retval | |||||
| Set retval = New LinkedList_Node_Class | |||||
| retval.SetValue value | |||||
| Set NewNode = retval | |||||
| End Function | |||||
| Public Sub Reset() | |||||
| Set m_first = Nothing | |||||
| Set m_last = Nothing | |||||
| m_size = 0 | |||||
| End Sub | |||||
| Public Function IsEmpty() | |||||
| IsEmpty = (m_last Is Nothing) | |||||
| End Function | |||||
| Public Property Get Count | |||||
| Count = m_size | |||||
| End Property | |||||
| 'I just like .Size better than .Count sometimes, sue me | |||||
| Public Property Get Size | |||||
| Size = m_size | |||||
| End Property | |||||
| Public Function Iterator() | |||||
| Dim retval | |||||
| Set retval = New Iterator_LinkedList_Class | |||||
| retval.Initialize m_first | |||||
| Set Iterator = retval | |||||
| End Function | |||||
| Public Function Push(ByVal value) | |||||
| Dim temp | |||||
| Set temp = NewNode(value) | |||||
| If Me.IsEmpty Then | |||||
| Set m_first = temp | |||||
| Set m_last = temp | |||||
| Else | |||||
| Set temp.m_prev = m_last | |||||
| Set m_last.m_next = temp | |||||
| Set m_last = temp | |||||
| End If | |||||
| m_size = m_size + 1 | |||||
| Set Push = Me | |||||
| End Function | |||||
| Public Function Peek() | |||||
| ' TODO: Error handling | |||||
| Assign Peek, m_last.m_value | |||||
| End Function | |||||
| ' Alias for Peek | |||||
| Public Function Back() | |||||
| ' TODO: Error handling | |||||
| Assign Back, m_last.m_value | |||||
| End Function | |||||
| Public Function Pop() | |||||
| Dim temp | |||||
| ' TODO: Error Handling | |||||
| Assign Pop, m_last.m_value | |||||
| Set temp = m_last | |||||
| Set m_last = temp.m_prev | |||||
| Set temp.m_prev = Nothing | |||||
| If m_last Is Nothing Then | |||||
| Set m_first = Nothing | |||||
| Else | |||||
| Set m_last.m_next = Nothing | |||||
| End If | |||||
| m_size = m_size - 1 | |||||
| End Function | |||||
| Public Function Unshift(ByVal value) | |||||
| Dim temp | |||||
| Set temp = NewNode(value) | |||||
| If Me.IsEmpty Then | |||||
| Set m_first = temp | |||||
| Set m_last = temp | |||||
| Else | |||||
| Set temp.m_next = m_first | |||||
| Set m_first.m_prev = temp | |||||
| Set m_first = temp | |||||
| End If | |||||
| m_size = m_size + 1 | |||||
| Set Unshift = Me | |||||
| End Function | |||||
| ' Alias for Peek | |||||
| Public Function Front() | |||||
| ' TODO: Error handling | |||||
| Assign Front, m_first.m_value | |||||
| End Function | |||||
| Public Function Shift() | |||||
| Dim temp | |||||
| ' TODO: Error Handling | |||||
| Assign Shift, m_first.m_value | |||||
| Set temp = m_first | |||||
| Set m_first = temp.m_next | |||||
| Set temp.m_next = Nothing | |||||
| If m_first Is Nothing Then | |||||
| Set m_last = Nothing | |||||
| Else | |||||
| Set m_first.m_prev = Nothing | |||||
| End If | |||||
| m_size = m_size - 1 | |||||
| End Function | |||||
| Public Function TO_Array() | |||||
| Dim i, iter | |||||
| ReDim retval(Me.Count - 1) | |||||
| i = 0 | |||||
| Set iter = Me.Iterator | |||||
| While iter.HasNext | |||||
| assign retval(i),iter.GetNext | |||||
| i = i + 1 | |||||
| Wend | |||||
| TO_Array = retval | |||||
| End Function | |||||
| Public Function TO_En() | |||||
| Set TO_En = En_Iterator(Iterator) | |||||
| End Function | |||||
| End Class | |||||
| '======================================================================================================================= | |||||
| ' Dynamic Array - From the Tolerable lib | |||||
| '======================================================================================================================= | |||||
| Class DynamicArray_Class | |||||
| Private m_data | |||||
| Private m_size | |||||
| Public Sub Initialize(ByVal d, ByVal s) | |||||
| m_data = d | |||||
| m_size = s | |||||
| End Sub | |||||
| Private Sub Class_Terminate() | |||||
| Set m_data = Nothing | |||||
| End Sub | |||||
| Public Property Get Capacity | |||||
| Capacity = UBOUND(m_data) + 1 | |||||
| End Property | |||||
| Public Property Get Count | |||||
| Count = m_size | |||||
| End Property | |||||
| ' Alias for Count | |||||
| Public Property Get Size | |||||
| Size = m_size | |||||
| End Property | |||||
| Public Function IsEmpty() | |||||
| IsEmpty = (m_size = 0) | |||||
| End Function | |||||
| Public Function Clear() | |||||
| m_size = 0 | |||||
| Set Clear = Me | |||||
| End Function | |||||
| Private Sub Grow | |||||
| ' TODO: There's probably a better way to | |||||
| ' do this. Doubling might be excessive | |||||
| ReDim Preserve m_data(UBOUND(m_data) * 2) | |||||
| End Sub | |||||
| Public Function Push(ByVal val) | |||||
| If m_size >= UBOUND(m_data) Then | |||||
| Grow | |||||
| End If | |||||
| Assign m_data(m_size), val | |||||
| m_size = m_size + 1 | |||||
| Set Push = Me | |||||
| End Function | |||||
| ' Look at the last element | |||||
| Public Function Peek() | |||||
| Assign Peek, m_data(m_size - 1) | |||||
| End Function | |||||
| ' Look at the last element and | |||||
| ' pop it off of the list | |||||
| Public Function Pop() | |||||
| Assign Pop, m_data(m_size - 1) | |||||
| m_size = m_size - 1 | |||||
| End Function | |||||
| ' If pseudo_index < 0, then we assume we're counting | |||||
| ' from the back of the Array. | |||||
| Private Function CalculateIndex(ByVal pseudo_index) | |||||
| If pseudo_index >= 0 Then | |||||
| CalculateIndex = pseudo_index | |||||
| Else | |||||
| CalculateIndex = m_size + pseudo_index | |||||
| End If | |||||
| End Function | |||||
| Public Default Function Item(ByVal i) | |||||
| Assign Item, m_data(CalculateIndex(i)) | |||||
| End Function | |||||
| ' This does not treat negative indices as wrap-around. | |||||
| ' Thus, it is slightly faster. | |||||
| Public Function FastItem(ByVal i) | |||||
| Assign FastItem, m_data(i) | |||||
| End Function | |||||
| Public Function Slice(ByVal s, ByVal e) | |||||
| s = CalculateIndex(s) | |||||
| e = CalculateIndex(e) | |||||
| If e < s Then | |||||
| Set Slice = DynamicArray() | |||||
| Else | |||||
| ReDim retval(e - s) | |||||
| Dim i, j | |||||
| j = 0 | |||||
| For i = s to e | |||||
| Assign retval(j), m_data(i) | |||||
| j = j + 1 | |||||
| Next | |||||
| Set Slice = DynamicArray1(retval) | |||||
| End If | |||||
| End Function | |||||
| Public Function Iterator() | |||||
| Dim retval | |||||
| Set retval = New Iterator_DynamicArray_Class | |||||
| retval.Initialize Me | |||||
| Set Iterator = retval | |||||
| End Function | |||||
| Public Function TO_En() | |||||
| Set TO_En = En_Iterator(Me.Iterator) | |||||
| End Function | |||||
| Public Function TO_Array() | |||||
| Dim i | |||||
| ReDim retval(m_size - 1) | |||||
| For i = 0 to UBOUND(retval) | |||||
| Assign retval(i), m_data(i) | |||||
| Next | |||||
| TO_Array = retval | |||||
| End Function | |||||
| End Class | |||||
| Public Function DynamicArray() | |||||
| ReDim data(3) | |||||
| Set DynamicArray = DynamicArray2(data, 0) | |||||
| End Function | |||||
| Public Function DynamicArray1(ByVal data) | |||||
| Set DynamicArray1 = DynamicArray2(data, UBOUND(data) + 1) | |||||
| End Function | |||||
| Private Function DynamicArray2(ByVal data, ByVal size) | |||||
| Dim retval | |||||
| Set retval = New DynamicArray_Class | |||||
| retval.Initialize data, size | |||||
| Set DynamicArray2 = retval | |||||
| End Function | |||||
| Class Iterator_DynamicArray_Class | |||||
| Private m_dynamic_array | |||||
| Private m_index | |||||
| Public Sub Initialize(ByVal dynamic_array) | |||||
| Set m_dynamic_array = dynamic_array | |||||
| m_index = 0 | |||||
| End Sub | |||||
| Private Sub Class_Terminate | |||||
| Set m_dynamic_array = Nothing | |||||
| End Sub | |||||
| Public Function HasNext() | |||||
| HasNext = (m_index < m_dynamic_array.Size) | |||||
| End Function | |||||
| Public Function PeekNext() | |||||
| Assign PeekNext, m_dynamic_array.FastItem(m_index) | |||||
| End Function | |||||
| Public Function GetNext() | |||||
| Assign GetNext, m_dynamic_array.FastItem(m_index) | |||||
| m_index = m_index + 1 | |||||
| End Function | |||||
| Public Function HasPrev() | |||||
| HasPrev = (m_index > 0) | |||||
| End Function | |||||
| Public Function PeekPrev() | |||||
| Assign PeekPrev, m_dynamic_array.FastItem(m_index - 1) | |||||
| End Function | |||||
| Public Function GetPrev() | |||||
| Assign GetPrev, m_dynamic_array.FastItem(m_index - 1) | |||||
| m_index = m_index - 1 | |||||
| End Function | |||||
| End Class | |||||
| '======================================================================================================================= | |||||
| ' Other Iterators | |||||
| '======================================================================================================================= | |||||
| '!!! EXPERIMENTAL !!! May not be very useful, oh well... | |||||
| Class Iterator_Recordset_Class | |||||
| Private m_rs | |||||
| Private m_record_count | |||||
| Private m_current_index | |||||
| Private m_field_names 'cached array | |||||
| Public Sub Initialize(ByVal rs) | |||||
| Set m_rs = rs | |||||
| m_rs.MoveFirst | |||||
| m_rs.MovePrevious | |||||
| m_record_count = rs.RecordCount | |||||
| m_current_index = 0 | |||||
| 'cache field names | |||||
| m_field_names = array() | |||||
| redim m_field_names(m_rs.Fields.Count) | |||||
| dim field | |||||
| dim i : i = 0 | |||||
| for each field in m_rs.Fields | |||||
| m_field_names(i) = field.Name | |||||
| next | |||||
| End Sub | |||||
| Private Sub Class_Terminate | |||||
| Set m_rs = Nothing | |||||
| End Sub | |||||
| Public Function HasNext() | |||||
| HasNext = (m_current_index < m_record_count) | |||||
| puts "m_current_index := " & m_current_index | |||||
| puts "m_record_count := " & m_record_count | |||||
| End Function | |||||
| Public Function PeekNext | |||||
| if HasNext then | |||||
| m_rs.MoveNext | |||||
| Assign PeekNext, GetPairs | |||||
| m_rs.MovePrevious | |||||
| else | |||||
| set PeekNext = Nothing | |||||
| end if | |||||
| End Function | |||||
| Private Function GetPairs | |||||
| End Function | |||||
| Public Function GetNext | |||||
| if m_current_index < m_record_count then | |||||
| Assign GetNext, m_rs | |||||
| m_rs.MoveNext | |||||
| m_current_index = m_current_index + 1 | |||||
| else | |||||
| set GetNext = Nothing | |||||
| end if | |||||
| End Function | |||||
| Public Function HasPrev() | |||||
| if m_rs.BOF then | |||||
| HasPrev = false | |||||
| else | |||||
| m_rs.MovePrevious | |||||
| HasPrev = Choice(m_rs.BOF, false, true) | |||||
| m_rs.MoveNext | |||||
| end if | |||||
| End Function | |||||
| Public Function PeekPrev | |||||
| m_rs.MovePrevious | |||||
| if m_rs.BOF then | |||||
| set PeekPrev = Nothing | |||||
| else | |||||
| Assign PeekPrev, m_rs | |||||
| end if | |||||
| m_rs.MoveNext | |||||
| End Function | |||||
| Public Function GetPrev | |||||
| m_rs.MovePrevious | |||||
| if m_rs.BOF then | |||||
| set GetPrev = Nothing | |||||
| else | |||||
| Assign GetPrev, m_rs | |||||
| end if | |||||
| End Function | |||||
| End Class | |||||
| Class Iterator_Dictionary_Class | |||||
| Private m_dic | |||||
| Private m_keys 'array | |||||
| Private m_idx 'current array index | |||||
| Private m_keys_ubound 'cached ubound(m_keys) | |||||
| Public Sub Initialize(ByVal dic) | |||||
| set m_dic = dic | |||||
| m_keys = m_dic.Keys() | |||||
| m_idx = -1 | |||||
| m_keys_ubound = ubound(m_keys) | |||||
| End Sub | |||||
| Private Sub Class_Terminate | |||||
| set m_dic = Nothing | |||||
| End Sub | |||||
| Public Function HasNext() | |||||
| HasNext = (m_idx < m_keys_ubound) | |||||
| End Function | |||||
| Public Function PeekNext() | |||||
| Assign PeekNext, m_dic(m_keys(m_idx + 1)) | |||||
| End Function | |||||
| Public Function GetNext() | |||||
| Assign GetNext, m_dic(m_keys(m_idx + 1)) | |||||
| m_idx = m_idx + 1 | |||||
| End Function | |||||
| Public Function HasPrev() | |||||
| HasPrev = (m_idx > 0) | |||||
| End Function | |||||
| Public Function PeekPrev() | |||||
| Assign PeekPrev, m_dic(m_keys(m_idx - 1)) | |||||
| End Function | |||||
| Public Function GetPrev() | |||||
| Assign GetPrev, m_dic(m_keys(m_idx - 1)) | |||||
| m_idx = m_idx - 1 | |||||
| End Function | |||||
| End Class | |||||
| '======================================================================================================================= | |||||
| ' Iterator Factory | |||||
| '======================================================================================================================= | |||||
| 'Returns the appropriate iterator for the passed-in collection. Errors if unknown collection. | |||||
| Function IteratorFor(col) | |||||
| dim result | |||||
| select case typename(col) | |||||
| case "LinkedList_Class" : set result = new Iterator_LinkedList_Class | |||||
| case "Dictionary" : set result = new Iterator_Dictionary_Class | |||||
| case "Recordset" : set result = new Iterator_Recordset_Class | |||||
| end select | |||||
| result.Initialize col | |||||
| set IteratorFor = result | |||||
| End Function | |||||
| Class List | |||||
| Private items | |||||
| Private P_count | |||||
| Private Sub Class_Initialize() | |||||
| ReDim items(-1) | |||||
| P_count = 0 | |||||
| End Sub | |||||
| Public Sub Add(value) | |||||
| ReDim Preserve items(P_count) | |||||
| If IsObject(value) Then | |||||
| Set items(P_count) = value | |||||
| Else | |||||
| items(P_count) = value | |||||
| End If | |||||
| P_count = P_count + 1 | |||||
| End Sub | |||||
| Public Sub AddRange(arrayToAdd) | |||||
| Dim i | |||||
| For i = 0 To UBound(arrayToAdd) | |||||
| Me.Add arrayToAdd(i) | |||||
| Next | |||||
| End Sub | |||||
| Public Property Get Count() | |||||
| Count = P_count | |||||
| End Property | |||||
| Public Property Get Item(index) | |||||
| If index < 0 Or index >= P_count Then | |||||
| Err.Raise 9, "List", "Index out of bounds" | |||||
| End If | |||||
| If IsObject(items(index)) Then | |||||
| Set Item = items(index) | |||||
| Else | |||||
| Item = items(index) | |||||
| End If | |||||
| End Property | |||||
| Public Property Let Item(index, value) | |||||
| If index < 0 Or index >= P_count Then | |||||
| Err.Raise 9, "List", "Index out of bounds" | |||||
| End If | |||||
| If IsObject(value) Then | |||||
| Set items(index) = value | |||||
| Else | |||||
| items(index) = value | |||||
| End If | |||||
| End Property | |||||
| Public Function Contains(ByRef value) | |||||
| Dim i | |||||
| For i = 0 To P_count - 1 | |||||
| If IsObject(items(i)) And IsObject(value) Then | |||||
| If (items(i) Is value) Then | |||||
| Contains = True | |||||
| Exit Function | |||||
| End If | |||||
| Else | |||||
| If items(i) = value Then | |||||
| Contains = True | |||||
| Exit Function | |||||
| End If | |||||
| End If | |||||
| Next | |||||
| Contains = False | |||||
| End Function | |||||
| Public Function IndexOf(value) | |||||
| Dim i | |||||
| For i = 0 To P_count - 1 | |||||
| If IsObject(items(i)) And IsObject(value) Then | |||||
| If items(i) Is value Then | |||||
| IndexOf = i | |||||
| Exit Function | |||||
| End If | |||||
| Else | |||||
| If items(i) = value Then | |||||
| IndexOf = i | |||||
| Exit Function | |||||
| End If | |||||
| End If | |||||
| Next | |||||
| IndexOf = -1 | |||||
| End Function | |||||
| Public Sub Remove(value) | |||||
| Dim i | |||||
| i = Me.IndexOf(value) | |||||
| If i <> -1 Then | |||||
| Me.RemoveAt i | |||||
| End If | |||||
| End Sub | |||||
| Public Sub RemoveAt(index) | |||||
| Dim i | |||||
| If index < 0 Or index >= P_count Then | |||||
| Err.Raise 9, "List", "Index out of bounds" | |||||
| End If | |||||
| For i = index To P_count - 2 | |||||
| If IsObject(items(i + 1)) Then | |||||
| Set items(i) = items(i + 1) | |||||
| Else | |||||
| items(i) = items(i + 1) | |||||
| End If | |||||
| Next | |||||
| P_count = P_count - 1 | |||||
| If P_count <= 0 Then | |||||
| ReDim items(-1) | |||||
| Else | |||||
| ReDim Preserve items(P_count - 1) | |||||
| End If | |||||
| End Sub | |||||
| Public Sub Clear() | |||||
| ReDim items(-1) | |||||
| P_count = 0 | |||||
| End Sub | |||||
| Public Sub Sort() | |||||
| Dim i, j, tmp | |||||
| For i = 0 To P_count - 2 | |||||
| For j = i + 1 To P_count - 1 | |||||
| If CStr(items(i)) > CStr(items(j)) Then | |||||
| Set tmp = items(i) | |||||
| Set items(i) = items(j) | |||||
| Set items(j) = tmp | |||||
| End If | |||||
| Next | |||||
| Next | |||||
| End Sub | |||||
| ' Note: this will NOT be used automatically by VBScript For Each, | |||||
| ' but you can use it manually. | |||||
| Public Function New_Enum() | |||||
| Set New_Enum = New ListEnumerator | |||||
| New_Enum.Init items, P_count | |||||
| End Function | |||||
| End Class | |||||
| Class ListEnumerator | |||||
| Private items, index, max | |||||
| Public Sub Init(arr, cnt) | |||||
| items = arr | |||||
| index = -1 | |||||
| max = cnt | |||||
| End Sub | |||||
| Public Function MoveNext() | |||||
| index = index + 1 | |||||
| MoveNext = (index < max) | |||||
| End Function | |||||
| Public Property Get Current() | |||||
| Set Current = items(index) | |||||
| End Property | |||||
| Public Sub Reset() | |||||
| index = -1 | |||||
| End Sub | |||||
| End Class | |||||
| %> | |||||
| @@ -0,0 +1,111 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' Controller Registry | |||||
| ' Provides a whitelist of valid controllers to prevent code injection attacks | |||||
| '======================================================================================================================= | |||||
| Class ControllerRegistry_Class | |||||
| Private m_controllers | |||||
| Private Sub Class_Initialize() | |||||
| Set m_controllers = Server.CreateObject("Scripting.Dictionary") | |||||
| m_controllers.CompareMode = 1 ' vbTextCompare for case-insensitive | |||||
| ' Register all valid controllers here | |||||
| ' Format: m_controllers.Add "controllername", True | |||||
| RegisterController "homecontroller" | |||||
| RegisterController "errorcontroller" | |||||
| RegisterController "docscontroller" | |||||
| End Sub | |||||
| Private Sub Class_Terminate() | |||||
| Set m_controllers = Nothing | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Register a controller as valid | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub RegisterController(controllerName) | |||||
| Dim key : key = LCase(Trim(controllerName)) | |||||
| If Not m_controllers.Exists(key) Then | |||||
| m_controllers.Add key, True | |||||
| End If | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Check if a controller is registered (valid) | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function IsValidController(controllerName) | |||||
| Dim key : key = LCase(Trim(controllerName)) | |||||
| IsValidController = m_controllers.Exists(key) | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Get list of all registered controllers | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function GetRegisteredControllers() | |||||
| GetRegisteredControllers = m_controllers.Keys() | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Validate controller name format (alphanumeric and underscore only) | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function IsValidControllerFormat(controllerName) | |||||
| If IsEmpty(controllerName) Or Len(controllerName) = 0 Then | |||||
| IsValidControllerFormat = False | |||||
| Exit Function | |||||
| End If | |||||
| Dim i, ch | |||||
| For i = 1 To Len(controllerName) | |||||
| ch = Mid(controllerName, i, 1) | |||||
| ' Allow a-z, A-Z, 0-9, and underscore | |||||
| If Not ((ch >= "a" And ch <= "z") Or _ | |||||
| (ch >= "A" And ch <= "Z") Or _ | |||||
| (ch >= "0" And ch <= "9") Or _ | |||||
| ch = "_") Then | |||||
| IsValidControllerFormat = False | |||||
| Exit Function | |||||
| End If | |||||
| Next | |||||
| IsValidControllerFormat = True | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Validate action name format (alphanumeric and underscore only) | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function IsValidActionFormat(actionName) | |||||
| If IsEmpty(actionName) Or Len(actionName) = 0 Then | |||||
| IsValidActionFormat = False | |||||
| Exit Function | |||||
| End If | |||||
| Dim i, ch | |||||
| For i = 1 To Len(actionName) | |||||
| ch = Mid(actionName, i, 1) | |||||
| ' Allow a-z, A-Z, 0-9, and underscore | |||||
| If Not ((ch >= "a" And ch <= "z") Or _ | |||||
| (ch >= "A" And ch <= "Z") Or _ | |||||
| (ch >= "0" And ch <= "9") Or _ | |||||
| ch = "_") Then | |||||
| IsValidActionFormat = False | |||||
| Exit Function | |||||
| End If | |||||
| Next | |||||
| IsValidActionFormat = True | |||||
| End Function | |||||
| End Class | |||||
| ' Singleton instance | |||||
| Dim ControllerRegistry_Class__Singleton | |||||
| Function ControllerRegistry() | |||||
| If IsEmpty(ControllerRegistry_Class__Singleton) Then | |||||
| Set ControllerRegistry_Class__Singleton = New ControllerRegistry_Class | |||||
| End If | |||||
| Set ControllerRegistry = ControllerRegistry_Class__Singleton | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,29 @@ | |||||
| <% | |||||
| ' This class encapsulates database access into one location, isolating database details from the rest of the app. | |||||
| ' Multiple databases can be handled in one of two ways: | |||||
| ' | |||||
| ' Option 1. Use a single DAL_Class instance with separate public properties for each database. | |||||
| ' Ex: To access Orders use DAL.Orders and to access Employees use DAL.Employees. | |||||
| ' | |||||
| ' Option 2. Use a separate DAL_Class instance for each database. | |||||
| ' Ex: | |||||
| ' dim OrdersDAL : set OrdersDAL = new DAL_Class | |||||
| ' OrdersDAL.ConnectionString = "..." <-- you would have to create this property to use this approach | |||||
| ' | |||||
| ' If you only access one database it is easier to just set the global DAL singleton to an instance of the | |||||
| ' Database_Class and use it directly. See the example project for details. | |||||
| '======================================================================================================================= | |||||
| ' DATA ACCESS LAYER Class | |||||
| '======================================================================================================================= | |||||
| dim DAL__Singleton : set DAL__Singleton = Nothing | |||||
| Function DAL() | |||||
| If DAL__Singleton is Nothing then | |||||
| set DAL__Singleton = new Database_Class | |||||
| DAL__Singleton.Initialize GetAppSetting("ConnectionString") | |||||
| End If | |||||
| set DAL = DAL__Singleton | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,214 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' DATABASE CLASS (native G3DB) | |||||
| '======================================================================================================================= | |||||
| ' Thin wrapper over AxonASP's G3DB library. Keeps the original Database_Class API (Query, PagedQuery, Execute, | |||||
| ' Begin/Commit/RollbackTransaction, Connection) so callers such as DAL() and the Migrator are unchanged. | |||||
| ' | |||||
| ' Connection string: "<driver>:<dsn>", e.g. | |||||
| ' sqlite:/opt/axonasp/site/db/app.sqlite | |||||
| ' mysql:user:pass@tcp(127.0.0.1:3306)/app?parseTime=true | |||||
| ' postgres:host=127.0.0.1 port=5432 user=u password=p dbname=app sslmode=disable | |||||
| ' mssql:server=127.0.0.1;port=1433;user id=u;password=p;database=app | |||||
| ' | |||||
| ' Behavior notes (G3DB): | |||||
| ' - Query returns a forward-only result set (EOF, MoveNext, rs("col"), rs(0), Fields.Count, Close). | |||||
| ' - Parameters are positional "?" values. G3DB does not expand an array, so this class does (max MAX_PARAMS). | |||||
| ' - G3DB signals failure with Empty plus LastError; this class turns that into a raised VBScript error that | |||||
| ' includes the SQL, so errors are never silently ignored. | |||||
| ' - Transactions are handle based; while one is open, Query/Execute are routed through it. | |||||
| Class Database_Class | |||||
| Private m_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 Initialize(connection_string) | |||||
| Dim p | |||||
| m_connection_string = "" & connection_string | |||||
| p = InStr(m_connection_string, ":") | |||||
| If p < 2 Then | |||||
| Err.Raise vbObjectError + 100, "Database_Class", "ConnectionString must look like '<driver>:<dsn>' (for example sqlite:/path/app.sqlite). Got: [" & m_connection_string & "]" | |||||
| End If | |||||
| m_driver = LCase(Left(m_connection_string, p - 1)) | |||||
| m_dsn = Mid(m_connection_string, p + 1) | |||||
| If m_driver = "sqlite" Or m_driver = "sqlite3" Then | |||||
| If InStr(m_dsn, "?") = 0 Then m_dsn = m_dsn & "?_busy_timeout=5000" | |||||
| End If | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' 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 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 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 | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' 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) | |||||
| 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() | |||||
| 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 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 RollbackTransaction() | |||||
| Dim tx | |||||
| If Not IsObject(m_tx) Then Exit Sub | |||||
| Set tx = m_tx | |||||
| Set m_tx = Empty | |||||
| tx.Rollback | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Private helpers | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' 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 | |||||
| ' 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 | |||||
| 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 | |||||
| %> | |||||
| @@ -0,0 +1,202 @@ | |||||
| <% | |||||
| Class EnumerableHelper_Class | |||||
| Private m_list | |||||
| Public Sub Init(list) | |||||
| set m_list = list | |||||
| End Sub | |||||
| Public Sub Class_Terminate | |||||
| set m_list = Nothing | |||||
| End Sub | |||||
| Public Default Function Data() | |||||
| set Data = m_list | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Convenience wrappers | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function Count() | |||||
| Count = m_list.Count() | |||||
| End Function | |||||
| Public Function First() | |||||
| Assign First, m_list.Front() | |||||
| End Function | |||||
| Public Function Last() | |||||
| Assign Last, m_list.Back() | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Methods that return a single value | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| 'true if all elements of the list satisfy the condition | |||||
| Public Function All(condition) | |||||
| dim item_, all_matched : all_matched = true | |||||
| dim it : set it = m_list.Iterator | |||||
| Do While it.HasNext | |||||
| Assign item_, it.GetNext() | |||||
| If "String" = typename(condition) then | |||||
| If Not eval(condition) then | |||||
| all_matched = false | |||||
| End If | |||||
| Else | |||||
| If Not condition(item_) then | |||||
| all_matched = false | |||||
| End If | |||||
| End If | |||||
| If Not all_matched then Exit Do | |||||
| Loop | |||||
| All = all_matched | |||||
| End Function | |||||
| 'true if any element of the list satisfies the condition | |||||
| Public Function Any(condition) | |||||
| Any = Not All("Not " & condition) | |||||
| End Function | |||||
| Public Function Max(expr) | |||||
| dim V_, item_, maxval | |||||
| dim it : set it = m_list.Iterator | |||||
| If "String" = typename(expr) then | |||||
| While it.HasNext | |||||
| Assign item_, it.GetNext() | |||||
| Assign V_, eval(expr) | |||||
| If V_ > maxval then maxval = V_ | |||||
| Wend | |||||
| Else | |||||
| While it.HasNext | |||||
| Assign item_, it.GetNext() | |||||
| Assign V_, expr(item_) | |||||
| If V_ > maxval then maxval = V_ | |||||
| Wend | |||||
| End If | |||||
| Max = maxval | |||||
| End Function | |||||
| Public Function Min(expr) | |||||
| dim V_, item_, minval | |||||
| dim it : set it = m_list.Iterator | |||||
| If "String" = typename(expr) then | |||||
| While it.HasNext | |||||
| Assign item_, it.GetNext() | |||||
| If IsEmpty(minval) then ' empty is always less than everything so set it on first pass | |||||
| Assign minval, item_ | |||||
| End If | |||||
| Assign V_, eval(expr) | |||||
| If V_ < minval then minval = V_ | |||||
| Wend | |||||
| Else | |||||
| While it.HasNext | |||||
| Assign item_, it.GetNext() | |||||
| If IsEmpty(minval) then | |||||
| Assign minval, item_ | |||||
| End If | |||||
| V_ = expr(item_) | |||||
| If V_ < minval then minval = V_ | |||||
| Wend | |||||
| End If | |||||
| Min = minval | |||||
| End Function | |||||
| Public Function Sum(expr) | |||||
| dim V_, item_ | |||||
| dim it : set it = m_list.Iterator | |||||
| While it.HasNext | |||||
| Assign item_, it.GetNext() | |||||
| execute "V_ = V_ + " & expr | |||||
| Wend | |||||
| Sum = V_ | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Methods that return a new instance of this class | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| 'returns a list that results from running lambda_or_proc once for every element in the list | |||||
| Public Function Map(lambda_or_proc) | |||||
| dim list2 : set list2 = new LinkedList_Class | |||||
| dim it : set it = m_list.Iterator | |||||
| dim item_ | |||||
| If "String" = typename(lambda_or_proc) then | |||||
| dim V_ | |||||
| While it.HasNext | |||||
| Assign item_, it.GetNext() | |||||
| execute lambda_or_proc | |||||
| list2.Push V_ | |||||
| Wend | |||||
| Else | |||||
| While it.HasNext | |||||
| Assign item_, it.GetNext() | |||||
| list2.Push lambda_or_proc(item_) | |||||
| Wend | |||||
| End If | |||||
| set Map = Enumerable(list2) | |||||
| End Function | |||||
| 'alias to match IEnumerable for convenience | |||||
| Public Function [Select](lambda_or_proc) | |||||
| set [Select] = Map(lambda_or_proc) | |||||
| End Function | |||||
| 'returns list containing first n items | |||||
| Public Function Take(n) | |||||
| dim list2 : set list2 = new LinkedList_Class | |||||
| dim it : set it = m_list.Iterator | |||||
| dim i : i = 1 | |||||
| While it.HasNext And i <= n | |||||
| list2.Push it.GetNext() | |||||
| i = i + 1 | |||||
| Wend | |||||
| set Take = Enumerable(list2) | |||||
| End Function | |||||
| 'returns list containing elements as long as the condition is true, and skips the remaining elements | |||||
| Public Function TakeWhile(condition) | |||||
| dim list2 : set list2 = new LinkedList_Class | |||||
| dim item_, V_, bln | |||||
| dim it : set it = m_list.Iterator | |||||
| Do While it.HasNext | |||||
| Assign item_, it.GetNext() | |||||
| If "String" = typename(condition) then | |||||
| 'execute condition | |||||
| If Not eval(condition) then Exit Do | |||||
| Else | |||||
| If Not condition(item_) then Exit Do | |||||
| End If | |||||
| list2.Push item_ | |||||
| Loop | |||||
| set TakeWhile = Enumerable(list2) | |||||
| End Function | |||||
| 'returns a list containing only elements that satisfy the condition | |||||
| Public Function Where(condition) | |||||
| dim list2 : set list2 = new LinkedList_Class | |||||
| dim it : set it = m_list.Iterator | |||||
| dim item_ | |||||
| While it.HasNext | |||||
| Assign item_, it.GetNext() | |||||
| If "String" = typename(condition) then | |||||
| If eval(condition) then list2.Push item_ | |||||
| Else | |||||
| If condition(item_) then list2.Push item_ | |||||
| End If | |||||
| Wend | |||||
| set Where = Enumerable(list2) | |||||
| End Function | |||||
| End Class | |||||
| Function Enumerable(list) | |||||
| dim E : set E = new EnumerableHelper_Class | |||||
| E.Init list | |||||
| set Enumerable = E | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,178 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' Error Handler Library | |||||
| ' Provides centralized error handling and logging functionality | |||||
| '======================================================================================================================= | |||||
| Class ErrorHandler_Class | |||||
| Private m_log_to_file | |||||
| Private m_log_file_path | |||||
| Private Sub Class_Initialize() | |||||
| m_log_to_file = False | |||||
| m_log_file_path = "" | |||||
| End Sub | |||||
| ' Configure whether to log errors to file | |||||
| Public Property Let LogToFile(value) | |||||
| m_log_to_file = value | |||||
| End Property | |||||
| Public Property Get LogToFile() | |||||
| LogToFile = m_log_to_file | |||||
| End Property | |||||
| ' Set the log file path | |||||
| Public Property Let LogFilePath(value) | |||||
| m_log_file_path = value | |||||
| End Property | |||||
| Public Property Get LogFilePath() | |||||
| LogFilePath = m_log_file_path | |||||
| End Property | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Main error handling method | |||||
| ' context: String describing where the error occurred | |||||
| ' errObj: VBScript Err object (optional, uses global Err if not provided) | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub HandleError(context, errObj) | |||||
| Dim isDevelopment | |||||
| isDevelopment = (LCase(GetAppSetting("Environment")) = "development") | |||||
| If IsEmpty(errObj) Or Not IsObject(errObj) Then | |||||
| ' Use global Err object if none provided | |||||
| If Err.Number <> 0 Then | |||||
| If isDevelopment Then | |||||
| ShowDetailedError context, Err | |||||
| Else | |||||
| ShowGenericError | |||||
| End If | |||||
| LogError context, Err | |||||
| End If | |||||
| Else | |||||
| If errObj.Number <> 0 Then | |||||
| If isDevelopment Then | |||||
| ShowDetailedError context, errObj | |||||
| Else | |||||
| ShowGenericError | |||||
| End If | |||||
| LogError context, errObj | |||||
| End If | |||||
| End If | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Display detailed error information (Development mode only) | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Private Sub ShowDetailedError(context, errObj) | |||||
| Dim errHtml | |||||
| errHtml = "<div style='padding:15px; margin:10px; border:2px solid #dc3545; background:#f8d7da; color:#721c24; font-family:Verdana,sans-serif; font-size:14px; border-radius:4px;'>" | |||||
| errHtml = errHtml & "<strong>Error Occurred</strong><br>" | |||||
| If Not IsEmpty(context) And Len(context) > 0 Then | |||||
| errHtml = errHtml & "<strong>Context:</strong> " & Server.HTMLEncode(context) & "<br>" | |||||
| End If | |||||
| errHtml = errHtml & "<strong>Time:</strong> " & Now() & "<br>" | |||||
| errHtml = errHtml & "<strong>Number:</strong> " & errObj.Number & "<br>" | |||||
| errHtml = errHtml & "<strong>Description:</strong> " & Server.HTMLEncode(errObj.Description) & "<br>" | |||||
| If Len(errObj.Source) > 0 Then | |||||
| errHtml = errHtml & "<strong>Source:</strong> " & Server.HTMLEncode(errObj.Source) & "<br>" | |||||
| End If | |||||
| errHtml = errHtml & "</div>" | |||||
| Response.Write errHtml | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Display generic error message (Production mode) | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Private Sub ShowGenericError() | |||||
| Dim errHtml | |||||
| errHtml = "<div style='padding:15px; margin:10px; border:2px solid #dc3545; background:#f8d7da; color:#721c24; font-family:Verdana,sans-serif; font-size:14px; border-radius:4px;'>" | |||||
| errHtml = errHtml & "<strong>An error occurred</strong><br>" | |||||
| errHtml = errHtml & "We apologize for the inconvenience. The error has been logged and will be investigated.<br>" | |||||
| errHtml = errHtml & "Please try again later or contact support if the problem persists." | |||||
| errHtml = errHtml & "</div>" | |||||
| Response.Write errHtml | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Log error to file (if enabled) | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Private Sub LogError(context, errObj) | |||||
| If Not m_log_to_file Or Len(m_log_file_path) = 0 Then Exit Sub | |||||
| On Error Resume Next | |||||
| Dim fso, logFile, logEntry | |||||
| Set fso = Server.CreateObject("Scripting.FileSystemObject") | |||||
| ' Create log entry | |||||
| logEntry = "[" & Now() & "] " | |||||
| If Len(context) > 0 Then | |||||
| logEntry = logEntry & "Context: " & context & " | " | |||||
| End If | |||||
| logEntry = logEntry & "Error #" & errObj.Number & ": " & errObj.Description | |||||
| If Len(errObj.Source) > 0 Then | |||||
| logEntry = logEntry & " | Source: " & errObj.Source | |||||
| End If | |||||
| logEntry = logEntry & vbCrLf | |||||
| ' Append to log file | |||||
| If fso.FileExists(m_log_file_path) Then | |||||
| Set logFile = fso.OpenTextFile(m_log_file_path, 8, False) ' 8 = ForAppending | |||||
| Else | |||||
| Set logFile = fso.CreateTextFile(m_log_file_path, True) | |||||
| End If | |||||
| logFile.Write logEntry | |||||
| logFile.Close | |||||
| Set logFile = Nothing | |||||
| Set fso = Nothing | |||||
| On Error GoTo 0 | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Quick check if an error exists | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function HasError() | |||||
| HasError = (Err.Number <> 0) | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Clear the current error | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub ClearError() | |||||
| Err.Clear | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Check and handle error in one call | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function CheckAndHandle(context) | |||||
| If Err.Number <> 0 Then | |||||
| HandleError context, Err | |||||
| CheckAndHandle = True | |||||
| Else | |||||
| CheckAndHandle = False | |||||
| End If | |||||
| End Function | |||||
| End Class | |||||
| ' Singleton instance | |||||
| Dim ErrorHandler_Class__Singleton | |||||
| Function ErrorHandler() | |||||
| If IsEmpty(ErrorHandler_Class__Singleton) Then | |||||
| Set ErrorHandler_Class__Singleton = New ErrorHandler_Class | |||||
| End If | |||||
| Set ErrorHandler = ErrorHandler_Class__Singleton | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,151 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' Flash Message Class | |||||
| '======================================================================================================================= | |||||
| Class Flash_Class | |||||
| Private m_errors_key | |||||
| Private m_success_key | |||||
| Private Sub Class_Initialize | |||||
| ' Use constants to avoid typos | |||||
| m_errors_key = "mvc.flash.errors_array" | |||||
| m_success_key = "mvc.flash.success_message" | |||||
| End Sub | |||||
| 'helper methods to avoid if..then statements in views | |||||
| Public Sub ShowErrorsIfPresent | |||||
| if HasErrors then ShowErrors | |||||
| End Sub | |||||
| Public Sub ShowSuccessIfPresent | |||||
| if HasSuccess then ShowSuccess | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Errors | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Property Get HasErrors | |||||
| HasErrors = (Not IsEmpty(Session(m_errors_key))) | |||||
| End Property | |||||
| Public Property Get Errors | |||||
| Errors = Session(m_errors_key) | |||||
| End Property | |||||
| Public Property Let Errors(ary) | |||||
| Session(m_errors_key) = ary | |||||
| End Property | |||||
| Public Sub AddError(msg) | |||||
| dim ary | |||||
| if IsEmpty(Session(m_errors_key)) then | |||||
| ary = Array() | |||||
| redim ary(-1) | |||||
| else | |||||
| ary = Session(m_errors_key) | |||||
| end if | |||||
| redim preserve ary(ubound(ary) + 1) | |||||
| ary(ubound(ary)) = msg | |||||
| Session(m_errors_key) = ary | |||||
| End Sub | |||||
| 'Public Sub ShowErrors | |||||
| ' ClearErrors | |||||
| 'End Sub | |||||
| Public Sub ShowErrors | |||||
| if HasErrors then | |||||
| %> | |||||
| <div id="flashErrorBox" class="alert alert-danger alert-dismissible fade show" role="alert"> | |||||
| <strong>Error!</strong> | |||||
| <ul class="mb-0 mt-2"> | |||||
| <% | |||||
| dim ary, i | |||||
| ary = Errors | |||||
| for i = 0 to ubound(ary) | |||||
| puts "<li>" | |||||
| puts H(ary(i)) | |||||
| puts "</li>" | |||||
| next | |||||
| %> | |||||
| </ul> | |||||
| <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> | |||||
| </div> | |||||
| <script> | |||||
| (function() { | |||||
| var timeout = <%= GetAppSetting("FlashMessageTimeout") %>; | |||||
| if (isNaN(timeout) || timeout <= 0) timeout = 3000; | |||||
| setTimeout(function() { | |||||
| var alertEl = document.getElementById("flashErrorBox"); | |||||
| if (alertEl && typeof bootstrap !== 'undefined') { | |||||
| var bsAlert = bootstrap.Alert.getOrCreateInstance(alertEl); | |||||
| bsAlert.close(); | |||||
| } else if (alertEl) { | |||||
| alertEl.style.display = "none"; | |||||
| } | |||||
| }, timeout); | |||||
| })(); | |||||
| </script> | |||||
| <% | |||||
| ClearErrors | |||||
| end if | |||||
| End Sub | |||||
| Public Sub ClearErrors | |||||
| Session.Contents.Remove(m_errors_key) | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Success | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Property Get HasSuccess | |||||
| HasSuccess = (Not IsEmpty(Session(m_success_key))) | |||||
| End Property | |||||
| Public Property Get Success | |||||
| Success = Session(m_success_key) | |||||
| End Property | |||||
| Public Property Let Success(msg) | |||||
| Session(m_success_key) = msg | |||||
| End Property | |||||
| Public Sub ShowSuccess | |||||
| if HasSuccess then | |||||
| %> | |||||
| <div id="flashSuccessBox" class="alert alert-success alert-dismissible fade show" role="alert"> | |||||
| <%= H(Success) %> | |||||
| <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> | |||||
| </div> | |||||
| <script> | |||||
| (function() { | |||||
| var timeout = <%= GetAppSetting("FlashMessageTimeout") %>; | |||||
| if (isNaN(timeout) || timeout <= 0) timeout = 3000; | |||||
| setTimeout(function() { | |||||
| var alertEl = document.getElementById("flashSuccessBox"); | |||||
| if (alertEl && typeof bootstrap !== 'undefined') { | |||||
| var bsAlert = bootstrap.Alert.getOrCreateInstance(alertEl); | |||||
| bsAlert.close(); | |||||
| } else if (alertEl) { | |||||
| alertEl.style.display = "none"; | |||||
| } | |||||
| }, timeout); | |||||
| })(); | |||||
| </script> | |||||
| <% | |||||
| ClearSuccess | |||||
| end if | |||||
| End Sub | |||||
| Public Sub ClearSuccess | |||||
| Session.Contents.Remove(m_success_key) | |||||
| End Sub | |||||
| End Class | |||||
| Function Flash() | |||||
| set Flash = new Flash_Class | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,79 @@ | |||||
| <% | |||||
| Class FormCache_Class | |||||
| 'given a form name and IRequestDictionary params (request.form) object, caches form values | |||||
| Public Sub SerializeForm(form_name, params) | |||||
| dim form_key, form_val, serialized_key | |||||
| For Each form_key in params | |||||
| form_val = params(form_key) | |||||
| serialized_key = CachedFormKeyName(form_name, form_key) | |||||
| 'put "serialize<br>" | |||||
| 'put "--form_key := " & form_key & "<br>" | |||||
| 'put "--form_val := " & form_val & "<br>" | |||||
| 'put "--serialized_key := " & serialized_key & "<br>" | |||||
| Session(serialized_key) = form_val | |||||
| Next | |||||
| End Sub | |||||
| 'given a form name, returns a dict with the form's stored values | |||||
| Public Function DeserializeForm(form_name) | |||||
| dim dict : set dict = Nothing | |||||
| dim serialized_key, serialized_val, form_key, form_val | |||||
| For Each serialized_key in Session.Contents | |||||
| 'put "serialized_key: " & serialized_key & "<br>" | |||||
| If InStr(serialized_key, "mvc.form." & form_name) > 0 then | |||||
| 'put "--match" & "<br>" | |||||
| If dict Is Nothing then | |||||
| set dict = Server.CreateObject("Scripting.Dictionary") | |||||
| 'put "dict created<br>" | |||||
| End If | |||||
| form_val = Session(serialized_key) | |||||
| form_key = Replace(serialized_key, "mvc.form." & form_name & ".", "") | |||||
| dict(form_key) = form_val | |||||
| 'Session.Contents.Remove serialized_key | |||||
| 'put "--serialized_val: " & serialized_val & "<br>" | |||||
| 'put "--form_val: " & form_val & "<br>" | |||||
| End If | |||||
| Next | |||||
| set DeserializeForm = dict | |||||
| End Function | |||||
| 'given a form name, clears the keys for that form | |||||
| Public Sub ClearForm(form_name) | |||||
| Dim key, prefix, keysToRemove(), idx | |||||
| prefix = "mvc.form." & form_name & "." | |||||
| ReDim keysToRemove(-1) | |||||
| ' First collect the keys to remove | |||||
| For Each key In Session.Contents | |||||
| If Left(CStr(key), Len(prefix)) = prefix Then | |||||
| ReDim Preserve keysToRemove(UBound(keysToRemove) + 1) | |||||
| keysToRemove(UBound(keysToRemove)) = key | |||||
| End If | |||||
| Next | |||||
| ' Then remove them | |||||
| For idx = 0 To UBound(keysToRemove) | |||||
| Session.Contents.Remove keysToRemove(idx) | |||||
| Next | |||||
| End Sub | |||||
| Private Function CachedFormKeyName(form_name, key) | |||||
| CachedFormKeyName = "mvc.form." & form_name & "." & key | |||||
| End Function | |||||
| End Class | |||||
| dim FormCache__Singleton | |||||
| Function FormCache() | |||||
| if IsEmpty(FormCache__Singleton) then | |||||
| set FormCache__Singleton = new FormCache_Class | |||||
| end if | |||||
| set FormCache = FormCache__Singleton | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,85 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' HTML SECURITY HELPER | |||||
| '======================================================================================================================= | |||||
| Class HTML_Security_Helper_Class | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Returns a random RFC 4122 v4 UUID (native G3CRYPTO; replaces Scriptlet.TypeLib, which does not exist on AxonASP) | |||||
| Public Function Nonce() | |||||
| Dim crypto | |||||
| Set crypto = Server.CreateObject("G3CRYPTO") | |||||
| Nonce = crypto.UUID() | |||||
| Set crypto = Nothing | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| 'Name is probably the combined ControllerName and ActionName of the form generator by convention | |||||
| Public Sub SetAntiCSRFToken(name) | |||||
| Session(name & ".anti_csrf_token") = Nonce() | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| '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 Then | |||||
| SetAntiCSRFToken name | |||||
| token = "" & Session(name & ".anti_csrf_token") ' re-read: return the newly created token | |||||
| End If | |||||
| GetAntiCSRFToken = token | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| 'Removes the current CSRF token nonce for the passed name | |||||
| Public Sub ClearAntiCSRFToken(name) | |||||
| Session.Contents.Remove(name & ".anti_csrf_token") | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| 'Returns true if passed nonce matches the stored CSRF token nonce for the specified name, false if not | |||||
| Public Function IsValidAntiCSRFToken(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 | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| 'If an invalid CSRF nonce is passed, sets the flash and redirects using the appropriate MVC.Redirect* method. | |||||
| 'If a valid CSRF nonce is passed, clears it from the cache to reset the state to the beginning. | |||||
| Public Sub OnInvalidAntiCSRFTokenRedirectToAction(token_name, token, action_name) | |||||
| OnInvalidAntiCSRFTokenRedirectToExt token_name, token, MVC.ControllerName, action_name, empty | |||||
| End Sub | |||||
| Public Sub OnInvalidAntiCSRFTokenRedirectToActionExt(token_name, token, action_name, params) | |||||
| OnInvalidAntiCSRFTokenRedirectToExt token_name, token, MVC.ControllerName, action_name, params | |||||
| End Sub | |||||
| Public Sub OnInvalidAntiCSRFTokenRedirectTo(token_name, token, controller_name, action_name) | |||||
| OnInvalidAntiCSRFTokenRedirectToExt token_name, token, controller_name, action_name | |||||
| End Sub | |||||
| Public Sub OnInvalidAntiCSRFTokenRedirectToExt(token_name, token, controller_name, action_name, params) | |||||
| If IsValidAntiCSRFToken(token_name, token) then | |||||
| ClearAntiCSRFToken token_name | |||||
| Else | |||||
| ClearAntiCSRFToken token_name | |||||
| Flash.AddError "Invalid form state. Please try again." | |||||
| MVC.RedirectToExt controller_name, action_name, params | |||||
| End If | |||||
| End Sub | |||||
| End Class | |||||
| dim HTML_Security_Helper__Singleton | |||||
| Function HTMLSecurity() | |||||
| If IsEmpty(HTML_Security_Helper__Singleton) Then | |||||
| set HTML_Security_Helper__Singleton = new HTML_Security_Helper_Class | |||||
| End If | |||||
| set HTMLSecurity = HTML_Security_Helper__Singleton | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,282 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' HTML HELPER | |||||
| '======================================================================================================================= | |||||
| Class HTML_Helper_Class | |||||
| 'Duplicate of Routes.NoCacheToken, copied to avoid extra lookup into the Routes object for such a trivial function. | |||||
| 'Allows caller to reference HTML.NoCacheToken in cases where it seems to feel right. | |||||
| Public Property Get NoCacheToken | |||||
| NoCacheToken = Timer() * 100 | |||||
| End Property | |||||
| 'Ensures safe output | |||||
| Public Function Encode(ByVal value) | |||||
| If Not IsEmpty(value) and Not IsNull(value) then | |||||
| Encode = Server.HtmlEncode(value) | |||||
| End If | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| 'LinkTo and its relatives DO NOT HTMLEncode the link_text! This allows use of HTML within the link, especially | |||||
| 'useful for Bootstrap icons and the like. | |||||
| ' | |||||
| 'Bottom Line: If you need to HTMLEncode the link text YOU MUST DO IT YOURSELF! The H() method makes this easy! | |||||
| Public Function LinkTo(link_text, controller_name, action_name) | |||||
| LinkTo = LinkToExt(link_text, controller_name, action_name, empty, empty) | |||||
| End Function | |||||
| Public Function LinkToExt(link_text, controller_name, action_name, params_array, attribs_array) | |||||
| LinkToExt = "<a href='" & Encode(Routes.UrlTo(controller_name, action_name, params_array)) & "'" &_ | |||||
| HtmlAttribs(attribs_array) & ">" & link_text & "</a>" & vbCR | |||||
| End Function | |||||
| Public Function LinkToIf(condition, link_text, controller_name, action_name) | |||||
| if condition then | |||||
| LinkToIf = LinkToExt(link_text, controller_name, action_name, empty, empty) | |||||
| end if | |||||
| End Function | |||||
| Public Function LinkToExtIf(condition, link_text, controller_name, action_name, params_array, attribs_array) | |||||
| if condition then | |||||
| LinkToExtIf = LinkToExt(link_text, controller_name, action_name, params_array, attribs_array) | |||||
| end if | |||||
| End Function | |||||
| Public Function LinkToUnless(condition, link_text, controller_name, action_name) | |||||
| if not condition then | |||||
| LinkToIf = LinkToExt(link_text, controller_name, action_name, empty, empty) | |||||
| end if | |||||
| End Function | |||||
| Public Function LinkToExtUnless(condition, link_text, controller_name, action_name, params_array, attribs_array) | |||||
| if not condition then | |||||
| LinkToExtUnless = LinkToExt(link_text, controller_name, action_name, params_array, attribs_array) | |||||
| end if | |||||
| End Function | |||||
| '' | |||||
| ' Creates a form button and a hidden form to enforce POST submissions. Params are in hidden fields. | |||||
| '' | |||||
| 'Public Function PostButtonLinkTo(controller_name, action_name, params) | |||||
| ' dim id : id = "post_button__" & controller_name & action_name | |||||
| ' dim s | |||||
| ' s = "<form id='" & id & "' action='" & Routes.UrlTo(controller_name, action_name, empty) & "' method='POST'>" | |||||
| ' dim i, key, val | |||||
| ' for i = 0 to ubound(params) step 2 | |||||
| ' KeyVal params, i, key, val | |||||
| ' s = s & "<input type='hidden' name='" & key & "' value='" & val & "'>" | |||||
| ' next | |||||
| ' s = s & "<input type='submit' value='>>'>" | |||||
| ' s = s & "</form>" | |||||
| ' PostButtonLinkTo = s | |||||
| 'End Function | |||||
| Public Function PostButtonTo(button_contents, controller_name, action_name, form_fields) | |||||
| PostButtonTo = PostButtonToExt(button_contents, controller_name, action_name, form_fields, empty) | |||||
| End Function | |||||
| Public Function PostButtonToExt(button_contents, controller_name, action_name, form_fields, url_params) | |||||
| dim s : s = "<form action='" & Routes.UrlTo(controller_name, action_name, url_params) & "' method='POST' style='margin: 0;'>" | |||||
| dim i, key, val | |||||
| for i = 0 to ubound(form_fields) step 2 | |||||
| KeyVal form_fields, i, key, val | |||||
| s = s & HTML.Hidden(key, val) | |||||
| next | |||||
| s = s & HTML.SubmitButton(button_contents) | |||||
| s = s & "</form>" & vbCR | |||||
| PostButtonToExt = s | |||||
| End Function | |||||
| Public Function AppStylesheetTag | |||||
| AppStylesheetTag = StylesheetTag(Routes.StylesheetsURL & "App.css") | |||||
| End Function | |||||
| Public Function ControllerStylesheetTag | |||||
| ControllerStylesheetTag = StylesheetTag(Routes.StylesheetsUrl & MVC.ControllerName & "Controller.css") | |||||
| End Function | |||||
| Public Function StylesheetTag(url) | |||||
| StylesheetTag = "<link rel='stylesheet' href='" & Encode(url) & "?" & Year(now) & Month(now) & Day(now) & Hour(now) & Minute(now) & Second(now) & "'>" & vbCR | |||||
| End Function | |||||
| Public Function JSTag(url) | |||||
| JSTag = "<script type='text/javascript' src='" & Encode(url) & "'></script>" & vbCR | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Form Helpers | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function FormTag(controller_name, action_name, route_attribs, form_attribs) | |||||
| FormTag = "<form action='" & Routes.UrlTo(controller_name, action_name, route_attribs) & "' method='POST' " & HtmlAttribs(form_attribs) & ">" & vbCR | |||||
| End Function | |||||
| Public Function Label(name, for_name) | |||||
| Label = LabelExt(name, for_name, empty) | |||||
| End Function | |||||
| Public Function LabelExt(name, for_name, attribs) | |||||
| LabelExt = "<label for='" & Encode(for_name) & "' " & HtmlAttribs(attribs) & ">" & Encode(name) & "</label>" & vbCR | |||||
| End Function | |||||
| Public Function Hidden(id, value) | |||||
| Hidden = HiddenExt(id, value, empty) | |||||
| End Function | |||||
| Public Function HiddenExt(id, value, attribs) | |||||
| HiddenExt = "<input type='hidden' id='" & Encode(id) & "' name='" & Encode(id) & "' value='" & Encode(value) & "' " & HtmlAttribs(attribs) & " >" & vbCR | |||||
| End Function | |||||
| Public Function TextBox(id, value) | |||||
| TextBox = TextBoxExt(id, value, empty) | |||||
| End Function | |||||
| Public Function TextBoxExt(id, value, attribs) | |||||
| TextBoxExt = "<input type='text' id='" & Encode(id) & "' name='" & Encode(id) & "' value='" & Encode(value) & "' " & HtmlAttribs(attribs) & " >" & vbCR | |||||
| End Function | |||||
| Public Function TextArea(id, value, rows, cols) | |||||
| TextArea = TextAreaExt(id, value, rows, cols, empty) | |||||
| End Function | |||||
| Public Function TextAreaExt(id, value, rows, cols, attribs) | |||||
| TextAreaExt = "<textarea id='" & Encode(id) & "' name='" & Encode(id) & "' cols='" & Encode(cols) & "' rows='" & Encode(rows) & "' " & HtmlAttribs(attribs) & " >" &_ | |||||
| Encode(value) & "</textarea>" & vbCR | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| 'If list is a recordset then option_value_field and option_text_field are required. | |||||
| 'If list is an array the method assumes it is a KVArray and those parameters are ignored. | |||||
| Public Function DropDownList(id, selected_value, list, option_value_field, option_text_field) | |||||
| DropDownList = DropDownListExt(id, selected_value, list, option_value_field, option_text_field, empty) | |||||
| End Function | |||||
| Public Function DropDownListExt(id, selected_value, list, option_value_field, option_text_field, attribs) | |||||
| If IsNull(selected_value) then | |||||
| selected_value = "" | |||||
| Else | |||||
| selected_value = CStr(selected_value) | |||||
| End If | |||||
| dim item, options, opt_val, opt_txt | |||||
| options = "<option value=''>" ' first value is "non-selected" blank state | |||||
| select case typename(list) | |||||
| case "Recordset" | |||||
| do until list.EOF | |||||
| If IsNull(list(option_value_field)) then | |||||
| opt_val = "" | |||||
| Else | |||||
| opt_val = CStr(list(option_value_field)) | |||||
| End If | |||||
| opt_txt = list(option_text_field) | |||||
| If Not IsNull(opt_val) And Not IsEmpty(opt_val) then | |||||
| options = options & "<option value='" & Encode(opt_val) & "' " & Choice((CStr(opt_val) = CStr(selected_value)), "selected='selected'", "") & ">" & Encode(opt_txt) & "</option>" & vbCR | |||||
| End If | |||||
| list.MoveNext | |||||
| loop | |||||
| case "Variant()" 'assumes KVArray | |||||
| dim i | |||||
| for i = 0 to ubound(list) step 2 | |||||
| KeyVal list, i, opt_val, opt_txt | |||||
| options = options & "<option value='" & Encode(opt_val) & "' " & Choice((CStr(opt_val) = CStr(selected_value)), "selected='selected'", "") & ">" & Encode(opt_txt) & "</option>" & vbCR | |||||
| next | |||||
| end select | |||||
| DropDownListExt = "<select id='" & Encode(id) & "' name='" & Encode(id) & "' " & HtmlAttribs(attribs) & " >" & vbCR & options & "</select>" & vbCR | |||||
| End Function | |||||
| Public Function Checkbox(id, value) | |||||
| Checkbox = CheckboxExt(id, value, empty) | |||||
| End Function | |||||
| Public Function CheckboxExt(id, value, attribs) | |||||
| CheckBoxExt = "<input type='checkbox' id='" & Encode(id) & "' name='" & Encode(id) & "' " & Choice( (value = 1) or (value = true) or (LCase(value) = "true") or (LCase(value) = "on"), "checked='checked'", "") & " " & HtmlAttribs(attribs) & ">" & vbCR | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| 'Button text IS NOT ENCODED! As with LinkTo, this allows use of Bootstrap icons and other arbitrary HTML in the | |||||
| 'button. If you need to HTMLEncode the text you MUST do it yourself! | |||||
| Public Function SubmitButton(text) | |||||
| SubmitButton = "<button type='submit' class='btn'>" & text & "</button>" & vbCR | |||||
| End Function | |||||
| Public Function Button(button_type, text, class_name) | |||||
| Button = "<button type='" & Encode(button_type) & "' class='btn " & Encode(class_name) & "'>" & text & "</button>" & vbCR | |||||
| End Function | |||||
| Public Function ButtonExt(button_type, text, attribs_array) | |||||
| ButtonExt = "<button type='" & Encode(button_type) & "' " & HtmlAttribs(attribs_array) & ">" & text & "</button>" & vbCR | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function Tag(Tag_name, attribs_array) | |||||
| Tag = "<" & Encode(tag_name) & " " & HtmlAttribs(attribs_array) & ">" | |||||
| End Function | |||||
| Public Function Tag_(Tag_name) | |||||
| Tag_ = "</" & Encode(tag_name) & ">" | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function HtmlAttribs(attribs) | |||||
| dim result : result = "" | |||||
| if not IsEmpty(attribs) then | |||||
| if IsArray(attribs) then | |||||
| dim idx | |||||
| for idx = lbound(attribs) to ubound(attribs) step 2 | |||||
| result = result & " " & HtmlAttrib(attribs, idx) & " " | |||||
| next | |||||
| else ' assume string or string-like default value | |||||
| result = attribs | |||||
| end if | |||||
| end if | |||||
| HtmlAttribs = result | |||||
| End Function | |||||
| Public Function HtmlAttrib(attribs_array, key_idx) | |||||
| dim key, val | |||||
| KeyVal attribs_array, key_idx, key, val | |||||
| HtmlAttrib = Encode(key) & "='" & Encode(val) & "'" | |||||
| End Function | |||||
| Function checkboxfor(fieldName, isChecked) | |||||
| Dim idSuffix, checkboxId, html | |||||
| ' Decide on the id suffix and checked attribute | |||||
| If isChecked Then | |||||
| idSuffix = "Checked" | |||||
| Else | |||||
| idSuffix = "Default" | |||||
| End If | |||||
| checkboxId = "flexSwitchCheck" & idSuffix | |||||
| ' Build the HTML string | |||||
| html = "<div class='form-check form-switch'>" & vbCrLf | |||||
| html = html & " <input class='form-check-input form-control' type='checkbox' id='" & checkboxId & "' name='" & fieldName & "'" | |||||
| If isChecked Then html = html & " checked" | |||||
| html = html & ">" & vbCrLf | |||||
| html = html & " <label class='form-check-label' for='" & checkboxId & "'>" & fieldName & "</label>" & vbCrLf | |||||
| html = html & "</div>" | |||||
| checkboxfor = html | |||||
| End Function | |||||
| End Class | |||||
| dim HTML_Helper__Singleton : set HTML_Helper__Singleton = Nothing | |||||
| Function HTML() | |||||
| if HTML_Helper__Singleton Is Nothing then | |||||
| set HTML_Helper__Singleton = new HTML_Helper_Class | |||||
| End if | |||||
| set HTML = HTML_Helper__Singleton | |||||
| End Function | |||||
| %> | |||||
| @@ -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 | |||||
| %> | |||||
| @@ -0,0 +1,436 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' MIGRATION SYSTEM | |||||
| '======================================================================================================================= | |||||
| ' Provides database migration capabilities for version-controlled schema changes. | |||||
| ' | |||||
| ' Features: | |||||
| ' - Sequential migration versioning (timestamp-based) | |||||
| ' - Up/Down migration support | |||||
| ' - Migration tracking in schema_migrations table | |||||
| ' - Transaction support for atomic migrations | |||||
| ' - Migration status checking | |||||
| ' | |||||
| ' Usage: | |||||
| ' Set migrator = Migrator() | |||||
| ' migrator.ApplyMigration "20260109120000_create_users_table.asp" | |||||
| ' migrator.RollbackMigration "20260109120000_create_users_table.asp" | |||||
| ' pending = migrator.GetPendingMigrations() | |||||
| ' applied = migrator.GetAppliedMigrations() | |||||
| ' | |||||
| Class Migrator_Class | |||||
| Private m_db | |||||
| Private m_migrations_path | |||||
| Private m_schema_table | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Private Sub Class_Initialize() | |||||
| Set m_db = DAL() | |||||
| m_schema_table = "schema_migrations" | |||||
| 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 | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub EnsureSchemaMigrationsTable() | |||||
| On Error Resume Next | |||||
| ' Try to query the table - if it doesn't exist, create it | |||||
| Dim rs | |||||
| 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 | |||||
| Err.Clear | |||||
| On Error GoTo 0 | |||||
| Dim createSQL | |||||
| createSQL = "CREATE TABLE " & m_schema_table & " (" & _ | |||||
| "version VARCHAR(14) PRIMARY KEY, " & _ | |||||
| "applied_at DATETIME NOT NULL)" | |||||
| m_db.Execute createSQL, empty | |||||
| Else | |||||
| If Not rs Is Nothing Then | |||||
| rs.Close | |||||
| Set rs = Nothing | |||||
| End If | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| End Sub | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Get all applied migration versions | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function GetAppliedMigrations() | |||||
| EnsureSchemaMigrationsTable | |||||
| Dim rs, versions, version | |||||
| Set versions = Server.CreateObject("Scripting.Dictionary") | |||||
| Set rs = m_db.Query("SELECT version FROM " & m_schema_table & " ORDER BY version", empty) | |||||
| Do While Not rs.EOF | |||||
| version = Trim(rs("version")) | |||||
| versions.Add version, True | |||||
| rs.MoveNext | |||||
| Loop | |||||
| rs.Close | |||||
| Set rs = Nothing | |||||
| Set GetAppliedMigrations = versions | |||||
| End Function | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Get all available migration files | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function GetAvailableMigrations() | |||||
| Dim fso, folder, files, file | |||||
| Set fso = Server.CreateObject("Scripting.FileSystemObject") | |||||
| If Not fso.FolderExists(m_migrations_path) Then | |||||
| Set GetAvailableMigrations = Server.CreateObject("Scripting.Dictionary") | |||||
| Exit Function | |||||
| End If | |||||
| Set folder = fso.GetFolder(m_migrations_path) | |||||
| Set files = folder.Files | |||||
| Dim migrations | |||||
| Set migrations = Server.CreateObject("Scripting.Dictionary") | |||||
| For Each file In files | |||||
| If LCase(fso.GetExtensionName(file.Name)) = "asp" Then | |||||
| Dim version | |||||
| version = GetVersionFromFilename(file.Name) | |||||
| If version <> "" Then | |||||
| migrations.Add version, file.Name | |||||
| End If | |||||
| End If | |||||
| Next | |||||
| Set GetAvailableMigrations = migrations | |||||
| End Function | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Get pending migrations (available but not applied) | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function GetPendingMigrations() | |||||
| Dim applied, available, pending, version | |||||
| Set applied = GetAppliedMigrations() | |||||
| Set available = GetAvailableMigrations() | |||||
| Set pending = Server.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 | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Extract version from migration filename | |||||
| ' Expected format: YYYYMMDDHHMMSS_description.asp | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Private 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 | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Apply a migration (run the Up method) | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub ApplyMigration(filename) | |||||
| Dim version, msg | |||||
| version = GetVersionFromFilename(filename) | |||||
| If version = "" Then | |||||
| Err.Raise vbObjectError + 1, "Migrator", "Invalid migration filename format: " & filename | |||||
| End If | |||||
| If GetAppliedMigrations().Exists(version) Then | |||||
| Response.Write "Migration " & version & " already applied. Skipping." & vbCrLf | |||||
| Exit Sub | |||||
| End If | |||||
| Response.Write "Applying migration: " & filename & "..." & vbCrLf | |||||
| m_db.BeginTransaction | |||||
| 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 | |||||
| If msg <> "" Then | |||||
| m_db.RollbackTransaction | |||||
| Err.Raise vbObjectError + 2, "Migrator", "Migration " & version & " FAILED and was rolled back: " & msg | |||||
| End If | |||||
| m_db.CommitTransaction | |||||
| Response.Write "Migration " & version & " applied successfully." & vbCrLf | |||||
| End Sub | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Rollback a migration (run the Down method) | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub RollbackMigration(filename) | |||||
| Dim version, msg | |||||
| version = GetVersionFromFilename(filename) | |||||
| If version = "" Then | |||||
| Err.Raise vbObjectError + 1, "Migrator", "Invalid migration filename format: " & filename | |||||
| End If | |||||
| 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 | |||||
| m_db.BeginTransaction | |||||
| 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 | |||||
| If msg <> "" Then | |||||
| m_db.RollbackTransaction | |||||
| Err.Raise vbObjectError + 4, "Migrator", "Rollback of " & version & " FAILED: " & msg | |||||
| End If | |||||
| m_db.CommitTransaction | |||||
| Response.Write "Migration " & version & " rolled back successfully." & vbCrLf | |||||
| End Sub | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Execute a migration file's Up or Down method | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| 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 | |||||
| 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 | |||||
| RunMigrationFile = "Migration file not found: " & migrationPath | |||||
| Exit Function | |||||
| End If | |||||
| 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 | |||||
| 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 | |||||
| RunMigrationFile = "" | |||||
| End Function | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Apply all pending migrations | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub ApplyAllPending() | |||||
| Dim pending, version, versions() | |||||
| Set pending = GetPendingMigrations() | |||||
| If pending.Count = 0 Then | |||||
| Response.Write "No pending migrations." & vbCrLf | |||||
| Exit Sub | |||||
| End If | |||||
| ' Sort versions | |||||
| ReDim versions(pending.Count - 1) | |||||
| Dim i : i = 0 | |||||
| For Each version In pending.Keys | |||||
| versions(i) = version | |||||
| i = i + 1 | |||||
| Next | |||||
| ' Simple bubble sort for versions | |||||
| Dim j, temp | |||||
| For i = 0 To UBound(versions) - 1 | |||||
| For j = i + 1 To UBound(versions) | |||||
| If CDbl(versions(i)) > CDbl(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 | |||||
| End Sub | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Rollback the last applied migration | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub RollbackLast() | |||||
| Dim applied, version, lastVersion | |||||
| Set applied = GetAppliedMigrations() | |||||
| If applied.Count = 0 Then | |||||
| Response.Write "No migrations to rollback." & vbCrLf | |||||
| Exit Sub | |||||
| End If | |||||
| ' Find the last version | |||||
| lastVersion = "" | |||||
| For Each version In applied.Keys | |||||
| ' 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 | |||||
| ' Find the filename | |||||
| Dim available | |||||
| Set available = GetAvailableMigrations() | |||||
| If available.Exists(lastVersion) Then | |||||
| RollbackMigration available(lastVersion) | |||||
| Else | |||||
| Err.Raise vbObjectError + 7, "Migrator", "Migration file not found for version: " & lastVersion | |||||
| End If | |||||
| End Sub | |||||
| End Class | |||||
| '======================================================================================================================= | |||||
| ' MIGRATION CONTEXT | |||||
| '======================================================================================================================= | |||||
| ' Provides helper methods for use within migration files | |||||
| ' | |||||
| Class MigrationContext_Class | |||||
| Public DB ' Reference to DAL | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' 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 | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Create a table | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub CreateTable(tableName, columns) | |||||
| Dim sql | |||||
| sql = "CREATE TABLE " & tableName & " (" & columns & ")" | |||||
| ExecuteSQL sql | |||||
| End Sub | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Drop a table | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub DropTable(tableName) | |||||
| ExecuteSQL "DROP TABLE " & tableName | |||||
| End Sub | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Add a column to a table | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub AddColumn(tableName, columnName, columnType) | |||||
| ExecuteSQL "ALTER TABLE " & tableName & " ADD COLUMN " & columnName & " " & columnType | |||||
| End Sub | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Drop a column from a table | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub DropColumn(tableName, columnName) | |||||
| ExecuteSQL "ALTER TABLE " & tableName & " DROP COLUMN " & columnName | |||||
| End Sub | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Create an index | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub CreateIndex(indexName, tableName, columns) | |||||
| ExecuteSQL "CREATE INDEX " & indexName & " ON " & tableName & " (" & columns & ")" | |||||
| End Sub | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| ' Drop an index | |||||
| '------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub DropIndex(indexName, tableName) | |||||
| ExecuteSQL "DROP INDEX " & indexName ' SQLite syntax (Access/SQL Server need "ON table") | |||||
| End Sub | |||||
| End Class | |||||
| '======================================================================================================================= | |||||
| ' SINGLETON | |||||
| '======================================================================================================================= | |||||
| Dim Migrator__Singleton : Set Migrator__Singleton = Nothing | |||||
| Function Migrator() | |||||
| If Migrator__Singleton Is Nothing Then | |||||
| Set Migrator__Singleton = New Migrator_Class | |||||
| End If | |||||
| Set Migrator = Migrator__Singleton | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,144 @@ | |||||
| <% | |||||
| ' Router_Class: pure-ASP port of router.wsc (AxonASP/Linux cannot load Windows Script Components) | |||||
| Class Router_Class | |||||
| '------------------------------------------------------------ | |||||
| ' Private state | |||||
| '------------------------------------------------------------ | |||||
| Private routes | |||||
| Private Sub Class_Initialize() | |||||
| Set routes = CreateObject("Scripting.Dictionary") | |||||
| End Sub | |||||
| '------------------------------------------------------------ | |||||
| ' METHOD AddRoute(method, path, controller, action) | |||||
| '------------------------------------------------------------ | |||||
| Public Sub AddRoute(method, path, controller, action) | |||||
| ' Input validation | |||||
| If IsEmpty(method) Or Len(Trim(method)) = 0 Then | |||||
| Err.Raise 5, "Router.AddRoute", "HTTP method parameter is required and cannot be empty" | |||||
| End If | |||||
| If IsEmpty(path) Then | |||||
| Err.Raise 5, "Router.AddRoute", "Path parameter is required" | |||||
| End If | |||||
| If IsEmpty(controller) Or Len(Trim(controller)) = 0 Then | |||||
| Err.Raise 5, "Router.AddRoute", "Controller parameter is required and cannot be empty" | |||||
| End If | |||||
| If IsEmpty(action) Or Len(Trim(action)) = 0 Then | |||||
| Err.Raise 5, "Router.AddRoute", "Action parameter is required and cannot be empty" | |||||
| End If | |||||
| ' Validate HTTP method (allow common methods) | |||||
| Dim validMethods, methodUpper, i, isValidMethod | |||||
| validMethods = Array("GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS") | |||||
| methodUpper = UCase(Trim(method)) | |||||
| isValidMethod = False | |||||
| For i = 0 To UBound(validMethods) | |||||
| If validMethods(i) = methodUpper Then | |||||
| isValidMethod = True | |||||
| Exit For | |||||
| End If | |||||
| Next | |||||
| If Not isValidMethod Then | |||||
| Err.Raise 5, "Router.AddRoute", "Invalid HTTP method: " & method & ". Allowed: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS" | |||||
| End If | |||||
| Dim routeKey | |||||
| routeKey = methodUpper & ":" & LCase(Trim(path)) | |||||
| If Not routes.Exists(routeKey) Then | |||||
| routes.Add routeKey, Array(Trim(controller), Trim(action)) | |||||
| End If | |||||
| End Sub | |||||
| '------------------------------------------------------------ | |||||
| ' METHOD Resolve(method, path) -> Array(controller, action, params()) | |||||
| '------------------------------------------------------------ | |||||
| Public Function Resolve(method, path) | |||||
| Dim routeKey, routeValue, values | |||||
| routeKey = UCase(method) & ":" & LCase(path) | |||||
| ' Always return a params array (empty by default) | |||||
| Dim emptyParams() : ReDim emptyParams(-1) | |||||
| ' Exact match first | |||||
| If routes.Exists(routeKey) Then | |||||
| routeValue = routes(routeKey) | |||||
| Resolve = Array(routeValue(0), routeValue(1), emptyParams) | |||||
| Exit Function | |||||
| End If | |||||
| ' Dynamic routes (e.g. /users/:id) | |||||
| Dim r, routeMethod, routePattern | |||||
| For Each r In routes.Keys | |||||
| routeMethod = Split(r, ":")(0) | |||||
| routePattern = Mid(r, Len(routeMethod) + 2) ' strip "METHOD:" | |||||
| If UCase(routeMethod) = UCase(method) Then | |||||
| If IsMatch(path, routePattern, values) Then | |||||
| routeValue = routes(r) | |||||
| Resolve = Array(routeValue(0), routeValue(1), values) | |||||
| Exit Function | |||||
| End If | |||||
| End If | |||||
| Next | |||||
| ' 404 fallback | |||||
| Resolve = Array("ErrorController", "NotFound", emptyParams) | |||||
| End Function | |||||
| '------------------------------------------------------------ | |||||
| ' INTERNAL IsMatch(requestPath, routePattern, values()) | |||||
| ' Returns True/False and fills values() with parameters | |||||
| '------------------------------------------------------------ | |||||
| Private Function IsMatch(requestPath, routePattern, values) | |||||
| Dim reqParts, routeParts, i, paramCount | |||||
| reqParts = Split(requestPath, "/") | |||||
| routeParts = Split(routePattern, "/") | |||||
| If UBound(reqParts) <> UBound(routeParts) Then | |||||
| IsMatch = False : Exit Function | |||||
| End If | |||||
| paramCount = 0 : ReDim values(-1) | |||||
| For i = 0 To UBound(reqParts) | |||||
| If Left(routeParts(i), 1) = ":" Then | |||||
| ReDim Preserve values(paramCount) | |||||
| values(paramCount) = reqParts(i) | |||||
| paramCount = paramCount + 1 | |||||
| ElseIf LCase(routeParts(i)) <> LCase(reqParts(i)) Then | |||||
| IsMatch = False : Exit Function | |||||
| End If | |||||
| Next | |||||
| If paramCount = 0 Then ReDim values(-1) | |||||
| IsMatch = True | |||||
| End Function | |||||
| '------------------------------------------------------------ | |||||
| ' Optional lifecycle hooks | |||||
| '------------------------------------------------------------ | |||||
| Private Sub Class_Terminate() | |||||
| Set routes = Nothing | |||||
| End Sub | |||||
| End Class | |||||
| ' Singleton accessor (same pattern as MVC()/ControllerRegistry()) so the router is visible | |||||
| ' inside class methods regardless of include order. | |||||
| Dim Router_Class__Singleton | |||||
| Function GetRouter() | |||||
| If IsEmpty(Router_Class__Singleton) Then | |||||
| Set Router_Class__Singleton = New Router_Class | |||||
| End If | |||||
| Set GetRouter = Router_Class__Singleton | |||||
| End Function | |||||
| Dim router : Set router = GetRouter() | |||||
| %> | |||||
| @@ -0,0 +1,262 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' ROUTING HELPER | |||||
| ' Provides URL generation for RouteKit framework | |||||
| '======================================================================================================================= | |||||
| Class Route_Helper_Class | |||||
| Private m_app_url | |||||
| Private m_content_url | |||||
| Private m_stylesheets_url | |||||
| Private m_js_url | |||||
| Private m_images_url | |||||
| Private m_enable_cache_busting | |||||
| Private m_cache_bust_param_name | |||||
| Private Sub Class_Initialize() | |||||
| ' Auto-detect application URL from current request | |||||
| Dim protocol, host, appPath | |||||
| protocol = IIf(Request.ServerVariables("HTTPS") = "on", "https://", "http://") | |||||
| host = Request.ServerVariables("HTTP_HOST") | |||||
| appPath = Request.ServerVariables("APPL_MD_PATH") | |||||
| ' Extract virtual directory from IIS path | |||||
| Dim vdir | |||||
| vdir = "" | |||||
| If InStr(appPath, "/LM/W3SVC/") > 0 Then | |||||
| vdir = Mid(appPath, InStrRev(appPath, "/") + 1) | |||||
| If vdir <> "ROOT" Then | |||||
| vdir = "/" & vdir | |||||
| Else | |||||
| vdir = "" | |||||
| End If | |||||
| End If | |||||
| m_app_url = protocol & host & vdir & "/" | |||||
| m_content_url = m_app_url & "content/" | |||||
| m_stylesheets_url = m_app_url & "css/" | |||||
| m_js_url = m_app_url & "js/" | |||||
| m_images_url = m_app_url & "images/" | |||||
| ' Load cache-busting configuration | |||||
| Dim cacheBustSetting | |||||
| cacheBustSetting = GetAppSetting("EnableCacheBusting") | |||||
| m_enable_cache_busting = (cacheBustSetting = "true" Or cacheBustSetting = "True") | |||||
| ' Get cache-bust parameter name (default: "v") | |||||
| m_cache_bust_param_name = GetAppSetting("CacheBustParamName") | |||||
| If m_cache_bust_param_name = "nothing" Or Len(m_cache_bust_param_name) = 0 Then | |||||
| m_cache_bust_param_name = "v" | |||||
| End If | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Cache-busting token (timestamp-based for uniqueness) | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Property Get NoCacheToken | |||||
| NoCacheToken = CLng(Timer() * 100) | |||||
| End Property | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Check if cache-busting is globally enabled | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Property Get CacheBustingEnabled | |||||
| CacheBustingEnabled = m_enable_cache_busting | |||||
| End Property | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Get/Set cache-busting enabled (can override config at runtime) | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Property Let CacheBustingEnabled(value) | |||||
| m_enable_cache_busting = value | |||||
| End Property | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' URL Properties | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Property Get AppURL | |||||
| AppURL = m_app_url | |||||
| End Property | |||||
| Public Property Get ContentURL | |||||
| ContentURL = m_content_url | |||||
| End Property | |||||
| Public Property Get StylesheetsURL | |||||
| StylesheetsURL = m_stylesheets_url | |||||
| End Property | |||||
| Public Property Get JsURL | |||||
| JsURL = m_js_url | |||||
| End Property | |||||
| Public Property Get ImagesURL | |||||
| ImagesURL = m_images_url | |||||
| End Property | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Generate clean URL for controller/action (RouteKit style) | |||||
| ' | |||||
| ' @param controller_name String Name of controller (without "Controller" suffix) | |||||
| ' @param action_name String Name of action method | |||||
| ' @param params_array KV Array Optional key/value pair array for query string | |||||
| ' @returns String Clean URL like "/controller/action?key=val" | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function UrlTo(controller_name, action_name, params_array) | |||||
| Dim url, qs | |||||
| ' Build clean URL: /controller/action | |||||
| url = m_app_url & LCase(controller_name) & "/" & LCase(action_name) | |||||
| ' Add query string parameters if provided | |||||
| qs = TO_Querystring(params_array) | |||||
| If Len(qs) > 0 Then | |||||
| url = url & "?" & qs | |||||
| End If | |||||
| UrlTo = url | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Generate URL with route parameters (e.g., /users/show/123) | |||||
| ' | |||||
| ' @param controller_name String Name of controller | |||||
| ' @param action_name String Name of action method | |||||
| ' @param route_params Array Route parameters (e.g., Array(123) for ID) | |||||
| ' @param query_params KV Array Optional query string parameters | |||||
| ' @returns String URL with route params | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function UrlToWithParams(controller_name, action_name, route_params, query_params) | |||||
| Dim url, qs, i | |||||
| ' Build base URL | |||||
| url = m_app_url & LCase(controller_name) & "/" & LCase(action_name) | |||||
| ' Append route parameters | |||||
| If IsArray(route_params) Then | |||||
| For i = 0 To UBound(route_params) | |||||
| url = url & "/" & Server.URLEncode(CStr(route_params(i))) | |||||
| Next | |||||
| ElseIf Not IsEmpty(route_params) Then | |||||
| url = url & "/" & Server.URLEncode(CStr(route_params)) | |||||
| End If | |||||
| ' Add query string parameters if provided | |||||
| qs = TO_Querystring(query_params) | |||||
| If Len(qs) > 0 Then | |||||
| url = url & "?" & qs | |||||
| End If | |||||
| UrlToWithParams = url | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Generate URL for static asset with cache-busting | |||||
| ' | |||||
| ' @param asset_path String Relative path to asset (e.g., "css/site.css") | |||||
| ' @param use_cache_bust Variant Boolean or Empty. If Empty, uses global setting. If True/False, overrides. | |||||
| ' @returns String Full URL to asset | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function AssetUrl(asset_path, use_cache_bust) | |||||
| Dim url, shouldBust | |||||
| url = m_app_url & asset_path | |||||
| ' Determine if we should cache-bust | |||||
| If IsEmpty(use_cache_bust) Then | |||||
| shouldBust = m_enable_cache_busting | |||||
| Else | |||||
| shouldBust = CBool(use_cache_bust) | |||||
| End If | |||||
| If shouldBust Then | |||||
| url = AppendCacheBustParam(url) | |||||
| End If | |||||
| AssetUrl = url | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Generate URL for route with optional cache-busting | |||||
| ' | |||||
| ' @param controller_name String Name of controller | |||||
| ' @param action_name String Name of action | |||||
| ' @param params_array KV Array Optional query params | |||||
| ' @param use_cache_bust Variant Boolean or Empty. If Empty, uses global setting | |||||
| ' @returns String URL with optional cache-busting | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Function UrlToWithCacheBust(controller_name, action_name, params_array, use_cache_bust) | |||||
| Dim url | |||||
| url = UrlTo(controller_name, action_name, params_array) | |||||
| ' Determine if we should cache-bust | |||||
| Dim shouldBust | |||||
| If IsEmpty(use_cache_bust) Then | |||||
| shouldBust = m_enable_cache_busting | |||||
| Else | |||||
| shouldBust = CBool(use_cache_bust) | |||||
| End If | |||||
| If shouldBust Then | |||||
| url = AppendCacheBustParam(url) | |||||
| End If | |||||
| UrlToWithCacheBust = url | |||||
| End Function | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' PRIVATE HELPER METHODS | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Private Function TO_Querystring(the_array) | |||||
| Dim result, idx | |||||
| result = "" | |||||
| If Not IsEmpty(the_array) And IsArray(the_array) Then | |||||
| ' Process key-value pairs (array with even number of elements) | |||||
| For idx = LBound(the_array) To UBound(the_array) Step 2 | |||||
| If idx + 1 <= UBound(the_array) Then | |||||
| result = result & GetParam(the_array, idx) | |||||
| ' Append & between parameters, but not on the last parameter | |||||
| If Not (idx >= UBound(the_array) - 1) Then | |||||
| result = result & "&" | |||||
| End If | |||||
| End If | |||||
| Next | |||||
| End If | |||||
| TO_Querystring = result | |||||
| End Function | |||||
| Private Function GetParam(params_array, key_idx) | |||||
| Dim key, val | |||||
| key = Server.URLEncode(CStr(params_array(key_idx))) | |||||
| val = Server.URLEncode(CStr(params_array(key_idx + 1))) | |||||
| GetParam = key & "=" & val | |||||
| End Function | |||||
| Private Function AppendCacheBustParam(url) | |||||
| Dim separator | |||||
| ' Determine if we need ? or & | |||||
| If InStr(url, "?") > 0 Then | |||||
| separator = "&" | |||||
| Else | |||||
| separator = "?" | |||||
| End If | |||||
| AppendCacheBustParam = url & separator & m_cache_bust_param_name & "=" & NoCacheToken | |||||
| End Function | |||||
| End Class | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Singleton accessor | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Dim Route_Helper__Singleton | |||||
| Set Route_Helper__Singleton = Nothing | |||||
| Function Routes() | |||||
| If Route_Helper__Singleton Is Nothing Then | |||||
| Set Route_Helper__Singleton = New Route_Helper_Class | |||||
| End If | |||||
| Set Routes = Route_Helper__Singleton | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,73 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' StringBuilder Class | |||||
| '======================================================================================================================= | |||||
| Class StringBuilder_Class | |||||
| dim m_array | |||||
| dim m_array_size | |||||
| dim m_cur_pos | |||||
| Private Sub Class_Initialize | |||||
| m_array = Array | |||||
| m_array_size = 100 | |||||
| redim m_array(m_array_size) | |||||
| m_cur_pos = -1 | |||||
| End Sub | |||||
| Private Sub Extend | |||||
| m_array_size = m_array_size + 100 | |||||
| redim preserve m_array(m_array_size) | |||||
| End Sub | |||||
| Public Sub Add(s) | |||||
| m_cur_pos = m_cur_pos + 1 | |||||
| m_array(m_cur_pos) = s | |||||
| if m_cur_pos = m_array_size then Extend | |||||
| End Sub | |||||
| Public Function [Get](delim) | |||||
| 'have to create a new array containing only the slots actually used, otherwise Join() happily adds delim | |||||
| 'for *every* slot even the unused ones... | |||||
| dim new_array : new_array = Array() | |||||
| redim new_array(m_cur_pos) | |||||
| dim i | |||||
| for i = 0 to m_cur_pos | |||||
| new_array(i) = m_array(i) | |||||
| next | |||||
| [Get] = Join(new_array, delim) | |||||
| End Function | |||||
| Public Default Property Get TO_String | |||||
| TO_String = Join(m_array, "") | |||||
| End Property | |||||
| End Class | |||||
| Function StringBuilder() | |||||
| set StringBuilder = new StringBuilder_Class | |||||
| End Function | |||||
| '======================================================================================================================= | |||||
| ' Misc | |||||
| '======================================================================================================================= | |||||
| Function Excerpt(text, length) | |||||
| Excerpt = Left(text, length) & " ..." | |||||
| End Function | |||||
| Function IsBlank(text) | |||||
| If IsObject(text) then | |||||
| If text Is Nothing then | |||||
| IsBlank = true | |||||
| Else | |||||
| IsBlank = false | |||||
| End If | |||||
| Else | |||||
| If IsEmpty(text) or IsNull(text) or Len(text) = 0 then | |||||
| IsBlank = true | |||||
| Else | |||||
| IsBlank = false | |||||
| End If | |||||
| End If | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,250 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' Validation Classes | |||||
| '======================================================================================================================= | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| ' Exists Validation | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| Class ExistsValidation_Class | |||||
| Private m_instance | |||||
| Private m_field_name | |||||
| Private m_message | |||||
| Private m_ok | |||||
| Public Function Initialize(instance, field_name, message) | |||||
| set m_instance = instance | |||||
| m_field_name = field_name | |||||
| m_message = message | |||||
| m_ok = true | |||||
| set Initialize = Me | |||||
| End Function | |||||
| Public Sub Check | |||||
| If Len(eval("m_instance." & m_field_name)) = 0 then | |||||
| m_ok = false | |||||
| End If | |||||
| End Sub | |||||
| Public Property Get OK | |||||
| OK = m_ok | |||||
| End Property | |||||
| Public Property Get Message | |||||
| Message = m_message | |||||
| End Property | |||||
| End Class | |||||
| Sub ValidateExists(instance, field_name, message) | |||||
| if not IsObject(instance.Validator) then set instance.Validator = new Validator_Class | |||||
| instance.Validator.AddValidation new ExistsValidation_Class.Initialize(instance, field_name, message) | |||||
| End Sub | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| ' Minimum Length Validation | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| Class MinLengthValidation_Class | |||||
| Private m_instance | |||||
| Private m_field_name | |||||
| Private m_size | |||||
| Private m_message | |||||
| Private m_ok | |||||
| Public Function Initialize(instance, field_name, size, message) | |||||
| set m_instance = instance | |||||
| m_field_name = field_name | |||||
| m_size = size | |||||
| m_message = message | |||||
| m_ok = true | |||||
| set Initialize = Me | |||||
| End Function | |||||
| Public Sub Check | |||||
| If Len(eval("m_instance." & m_field_name)) < m_size then m_ok = false | |||||
| End Sub | |||||
| Public Property Get OK | |||||
| OK = m_ok | |||||
| End Property | |||||
| Public Property Get Message | |||||
| Message = m_message | |||||
| End Property | |||||
| End Class | |||||
| Sub ValidateMinLength(instance, field_name, size, message) | |||||
| if not IsObject(instance.Validator) then set instance.Validator = new Validator_Class | |||||
| instance.Validator.AddValidation new MinLengthValidation_Class.Initialize(instance, field_name, size, message) | |||||
| End Sub | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| ' Max Length Validation | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| Class MaxLengthValidation_Class | |||||
| Private m_instance | |||||
| Private m_field_name | |||||
| Private m_size | |||||
| Private m_message | |||||
| Private m_ok | |||||
| Public Function Initialize(instance, field_name, size, message) | |||||
| set m_instance = instance | |||||
| m_field_name = field_name | |||||
| m_size = size | |||||
| m_message = message | |||||
| m_ok = true | |||||
| set Initialize = Me | |||||
| End Function | |||||
| Public Sub Check | |||||
| If Len(eval("m_instance." & m_field_name)) > m_size then m_ok = false | |||||
| End Sub | |||||
| Public Property Get OK | |||||
| OK = m_ok | |||||
| End Property | |||||
| Public Property Get Message | |||||
| Message = m_message | |||||
| End Property | |||||
| End Class | |||||
| Sub ValidateMaxLength(instance, field_name, size, message) | |||||
| if not IsObject(instance.Validator) then set instance.Validator = new Validator_Class | |||||
| instance.Validator.AddValidation new MaxLengthValidation_Class.Initialize(instance, field_name, size, message) | |||||
| End Sub | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| ' Numeric Validation | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| Class NumericValidation_Class | |||||
| Private m_instance | |||||
| Private m_field_name | |||||
| Private m_message | |||||
| Private m_ok | |||||
| Public Function Initialize(instance, field_name, message) | |||||
| set m_instance = instance | |||||
| m_field_name = field_name | |||||
| m_message = message | |||||
| m_ok = true | |||||
| set Initialize = Me | |||||
| End Function | |||||
| Public Sub Check | |||||
| If Not IsNumeric(eval("m_instance." & m_field_name)) then m_ok = false | |||||
| End Sub | |||||
| Public Property Get OK | |||||
| OK = m_ok | |||||
| End Property | |||||
| Public Property Get Message | |||||
| Message = m_message | |||||
| End Property | |||||
| End Class | |||||
| Sub ValidateNumeric(instance, field_name, message) | |||||
| if not IsObject(instance.Validator) then set instance.Validator = new Validator_Class | |||||
| instance.Validator.AddValidation new NumericValidation_Class.Initialize(instance, field_name, message) | |||||
| End Sub | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| ' Regular Expression Pattern Validation | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| Class PatternValidation_Class | |||||
| Private m_instance | |||||
| Private m_field_name | |||||
| Private m_pattern | |||||
| Private m_message | |||||
| Private m_ok | |||||
| Public Function Initialize(instance, field_name, pattern, message) | |||||
| set m_instance = instance | |||||
| m_field_name = field_name | |||||
| m_pattern = pattern | |||||
| m_message = message | |||||
| m_ok = true | |||||
| set Initialize = Me | |||||
| End Function | |||||
| Public Sub Check | |||||
| dim re : set re = new RegExp | |||||
| With re | |||||
| .Pattern = m_pattern | |||||
| .Global = true | |||||
| .IgnoreCase = true | |||||
| End With | |||||
| dim matches : set matches = re.Execute(eval("m_instance." & m_field_name)) | |||||
| if matches.Count = 0 then | |||||
| m_ok = false | |||||
| end if | |||||
| End Sub | |||||
| Public Property Get OK | |||||
| OK = m_ok | |||||
| End Property | |||||
| Public Property Get Message | |||||
| Message = m_message | |||||
| End Property | |||||
| End Class | |||||
| Sub ValidatePattern(instance, field_name, pattern, message) | |||||
| if not IsObject(instance.Validator) then set instance.Validator = new Validator_Class | |||||
| instance.Validator.AddValidation new PatternValidation_Class.Initialize(instance, field_name, pattern, message) | |||||
| End Sub | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| ' Validator Class | |||||
| ' This class is not intended to be used directly. Models should use the Validate* subs instead. | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| Class Validator_Class | |||||
| Private m_validations | |||||
| Private m_errors | |||||
| Private Sub Class_Initialize | |||||
| m_validations = Array() | |||||
| redim m_validations(-1) | |||||
| m_errors = Array() | |||||
| redim m_errors(-1) | |||||
| End Sub | |||||
| Public Property Get Errors | |||||
| Errors = m_errors | |||||
| End Property | |||||
| Public Sub AddValidation(validation) | |||||
| dim n : n = ubound(m_validations) + 1 | |||||
| redim preserve m_validations(n) | |||||
| set m_validations(n) = validation | |||||
| End Sub | |||||
| Public Sub Validate | |||||
| dim n : n = ubound(m_validations) | |||||
| dim i, V | |||||
| for i = 0 to n | |||||
| set V = m_validations(i) | |||||
| V.Check | |||||
| if not V.OK then | |||||
| AddError V.Message | |||||
| end if | |||||
| next | |||||
| End Sub | |||||
| Public Property Get HasErrors | |||||
| HasErrors = (ubound(m_errors) > -1) | |||||
| End Property | |||||
| 'Public to allow other errors to be added by the controller for circumstances not accounted for by the validators | |||||
| Public Sub AddError(msg) | |||||
| redim preserve m_errors(ubound(m_errors) + 1) | |||||
| m_errors(ubound(m_errors)) = msg | |||||
| End Sub | |||||
| End Class | |||||
| %> | |||||
| @@ -0,0 +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 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 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 | |||||
| Set crypto = Server.CreateObject("G3CRYPTO") | |||||
| CheckPassword = crypto.VerifyPassword(password, storedHash) | |||||
| Set crypto = Nothing | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,115 @@ | |||||
| <% | |||||
| 'protocol = IIf(LCase(Request.ServerVariables("HTTPS")) = "1", "https", "http") | |||||
| protocol = "https" | |||||
| Dim timeZones | |||||
| timeZones = Array( _ | |||||
| Array("America/New_York", "Eastern (New York)"), _ | |||||
| Array("America/Chicago", "Central (Chicago)"), _ | |||||
| Array("America/Denver", "Mountain (Denver)"), _ | |||||
| Array("America/Los_Angeles", "Pacific (Los Angeles)"), _ | |||||
| Array("Europe/London", "London (UK)") _ | |||||
| ) | |||||
| Function RequestBinary() | |||||
| On Error Resume Next | |||||
| Dim stream, rawData | |||||
| If Request.TotalBytes = 0 Then | |||||
| RequestBinary = "" | |||||
| Exit Function | |||||
| End If | |||||
| Set stream = Server.CreateObject("ADODB.Stream") | |||||
| stream.Type = 1 ' adTypeBinary | |||||
| stream.Open | |||||
| stream.Write Request.BinaryRead(Request.TotalBytes) | |||||
| stream.Position = 0 | |||||
| stream.Type = 2 ' adTypeText | |||||
| stream.Charset = "utf-8" | |||||
| rawData = stream.ReadText | |||||
| stream.Close | |||||
| Set stream = Nothing | |||||
| If Err.Number <> 0 Then | |||||
| rawData = "" | |||||
| Err.Clear | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| RequestBinary = rawData | |||||
| End Function | |||||
| Function ArrayContains(arr, val) | |||||
| Dim i | |||||
| ArrayContains = False | |||||
| If IsArray(arr) Then | |||||
| For i = LBound(arr) To UBound(arr) | |||||
| If arr(i) = val Then | |||||
| ArrayContains = True | |||||
| Exit Function | |||||
| End If | |||||
| Next | |||||
| End If | |||||
| End Function | |||||
| Function RenderPOBOArrayAsJson(pobo) | |||||
| Dim i, j, obj, propList, propName, json, propVal, line,poboArray | |||||
| if IsLinkedList(pobo) Then | |||||
| poboArray = pobo.TO_Array() | |||||
| End If | |||||
| json = "[" | |||||
| If IsEmpty(poboArray) Then | |||||
| RenderPOBOArrayAsJson = "[]" | |||||
| Exit Function | |||||
| End If | |||||
| For i = 0 To UBound(poboArray) | |||||
| Set obj = poboArray(i) | |||||
| propList = obj.Properties | |||||
| line = "{" | |||||
| For j = 0 To UBound(propList) | |||||
| propName = propList(j) | |||||
| ' Dynamically get value using Execute | |||||
| Execute "propVal = obj." & propName | |||||
| Select Case VarType(propVal) | |||||
| Case vbString | |||||
| line = line & """" & propName & """:""" & JsonEscape(propVal) & """" | |||||
| Case vbBoolean | |||||
| line = line & """" & propName & """:" & LCase(CStr(propVal)) | |||||
| Case vbDate | |||||
| line = line & """" & propName & """:""" & Replace(CStr(propVal), """", "") & """" | |||||
| Case vbNull | |||||
| line = line & """" & propName & """:null" | |||||
| Case Else | |||||
| line = line & """" & propName & """:" & CStr(propVal) | |||||
| End Select | |||||
| If j < UBound(propList) Then | |||||
| line = line & "," | |||||
| End If | |||||
| Next | |||||
| line = line & "}" | |||||
| If i < UBound(poboArray) Then line = line & "," | |||||
| json = json & line | |||||
| Next | |||||
| json = json & "]" | |||||
| RenderPOBOArrayAsJson = json | |||||
| End Function | |||||
| Function JsonEscape(str) | |||||
| str = Replace(str, "\", "\\") | |||||
| str = Replace(str, """", "\""") | |||||
| str = Replace(str, vbCrLf, "\n") | |||||
| str = Replace(str, vbLf, "\n") | |||||
| str = Replace(str, vbCr, "\n") | |||||
| str = Replace(str, Chr(9), "\t") | |||||
| JsonEscape = str | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,167 @@ | |||||
| <!--#include file="../app/models/autoload_models.asp" --> | |||||
| <!--#include file="../app/controllers/autoload_controllers.asp" --> | |||||
| <% | |||||
| ' Set cache expiration from configuration | |||||
| Dim cacheYear : cacheYear = GetAppSetting("CacheExpirationYear") | |||||
| If cacheYear = "nothing" Then cacheYear = "2030" | |||||
| Response.ExpiresAbsolute = "01/01/" & cacheYear | |||||
| Response.AddHeader "pragma", "no-cache" | |||||
| Response.AddHeader "cache-control", "private, no-cache, must-revalidate" | |||||
| '======================================================================================================================= | |||||
| ' MVC Dispatcher | |||||
| '======================================================================================================================= | |||||
| Class MVC_Dispatcher_Class | |||||
| dim CurrentController | |||||
| Public Property Get ControllerName | |||||
| ControllerName = CurrentController | |||||
| end Property | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Convenience method to resolve route and dispatch in one call | |||||
| ' method: HTTP method (GET, POST, etc.) | |||||
| ' path: Request path (already cleaned of query params) | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub DispatchRequest(method, path) | |||||
| Dim routeArray | |||||
| routeArray = GetRouter().Resolve(method, path) | |||||
| Dispatch routeArray | |||||
| End Sub | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| ' Main dispatch method - executes a resolved route | |||||
| ' RouteArray: Array(controller, action, params) from GetRouter().Resolve() | |||||
| '--------------------------------------------------------------------------------------------------------------------- | |||||
| Public Sub Dispatch(RouteArray) | |||||
| On Error Resume Next | |||||
| Dim controllerName, actionName, hasParams, paramsArray | |||||
| controllerName = RouteArray(0) | |||||
| actionName = RouteArray(1) | |||||
| ' Security: Validate controller and action names | |||||
| If Not ControllerRegistry.IsValidControllerFormat(controllerName) Then | |||||
| Response.Write "<div style='padding:15px; margin:10px; border:2px solid #dc3545; background:#f8d7da; color:#721c24; border-radius:4px;'>" | |||||
| Response.Write "<strong>Security Error:</strong> Invalid controller name format." | |||||
| Response.Write "</div>" | |||||
| Exit Sub | |||||
| End If | |||||
| If Not ControllerRegistry.IsValidActionFormat(actionName) Then | |||||
| Response.Write "<div style='padding:15px; margin:10px; border:2px solid #dc3545; background:#f8d7da; color:#721c24; border-radius:4px;'>" | |||||
| Response.Write "<strong>Security Error:</strong> Invalid action name format." | |||||
| Response.Write "</div>" | |||||
| Exit Sub | |||||
| End If | |||||
| ' Security: Check controller whitelist | |||||
| If Not ControllerRegistry.IsValidController(controllerName) Then | |||||
| Response.Write "<div style='padding:15px; margin:10px; border:2px solid #dc3545; background:#f8d7da; color:#721c24; border-radius:4px;'>" | |||||
| Response.Write "<strong>Security Error:</strong> Controller '" & Server.HTMLEncode(controllerName) & "' is not registered." | |||||
| Response.Write "</div>" | |||||
| Exit Sub | |||||
| End If | |||||
| ' Initialize current controller | |||||
| Dim controllerAssignment : controllerAssignment = "Set CurrentController = " & controllerName & "()" | |||||
| Execute controllerAssignment | |||||
| ' Check if layout should be used | |||||
| hasParams = (UBound(RouteArray) >= 2) | |||||
| If eval(controllerName & ".useLayout") Then | |||||
| %> <!-- #include file="../app/views/shared/header.asp" --> <% | |||||
| End If | |||||
| ' Prepare parameters | |||||
| If hasParams Then | |||||
| paramsArray = SurroundStringInArray(RouteArray(2)) | |||||
| Else | |||||
| paramsArray = Empty | |||||
| End If | |||||
| ' Execute controller action | |||||
| ExecuteControllerAction controllerName, actionName, paramsArray | |||||
| ' Include footer if layout is used | |||||
| If eval(controllerName & ".useLayout") Then | |||||
| %> <!-- #include file="../app/views/shared/footer.asp" --> <% | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| End Sub | |||||
| ' Helper method to execute controller actions (eliminates code duplication) | |||||
| Private Sub ExecuteControllerAction(controllerName, actionName, paramsArray) | |||||
| On Error Resume Next | |||||
| Dim callString | |||||
| ' Build the call string based on whether we have parameters | |||||
| If Not IsEmpty(paramsArray) And IsArray(paramsArray) And UBound(paramsArray) >= 0 Then | |||||
| callString = "Call " & controllerName & "." & actionName & "(" & Join(paramsArray, ",") & ")" | |||||
| Else | |||||
| callString = "Call " & controllerName & "." & actionName & "()" | |||||
| End If | |||||
| ' Execute the action | |||||
| Execute callString | |||||
| ' Handle errors | |||||
| If Err.Number <> 0 Then | |||||
| HandleDispatchError actionName, Err.Description, Err.Number | |||||
| Err.Clear | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| End Sub | |||||
| ' Centralized error handling for dispatch errors | |||||
| Private Sub HandleDispatchError(actionName, errorDesc, errorNum) | |||||
| Dim isDevelopment | |||||
| isDevelopment = (LCase(GetAppSetting("Environment")) = "development") | |||||
| If isDevelopment Then | |||||
| Response.Write "<div style='padding:15px; margin:10px; border:2px solid #dc3545; background:#f8d7da; color:#721c24; border-radius:4px;'>" | |||||
| Response.Write "<strong>Controller Action Error</strong><br>" | |||||
| Response.Write "Action: <code>" & Server.HTMLEncode(actionName) & "</code><br>" | |||||
| Response.Write "Error: " & Server.HTMLEncode(errorDesc) & "<br>" | |||||
| Response.Write "Error Number: " & errorNum | |||||
| Response.Write "</div>" | |||||
| Else | |||||
| Response.Write "<div style='padding:15px; margin:10px; border:2px solid #dc3545; background:#f8d7da; color:#721c24; border-radius:4px;'>" | |||||
| Response.Write "<strong>An error occurred</strong><br>" | |||||
| Response.Write "Please contact the system administrator if the problem persists." | |||||
| Response.Write "</div>" | |||||
| End If | |||||
| End Sub | |||||
| Public Sub RequirePost | |||||
| If Request.Form.Count = 0 Then MVC.RedirectToExt "NotValid","",empty:End If | |||||
| End Sub | |||||
| ' Shortcut for RedirectToActionExt that does not require passing a parameters argument. | |||||
| Public Sub RedirectToAction(ByVal action_name) | |||||
| RedirectToActionExt action_name, empty | |||||
| End Sub | |||||
| Public Sub RedirectTo(controller_name, action_name) | |||||
| RedirectToExt controller_name, action_name, empty | |||||
| End Sub | |||||
| ' Redirects the browser to the specified action on the specified controller with the specified querystring parameters. | |||||
| ' params is a KVArray of querystring parameters. | |||||
| Public Sub RedirectToExt(controller_name, action_name, params) | |||||
| Response.Redirect Routes.UrlTo(controller_name, action_name, params) | |||||
| End Sub | |||||
| Public Sub RedirectToActionExt(ByVal action_name, ByVal params) | |||||
| RedirectToExt ControllerName, action_name, params | |||||
| End Sub | |||||
| End Class | |||||
| dim MVC_Dispatcher_Class__Singleton | |||||
| Function MVC() | |||||
| if IsEmpty(MVC_Dispatcher_Class__Singleton) then | |||||
| set MVC_Dispatcher_Class__Singleton = new MVC_Dispatcher_Class | |||||
| end if | |||||
| set MVC = MVC_Dispatcher_Class__Singleton | |||||
| End Function | |||||
| %> | |||||
| @@ -0,0 +1,147 @@ | |||||
| <?xml version="1.0"?> | |||||
| <!-- RouterComponent.wsc --> | |||||
| <component> | |||||
| <!-- COM registration --> | |||||
| <registration | |||||
| description = "Classic ASP Router Component" | |||||
| progid = "App.Router" | |||||
| version = "1.0" | |||||
| classid = "{A1FC6EA8-519E-4E34-AC08-77788E3E5E44}" /> | |||||
| <!-- Public interface --> | |||||
| <public> | |||||
| <method name="AddRoute"/> | |||||
| <method name="Resolve"/> | |||||
| </public> | |||||
| <!-- Give the component ASP intrinsic objects (Request, Response, Server …) --> | |||||
| <implements type="ASP"/> | |||||
| <!-- Implementation --> | |||||
| <script language="VBScript"> | |||||
| <![CDATA[ | |||||
| Option Explicit | |||||
| '------------------------------------------------------------ | |||||
| ' Private state | |||||
| '------------------------------------------------------------ | |||||
| Dim routes : Set routes = CreateObject("Scripting.Dictionary") | |||||
| '------------------------------------------------------------ | |||||
| ' 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 | |||||
| ]]> | |||||
| </script> | |||||
| </component> | |||||
| @@ -0,0 +1,16 @@ | |||||
| <!--#include file="../core/autoload_core.asp" --> | |||||
| <% | |||||
| ' Define starter application routes | |||||
| router.AddRoute "GET", "/home", "HomeController", "Index" | |||||
| router.AddRoute "GET", "/", "HomeController", "Index" | |||||
| router.AddRoute "GET", "", "HomeController", "Index" | |||||
| router.AddRoute "GET", "/404", "ErrorController", "NotFound" | |||||
| ' 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() | |||||
| %> | |||||
| @@ -0,0 +1,69 @@ | |||||
| <?xml version="1.0" encoding="UTF-8"?> | |||||
| <configuration> | |||||
| <appSettings> | |||||
| <!-- | |||||
| SQLite connection string (AxonASP ADODB layer: "sqlite:" prefix + file path). | |||||
| docker-compose.yml mounts the framework folder at /opt/axonasp/site, so db/ is /opt/axonasp/site/db. | |||||
| The file is created on first open if it does not exist. | |||||
| --> | |||||
| <add key="ConnectionString" value="sqlite:/opt/axonasp/site/db/app.sqlite" /> | |||||
| <!-- Environment flag (Development / Staging / Production) --> | |||||
| <add key="Environment" value="Development" /> | |||||
| <!-- Flash message display duration in milliseconds --> | |||||
| <add key="FlashMessageTimeout" value="3000" /> | |||||
| <!-- 404 error page redirect countdown in seconds --> | |||||
| <add key="Error404RedirectSeconds" value="5" /> | |||||
| <!-- Cache expiration year for static content --> | |||||
| <add key="CacheExpirationYear" value="2030" /> | |||||
| <!-- Maximum characters to display in table cells before truncating --> | |||||
| <add key="TableCellMaxLength" value="90" /> | |||||
| <!-- Character threshold for textarea vs input field in forms --> | |||||
| <add key="FormTextareaThreshold" value="100" /> | |||||
| <!-- Enable error logging to file (true/false) --> | |||||
| <add key="EnableErrorLogging" value="false" /> | |||||
| <!-- Error log file path (if EnableErrorLogging is true) --> | |||||
| <add key="ErrorLogPath" value="C:\YourApp\logs\errors.log" /> | |||||
| <!-- Enable cache-busting for URLs and assets (true/false) --> | |||||
| <add key="EnableCacheBusting" value="false" /> | |||||
| <!-- Cache-bust parameter name (default: "v") --> | |||||
| <add key="CacheBustParamName" value="v" /> | |||||
| </appSettings> | |||||
| <system.webServer> | |||||
| <!-- Default document for the site root --> | |||||
| <defaultDocument> | |||||
| <files> | |||||
| <clear /> | |||||
| <add value="Default.asp" /> | |||||
| </files> | |||||
| </defaultDocument> | |||||
| <!-- URL Rewrite: send everything that is not an existing file/folder through Default.asp (RE2: no lookahead; the original path is passed as __route) --> | |||||
| <rewrite> | |||||
| <rules> | |||||
| <rule name="Rewrite to Default.asp" stopProcessing="true"> | |||||
| <match url="^(.+)$" /> | |||||
| <conditions> | |||||
| <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> | |||||
| <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> | |||||
| </conditions> | |||||
| <action type="Rewrite" url="/Default.asp?__route=/{R:1}" appendQueryString="true" /> | |||||
| </rule> | |||||
| </rules> | |||||
| </rewrite> | |||||
| </system.webServer> | |||||
| </configuration> | |||||
| @@ -0,0 +1,611 @@ | |||||
| '============================================================== | |||||
| ' GenerateApi.vbs (AxonASP CLI + G3DB edition) | |||||
| ' | |||||
| ' Usage (runs under the AxonASP CLI in the container; gen.cmd runs GenerateRepo.vbs first): | |||||
| ' scripts\gen.cmd api /table:Products /pk:Id | |||||
| ' | |||||
| ' Sets up a JSON API for one table: | |||||
| ' app/controllers/Api<Table>Controller.asp controller (list/search/paging, show, create, PUT, PATCH, delete) | |||||
| ' app/controllers/autoload_controllers.asp include line added | |||||
| ' app/models/autoload_models.asp POBO + repository include lines added | |||||
| ' core/lib.ControllerRegistry.asp controller whitelisted | |||||
| ' public/Default.asp 6 routes under /api/<table> added | |||||
| ' public/api/<table>.openapi.json OpenAPI spec (shows up in the /api/docs Swagger UI) | |||||
| ' api-tests/<table>.http sample requests (VS Code REST Client) | |||||
| ' | |||||
| ' Notes: a JSON null is not accepted for a field (omit it instead). Needs app/models/POBO_<Table>.asp and <Table>Repository.asp (GenerateRepo.vbs). Refuses to overwrite an | |||||
| ' existing controller. Validation is derived from the column types and NOT NULL / DEFAULT; add business rules | |||||
| ' (ranges, lengths) in the generated controller by hand. | |||||
| '============================================================== | |||||
| Option Explicit | |||||
| ' AxonASP CLI: provide the WScript object (see _cli.vbs) | |||||
| Dim shimFso | |||||
| Set shimFso = CreateObject("Scripting.FileSystemObject") | |||||
| ExecuteGlobal shimFso.OpenTextFile(Server.MapPath("/scripts/_cli.vbs"), 1).ReadAll | |||||
| Dim fso, args, i, arg, parts, tableName, primaryKey, csKey, configPath | |||||
| Set fso = CreateObject("Scripting.FileSystemObject") | |||||
| Set args = WScript.Arguments | |||||
| csKey = "ConnectionString" | |||||
| configPath = Server.MapPath("/public/web.config") | |||||
| For i = 0 To args.Count - 1 | |||||
| arg = args(i) | |||||
| If InStr(arg, ":") > 0 Then | |||||
| parts = Split(arg, ":", 2) | |||||
| Select Case LCase(Replace(parts(0), "/", "")) | |||||
| Case "table": tableName = parts(1) | |||||
| Case "pk": primaryKey = parts(1) | |||||
| End Select | |||||
| End If | |||||
| Next | |||||
| If Len(tableName) = 0 Or Len(primaryKey) = 0 Then | |||||
| WScript.Echo "Usage: scripts\gen.cmd api /table:<TableName> /pk:<PrimaryKey>" | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| If Not IsValidIdentifier(tableName) Or Not IsValidIdentifier(primaryKey) Then | |||||
| WScript.Echo "Error: table and primary key may only contain letters, numbers and underscores." | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| Dim ctrlPath, routeName, constName | |||||
| routeName = LCase(tableName) | |||||
| constName = "API_" & UCase(tableName) | |||||
| ctrlPath = Server.MapPath("/app/controllers/Api" & tableName & "Controller.asp") | |||||
| If fso.FileExists(ctrlPath) Then | |||||
| WScript.Echo "Error: " & ctrlPath & " already exists. Delete it first if you want to regenerate." | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| If Not fso.FileExists(Server.MapPath("/app/models/" & tableName & "Repository.asp")) Then | |||||
| WScript.Echo "Error: app/models/" & tableName & "Repository.asp not found. Run: scripts\gen.cmd repo /table:" & tableName & " /pk:" & primaryKey | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| '---------------- Connection + schema ---------------- | |||||
| Dim connStr, p, dsn, db | |||||
| connStr = GetAppSetting(csKey, configPath) | |||||
| p = InStr(connStr, ":") | |||||
| If connStr = "nothing" Or p < 2 Then | |||||
| WScript.Echo "Error: ConnectionString not found or malformed in " & configPath | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| If LCase(Left(connStr, p - 1)) <> "sqlite" Then | |||||
| WScript.Echo "Error: schema discovery is implemented for SQLite only." | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| dsn = Mid(connStr, p + 1) | |||||
| Set db = Server.CreateObject("G3DB") | |||||
| If Not db.Open("sqlite", dsn) Then | |||||
| WScript.Echo "DB connection failed: " & db.LastError | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| ' cols(i) name, kinds(i) string|int|real|bool|date, needs(i) True when NOT NULL without DEFAULT, isPk(i) | |||||
| Dim cols(), kinds(), needs(), isPk(), dflts(), idx, rs, declType, notNull, dflt, pkFlag | |||||
| idx = -1 | |||||
| Set rs = db.Query("PRAGMA table_info(" & tableName & ")") | |||||
| If IsEmpty(rs) Then | |||||
| WScript.Echo "Error reading table [" & tableName & "]: " & db.LastError | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| Do Until rs.EOF | |||||
| idx = idx + 1 | |||||
| ReDim Preserve cols(idx), kinds(idx), needs(idx), isPk(idx), dflts(idx) | |||||
| cols(idx) = CStr(rs(1)) | |||||
| declType = "" & rs(2) | |||||
| notNull = rs(3) | |||||
| dflt = rs(4) | |||||
| dflts(idx) = dflt | |||||
| pkFlag = rs(5) | |||||
| kinds(idx) = ApiKind(declType) | |||||
| isPk(idx) = (StrEqualCI(cols(idx), primaryKey) Or CLng(pkFlag) > 0) | |||||
| needs(idx) = (CLng(notNull) = 1 And IsNull(dflt) And Not isPk(idx)) | |||||
| rs.MoveNext | |||||
| Loop | |||||
| rs.Close | |||||
| db.Close | |||||
| If idx < 0 Then | |||||
| WScript.Echo "No columns found for table [" & tableName & "]. Run the migrations first." | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| '---------------- Build the pieces ---------------- | |||||
| Dim newDefaults, updStamps, dv, members, clearFields, parseBody, applyBody, rowJson, docFields, searchCols, orderCol, writable | |||||
| newDefaults = "" : updStamps = "" : members = "" : clearFields = "" : parseBody = "" : applyBody = "" : rowJson = "" : docFields = "" : searchCols = "" : orderCol = primaryKey | |||||
| writable = 0 | |||||
| Dim q | |||||
| q = Chr(34) | |||||
| For i = 0 To idx | |||||
| Dim c, camel, fv | |||||
| c = cols(i) | |||||
| camel = LCase(Left(c, 1)) & Mid(c, 2) | |||||
| fv = "f_" & c | |||||
| ' ---- output JSON (all columns) | |||||
| If Len(rowJson) = 0 Then | |||||
| rowJson = q & "{" & q & q & camel & q & q & ":" & q & " & " & JsonExpr(c, kinds(i), isPk(i)) | |||||
| Else | |||||
| rowJson = rowJson & " & _" & vbCrLf & " " & q & "," & q & q & camel & q & q & ":" & q & " & " & JsonExpr(c, kinds(i), isPk(i)) | |||||
| End If | |||||
| ' ---- first string column is the default sort, string columns are searchable | |||||
| If kinds(i) = "string" And Not isPk(i) Then | |||||
| If Len(searchCols) > 0 Then searchCols = searchCols & ", " | |||||
| searchCols = searchCols & """" & c & """" | |||||
| If orderCol = primaryKey Then orderCol = c | |||||
| End If | |||||
| If isPk(i) Then | |||||
| docFields = docFields & "' " & camel & " (read-only primary key)" & vbCrLf | |||||
| ElseIf IsStampCol(c, kinds(i)) Then | |||||
| ' CreatedAt / UpdatedAt are managed by the server | |||||
| If LCase(c) = "createdat" Then | |||||
| newDefaults = newDefaults & " rec." & c & " = NowStamp()" & vbCrLf | |||||
| Else | |||||
| newDefaults = newDefaults & " rec." & c & " = NowStamp()" & vbCrLf | |||||
| updStamps = updStamps & " rec." & c & " = NowStamp()" & vbCrLf | |||||
| End If | |||||
| docFields = docFields & "' " & camel & " (set by the server)" & vbCrLf | |||||
| Else | |||||
| writable = writable + 1 | |||||
| dv = DefaultLiteral(dflts(i)) | |||||
| If Len(dv) > 0 Then | |||||
| newDefaults = newDefaults & " rec." & c & " = " & dv & vbCrLf | |||||
| End If | |||||
| members = members & " Private " & fv & vbCrLf | |||||
| clearFields = clearFields & " " & fv & " = Empty" & vbCrLf | |||||
| parseBody = parseBody & BuildParse(c, camel, fv, kinds(i), needs(i)) | |||||
| applyBody = applyBody & " If Not IsEmpty(" & fv & ") Then" & vbCrLf & _ | |||||
| " rec." & c & " = " & fv & vbCrLf & _ | |||||
| " End If" & vbCrLf | |||||
| docFields = docFields & "' " & c & " (" & kinds(i) & Pick(needs(i), ", required", "") & ")" & vbCrLf | |||||
| End If | |||||
| Next | |||||
| rowJson = rowJson & " & ""}""" | |||||
| If Len(searchCols) = 0 Then | |||||
| searchCols = "Empty" | |||||
| Else | |||||
| searchCols = "Array(" & searchCols & ")" | |||||
| End If | |||||
| docFields = Left(docFields, Len(docFields) - 2) | |||||
| '---------------- Write the controller ---------------- | |||||
| Dim t | |||||
| t = ReadTemplate("Api.tpl.asp") | |||||
| t = Replace(t, "{{TABLE}}", tableName) | |||||
| t = Replace(t, "{{PK}}", primaryKey) | |||||
| t = Replace(t, "{{ROUTE}}", routeName) | |||||
| t = Replace(t, "{{CONST}}", constName) | |||||
| If Len(updStamps) = 0 Then | |||||
| t = Replace(t, "{{UPDATE_STAMPS}}" & vbLf, "") | |||||
| t = Replace(t, "{{UPDATE_STAMPS}}" & vbCrLf, "") | |||||
| Else | |||||
| t = Replace(t, "{{UPDATE_STAMPS}}", Left(updStamps, Len(updStamps) - 2)) | |||||
| End If | |||||
| If Len(newDefaults) = 0 Then | |||||
| t = Replace(t, "{{NEW_DEFAULTS}}" & vbCrLf, "") | |||||
| Else | |||||
| t = Replace(t, "{{NEW_DEFAULTS}}", Left(newDefaults, Len(newDefaults) - 2)) | |||||
| End If | |||||
| t = Replace(t, "{{DATE}}", CStr(Now())) | |||||
| t = Replace(t, "{{DOC_FIELDS}}", docFields) | |||||
| t = Replace(t, "{{MEMBERS}}", Left(members, Len(members) - 2)) | |||||
| t = Replace(t, "{{CLEAR_FIELDS}}", Left(clearFields, Len(clearFields) - 2)) | |||||
| t = Replace(t, "{{PARSE_BODY}}", parseBody) | |||||
| t = Replace(t, "{{APPLY_BODY}}", Left(applyBody, Len(applyBody) - 2)) | |||||
| t = Replace(t, "{{SEARCH_COLS}}", searchCols) | |||||
| t = Replace(t, "{{ORDER_COL}}", orderCol) | |||||
| t = Replace(t, "{{ROW_JSON}}", rowJson) | |||||
| WriteFile ctrlPath, t | |||||
| WScript.Echo "Controller: " & ctrlPath | |||||
| '---------------- Wire it up ---------------- | |||||
| AppendIfMissing "/app/models/autoload_models.asp", "POBO_" & tableName & ".asp", "<!--#include file=""POBO_" & tableName & ".asp"" -->" | |||||
| AppendIfMissing "/app/models/autoload_models.asp", tableName & "Repository.asp", "<!--#include file=""" & tableName & "Repository.asp"" -->" | |||||
| AppendIfMissing "/app/controllers/autoload_controllers.asp", "Api" & tableName & "Controller.asp", "<!--#include file=""Api" & tableName & "Controller.asp"" -->" | |||||
| WScript.Echo "Includes: autoload_models.asp, autoload_controllers.asp" | |||||
| InsertAfterLine "/core/lib.ControllerRegistry.asp", "RegisterController ""errorcontroller""", "api" & LCase(tableName) & "controller", _ | |||||
| " RegisterController ""api" & LCase(tableName) & "controller""" | |||||
| WScript.Echo "Registry: api" & LCase(tableName) & "controller whitelisted" | |||||
| Dim r | |||||
| r = vbTab & "' " & tableName & " JSON API (generated by GenerateApi.vbs)" & vbCrLf & _ | |||||
| vbTab & "router.AddRoute ""GET"", ""/api/" & routeName & """, ""Api" & tableName & "Controller"", ""Index""" & vbCrLf & _ | |||||
| vbTab & "router.AddRoute ""POST"", ""/api/" & routeName & """, ""Api" & tableName & "Controller"", ""Create""" & vbCrLf & _ | |||||
| vbTab & "router.AddRoute ""GET"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Show""" & vbCrLf & _ | |||||
| vbTab & "router.AddRoute ""PUT"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Update""" & vbCrLf & _ | |||||
| vbTab & "router.AddRoute ""PATCH"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Update""" & vbCrLf & _ | |||||
| vbTab & "router.AddRoute ""DELETE"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Delete""" & vbCrLf & vbCrLf | |||||
| InsertBeforeLine "/public/Default.asp", "' Dispatch the request", "Api" & tableName & "Controller", r | |||||
| WScript.Echo "Routes: /api/" & routeName & " and /api/" & routeName & "/:id added to public/Default.asp" | |||||
| '---------------- Spec + sample requests ---------------- | |||||
| Dim specDir, specPath | |||||
| specDir = Server.MapPath("/public/api") | |||||
| If Not fso.FolderExists(specDir) Then fso.CreateFolder specDir | |||||
| specPath = specDir & "/" & routeName & ".openapi.json" | |||||
| WriteFile specPath, BuildSpec() | |||||
| WScript.Echo "OpenAPI spec: " & specPath | |||||
| Dim httpDir, httpPath | |||||
| httpDir = Server.MapPath("/api-tests") | |||||
| If Not fso.FolderExists(httpDir) Then fso.CreateFolder httpDir | |||||
| httpPath = httpDir & "/" & routeName & ".http" | |||||
| WriteFile httpPath, BuildHttp() | |||||
| WScript.Echo "Sample calls: " & httpPath | |||||
| WScript.Echo "" | |||||
| WScript.Echo "Done. Restart the container (docker restart axonasp), then open /api/docs and pick '" & tableName & "' in the spec list." | |||||
| '============================================================== | |||||
| ' Code generation | |||||
| '============================================================== | |||||
| Function BuildParse(c, camel, fv, kind, required) | |||||
| Dim s, label | |||||
| label = c | |||||
| s = " k = """"" & vbCrLf | |||||
| s = s & " If input.Exists(""" & c & """) Then" & vbCrLf | |||||
| s = s & " k = """ & c & """" & vbCrLf | |||||
| If camel <> c Then | |||||
| s = s & " ElseIf input.Exists(""" & camel & """) Then" & vbCrLf | |||||
| s = s & " k = """ & camel & """" & vbCrLf | |||||
| End If | |||||
| s = s & " End If" & vbCrLf | |||||
| s = s & " If Len(k) > 0 Then" & vbCrLf | |||||
| s = s & " v = input.Item(k)" & vbCrLf | |||||
| Select Case kind | |||||
| Case "string" | |||||
| s = s & " v = Trim("""" & v)" & vbCrLf | |||||
| If required Then | |||||
| s = s & " If Len(v) = 0 Then" & vbCrLf | |||||
| s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " is required.""" & vbCrLf | |||||
| s = s & " End If" & vbCrLf | |||||
| End If | |||||
| s = s & " " & fv & " = v" & vbCrLf | |||||
| Case "int", "real" | |||||
| s = s & " If VarType(v) = 11 Then" & vbCrLf | |||||
| s = s & " v = CLng(v) * -1" & vbCrLf | |||||
| s = s & " End If" & vbCrLf | |||||
| s = s & " If IsNumeric(v) And Not IsNull(v) And VarType(v) <> 8 Then" & vbCrLf | |||||
| If kind = "int" Then | |||||
| s = s & " If CDbl(v) <> Int(CDbl(v)) Then" & vbCrLf | |||||
| s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be a whole number.""" & vbCrLf | |||||
| s = s & " Else" & vbCrLf | |||||
| s = s & " " & fv & " = CLng(v)" & vbCrLf | |||||
| s = s & " End If" & vbCrLf | |||||
| Else | |||||
| s = s & " " & fv & " = CDbl(v)" & vbCrLf | |||||
| End If | |||||
| s = s & " Else" & vbCrLf | |||||
| s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be a number.""" & vbCrLf | |||||
| s = s & " End If" & vbCrLf | |||||
| Case "bool" | |||||
| s = s & " If VarType(v) = 11 Then" & vbCrLf | |||||
| s = s & " " & fv & " = v" & vbCrLf | |||||
| s = s & " ElseIf IsNumeric(v) And Not IsNull(v) And VarType(v) <> 8 Then" & vbCrLf | |||||
| s = s & " " & fv & " = (CDbl(v) <> 0)" & vbCrLf | |||||
| s = s & " Else" & vbCrLf | |||||
| s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be true or false.""" & vbCrLf | |||||
| s = s & " End If" & vbCrLf | |||||
| Case "date" | |||||
| s = s & " If IsDate(v) Then" & vbCrLf | |||||
| s = s & " " & fv & " = CDate(v)" & vbCrLf | |||||
| s = s & " Else" & vbCrLf | |||||
| s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be a date.""" & vbCrLf | |||||
| s = s & " End If" & vbCrLf | |||||
| End Select | |||||
| If required Then | |||||
| s = s & " ElseIf Not partial Then" & vbCrLf | |||||
| s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " is required.""" & vbCrLf | |||||
| End If | |||||
| s = s & " End If" & vbCrLf & vbCrLf | |||||
| BuildParse = s | |||||
| End Function | |||||
| ' VBScript expression (generator output) that renders column c of "rec" as a JSON value | |||||
| Function JsonExpr(c, kind, pk) | |||||
| If pk Or kind = "int" Then | |||||
| JsonExpr = "CLng(rec." & c & ")" | |||||
| ElseIf kind = "real" Then | |||||
| JsonExpr = "JsonLite_Num(rec." & c & ")" | |||||
| ElseIf kind = "bool" Then | |||||
| JsonExpr = "LCase(CStr(CBool(rec." & c & ")))" | |||||
| ElseIf kind = "date" Then | |||||
| JsonExpr = "JsonDate(rec." & c & ")" | |||||
| Else | |||||
| JsonExpr = "JsonLite_Quote(rec." & c & ")" | |||||
| End If | |||||
| End Function | |||||
| Function BuildSpec() | |||||
| Dim sch, inp, req, k, nm, ty, ex, exs, sep | |||||
| sch = "" : inp = "" : req = "" : exs = "" | |||||
| For k = 0 To idx | |||||
| nm = LCase(Left(cols(k), 1)) & Mid(cols(k), 2) | |||||
| ty = SpecType(kinds(k), isPk(k)) | |||||
| If Len(sch) > 0 Then sch = sch & "," & vbCrLf | |||||
| sch = sch & " """ & nm & """: " & ty | |||||
| If Not isPk(k) And Not IsStampCol(cols(k), kinds(k)) Then | |||||
| If Len(inp) > 0 Then inp = inp & "," & vbCrLf | |||||
| inp = inp & " """ & cols(k) & """: " & ty | |||||
| If needs(k) Then | |||||
| If Len(req) > 0 Then req = req & ", " | |||||
| req = req & """" & cols(k) & """" | |||||
| End If | |||||
| If Len(exs) > 0 Then exs = exs & ", " | |||||
| exs = exs & """" & cols(k) & """: " & SampleValue(kinds(k)) | |||||
| End If | |||||
| Next | |||||
| Dim reqLine | |||||
| reqLine = "" | |||||
| If Len(req) > 0 Then reqLine = " ""required"": [" & req & "]," & vbCrLf | |||||
| Dim T, R | |||||
| T = tableName : R = routeName | |||||
| Dim s | |||||
| s = "{" & vbCrLf | |||||
| s = s & " ""openapi"": ""3.0.3""," & vbCrLf | |||||
| s = s & " ""info"": { ""title"": """ & T & " API"", ""version"": ""1.0.0"", ""description"": ""Generated by GenerateApi.vbs from the " & T & " table. Stateless: no auth or CSRF. Request fields use the column names (camelCase also accepted); responses use camelCase."" }," & vbCrLf | |||||
| s = s & " ""servers"": [{ ""url"": ""/"" }]," & vbCrLf | |||||
| s = s & " ""tags"": [{ ""name"": """ & T & """ }]," & vbCrLf | |||||
| s = s & " ""paths"": {" & vbCrLf | |||||
| s = s & " ""/api/" & R & """: {" & vbCrLf | |||||
| s = s & " ""get"": { ""tags"": [""" & T & """], ""summary"": ""List (search + paging)""," & vbCrLf | |||||
| s = s & " ""parameters"": [" & vbCrLf | |||||
| s = s & " { ""name"": ""q"", ""in"": ""query"", ""schema"": { ""type"": ""string"" }, ""description"": ""Case-insensitive match on the text columns"" }," & vbCrLf | |||||
| s = s & " { ""name"": ""page"", ""in"": ""query"", ""schema"": { ""type"": ""integer"", ""minimum"": 1, ""default"": 1 } }," & vbCrLf | |||||
| s = s & " { ""name"": ""per_page"", ""in"": ""query"", ""schema"": { ""type"": ""integer"", ""minimum"": 1, ""maximum"": 100, ""default"": 10 } }" & vbCrLf | |||||
| s = s & " ]," & vbCrLf | |||||
| s = s & " ""responses"": { ""200"": { ""description"": ""A page of records"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/List"" } } } } } }," & vbCrLf | |||||
| s = s & " ""post"": { ""tags"": [""" & T & """], ""summary"": ""Create""," & vbCrLf | |||||
| s = s & " ""requestBody"": { ""required"": true, ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Input"" }, ""example"": {" & exs & "} } } }," & vbCrLf | |||||
| s = s & " ""responses"": { ""201"": { ""description"": ""Created (Location header has the new URL)"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Envelope"" } } } }, ""400"": { ""$ref"": ""#/components/responses/Error"" }, ""422"": { ""$ref"": ""#/components/responses/Error"" } } }" & vbCrLf | |||||
| s = s & " }," & vbCrLf | |||||
| s = s & " ""/api/" & R & "/{id}"": {" & vbCrLf | |||||
| s = s & " ""parameters"": [{ ""name"": ""id"", ""in"": ""path"", ""required"": true, ""schema"": { ""type"": ""integer"" } }]," & vbCrLf | |||||
| s = s & " ""get"": { ""tags"": [""" & T & """], ""summary"": ""Get one""," & vbCrLf | |||||
| s = s & " ""responses"": { ""200"": { ""description"": ""The record"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Envelope"" } } } }, ""404"": { ""$ref"": ""#/components/responses/Error"" } } }," & vbCrLf | |||||
| s = s & " ""put"": { ""tags"": [""" & T & """], ""summary"": ""Replace (required fields enforced)""," & vbCrLf | |||||
| s = s & " ""requestBody"": { ""required"": true, ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Input"" }, ""example"": {" & exs & "} } } }," & vbCrLf | |||||
| s = s & " ""responses"": { ""200"": { ""description"": ""Updated"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Envelope"" } } } }, ""400"": { ""$ref"": ""#/components/responses/Error"" }, ""404"": { ""$ref"": ""#/components/responses/Error"" }, ""422"": { ""$ref"": ""#/components/responses/Error"" } } }," & vbCrLf | |||||
| s = s & " ""patch"": { ""tags"": [""" & T & """], ""summary"": ""Partial update (only fields sent change)""," & vbCrLf | |||||
| s = s & " ""requestBody"": { ""required"": true, ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Input"" }, ""example"": {} } } }," & vbCrLf | |||||
| s = s & " ""responses"": { ""200"": { ""description"": ""Updated"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Envelope"" } } } }, ""400"": { ""$ref"": ""#/components/responses/Error"" }, ""404"": { ""$ref"": ""#/components/responses/Error"" }, ""422"": { ""$ref"": ""#/components/responses/Error"" } } }," & vbCrLf | |||||
| s = s & " ""delete"": { ""tags"": [""" & T & """], ""summary"": ""Delete""," & vbCrLf | |||||
| s = s & " ""responses"": { ""200"": { ""description"": ""Deleted"", ""content"": { ""application/json"": { ""schema"": { ""type"": ""object"", ""properties"": { ""deleted"": { ""type"": ""boolean"" }, ""id"": { ""type"": ""integer"" } } } } } }, ""404"": { ""$ref"": ""#/components/responses/Error"" } } }" & vbCrLf | |||||
| s = s & " }" & vbCrLf | |||||
| s = s & " }," & vbCrLf | |||||
| s = s & " ""components"": {" & vbCrLf | |||||
| s = s & " ""schemas"": {" & vbCrLf | |||||
| s = s & " ""Record"": { ""type"": ""object"", ""properties"": {" & vbCrLf & sch & vbCrLf & " } }," & vbCrLf | |||||
| s = s & " ""Input"": { ""type"": ""object""," & vbCrLf & reqLine & " ""properties"": {" & vbCrLf & inp & vbCrLf & " } }," & vbCrLf | |||||
| s = s & " ""Envelope"": { ""type"": ""object"", ""properties"": { ""data"": { ""$ref"": ""#/components/schemas/Record"" } } }," & vbCrLf | |||||
| s = s & " ""List"": { ""type"": ""object"", ""properties"": { ""data"": { ""type"": ""array"", ""items"": { ""$ref"": ""#/components/schemas/Record"" } }, ""meta"": { ""type"": ""object"", ""properties"": { ""page"": { ""type"": ""integer"" }, ""per_page"": { ""type"": ""integer"" }, ""page_count"": { ""type"": ""integer"" }, ""record_count"": { ""type"": ""integer"" } } } } }," & vbCrLf | |||||
| s = s & " ""Error"": { ""type"": ""object"", ""properties"": { ""error"": { ""type"": ""object"", ""properties"": { ""message"": { ""type"": ""string"" }, ""details"": { ""type"": ""array"", ""items"": { ""type"": ""string"" } } } } } }" & vbCrLf | |||||
| s = s & " }," & vbCrLf | |||||
| s = s & " ""responses"": { ""Error"": { ""description"": ""Error"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Error"" } } } } }" & vbCrLf | |||||
| s = s & " }" & vbCrLf | |||||
| s = s & "}" & vbCrLf | |||||
| BuildSpec = s | |||||
| End Function | |||||
| Function BuildHttp() | |||||
| Dim k, ex, h | |||||
| ex = "" | |||||
| For k = 0 To idx | |||||
| If Not isPk(k) And Not IsStampCol(cols(k), kinds(k)) Then | |||||
| If Len(ex) > 0 Then ex = ex & ", " | |||||
| ex = ex & """" & cols(k) & """: " & SampleValue(kinds(k)) | |||||
| End If | |||||
| Next | |||||
| h = "### " & tableName & " JSON API. Use with the VS Code ""REST Client"" extension (or any .http runner)." & vbLf | |||||
| h = h & "@base = http://localhost:8801" & vbLf & vbLf | |||||
| h = h & "### List (q = text search, page, per_page max 100)" & vbLf & "GET {{base}}/api/" & routeName & "?page=1&per_page=5" & vbLf & vbLf | |||||
| h = h & "### Show" & vbLf & "GET {{base}}/api/" & routeName & "/1" & vbLf & vbLf | |||||
| h = h & "### Create -> 201 + Location header" & vbLf & "POST {{base}}/api/" & routeName & vbLf & "Content-Type: application/json" & vbLf & vbLf & "{ " & ex & " }" & vbLf & vbLf | |||||
| h = h & "### Replace (required fields enforced)" & vbLf & "PUT {{base}}/api/" & routeName & "/1" & vbLf & "Content-Type: application/json" & vbLf & vbLf & "{ " & ex & " }" & vbLf & vbLf | |||||
| h = h & "### Partial update (only the fields sent change)" & vbLf & "PATCH {{base}}/api/" & routeName & "/1" & vbLf & "Content-Type: application/json" & vbLf & vbLf & "{ }" & vbLf & vbLf | |||||
| h = h & "### Delete" & vbLf & "DELETE {{base}}/api/" & routeName & "/1" & vbLf | |||||
| BuildHttp = h | |||||
| End Function | |||||
| Function SpecType(kind, pk) | |||||
| If pk Or kind = "int" Then | |||||
| SpecType = "{ ""type"": ""integer"" }" | |||||
| ElseIf kind = "real" Then | |||||
| SpecType = "{ ""type"": ""number"" }" | |||||
| ElseIf kind = "bool" Then | |||||
| SpecType = "{ ""type"": ""boolean"" }" | |||||
| ElseIf kind = "date" Then | |||||
| SpecType = "{ ""type"": ""string"", ""format"": ""date-time"", ""nullable"": true }" | |||||
| Else | |||||
| SpecType = "{ ""type"": ""string"" }" | |||||
| End If | |||||
| End Function | |||||
| ' SQLite DEFAULT text -> VBScript literal ("" when it is not a plain number or quoted string) | |||||
| Function DefaultLiteral(d) | |||||
| Dim s | |||||
| DefaultLiteral = "" | |||||
| If IsNull(d) Then Exit Function | |||||
| s = Trim("" & d) | |||||
| If Len(s) = 0 Then Exit Function | |||||
| If IsNumeric(s) Then | |||||
| DefaultLiteral = s | |||||
| ElseIf Len(s) >= 2 And Left(s, 1) = "'" And Right(s, 1) = "'" Then | |||||
| s = Mid(s, 2, Len(s) - 2) | |||||
| DefaultLiteral = """" & Replace(Replace(s, "''", "'"), """", """""") & """" | |||||
| End If | |||||
| End Function | |||||
| Function SampleValue(kind) | |||||
| Select Case kind | |||||
| Case "int": SampleValue = "1" | |||||
| Case "real": SampleValue = "9.99" | |||||
| Case "bool": SampleValue = "true" | |||||
| Case "date": SampleValue = """2026-01-01 00:00:00""" | |||||
| Case Else: SampleValue = """text""" | |||||
| End Select | |||||
| End Function | |||||
| '============================================================== | |||||
| ' File helpers | |||||
| '============================================================== | |||||
| Function ReadTemplate(name) | |||||
| Dim ts | |||||
| Set ts = fso.OpenTextFile(Server.MapPath("/scripts/templates/" & name), 1) | |||||
| ReadTemplate = ts.ReadAll | |||||
| ts.Close | |||||
| End Function | |||||
| Function ReadFile(path) | |||||
| Dim ts | |||||
| Set ts = fso.OpenTextFile(Server.MapPath(path), 1) | |||||
| ReadFile = ts.ReadAll | |||||
| ts.Close | |||||
| End Function | |||||
| Sub WriteFile(path, text) | |||||
| Dim tf | |||||
| Set tf = fso.CreateTextFile(path, True) | |||||
| tf.Write text | |||||
| tf.Close | |||||
| End Sub | |||||
| Function EolOf(text) | |||||
| If InStr(text, vbCrLf) > 0 Then | |||||
| EolOf = vbCrLf | |||||
| Else | |||||
| EolOf = vbLf | |||||
| End If | |||||
| End Function | |||||
| Function WithEol(text, eol) | |||||
| WithEol = Replace(Replace(text, vbCrLf, vbLf), vbLf, eol) | |||||
| End Function | |||||
| ' Appends a line to the file unless "marker" is already in it | |||||
| Sub AppendIfMissing(path, marker, line) | |||||
| Dim s, eol | |||||
| s = ReadFile(path) | |||||
| If InStr(1, s, marker, vbTextCompare) > 0 Then Exit Sub | |||||
| eol = EolOf(s) | |||||
| If Right(s, 1) <> vbLf Then s = s & eol | |||||
| WriteFile Server.MapPath(path), s & line & eol | |||||
| End Sub | |||||
| ' Inserts newText on a new line after the first line containing anchor (unless marker is already present) | |||||
| Sub InsertAfterLine(path, anchor, marker, newText) | |||||
| Dim s, eol, pos, eolPos | |||||
| s = ReadFile(path) | |||||
| If InStr(1, s, marker, vbTextCompare) > 0 Then Exit Sub | |||||
| eol = EolOf(s) | |||||
| pos = InStr(1, s, anchor, vbTextCompare) | |||||
| If pos = 0 Then | |||||
| WScript.Echo "Warning: anchor '" & anchor & "' not found in " & path & "; add the line yourself: " & newText | |||||
| Exit Sub | |||||
| End If | |||||
| eolPos = InStr(pos, s, eol) | |||||
| s = Left(s, eolPos - 1) & eol & newText & Mid(s, eolPos) | |||||
| WriteFile Server.MapPath(path), s | |||||
| End Sub | |||||
| ' Inserts newText before the line containing anchor (unless marker is already present) | |||||
| Sub InsertBeforeLine(path, anchor, marker, newText) | |||||
| Dim s, eol, pos, lineStart | |||||
| s = ReadFile(path) | |||||
| If InStr(1, s, marker, vbTextCompare) > 0 Then Exit Sub | |||||
| eol = EolOf(s) | |||||
| pos = InStr(1, s, anchor, vbTextCompare) | |||||
| If pos = 0 Then | |||||
| WScript.Echo "Warning: anchor '" & anchor & "' not found in " & path & "; add the routes yourself:" & vbCrLf & newText | |||||
| Exit Sub | |||||
| End If | |||||
| lineStart = InStrRev(s, eol, pos) | |||||
| If lineStart = 0 Then | |||||
| lineStart = 1 | |||||
| Else | |||||
| lineStart = lineStart + Len(eol) | |||||
| End If | |||||
| s = Left(s, lineStart - 1) & WithEol(newText, eol) & Mid(s, lineStart) | |||||
| WriteFile Server.MapPath(path), s | |||||
| End Sub | |||||
| '============================================================== | |||||
| ' Misc helpers | |||||
| '============================================================== | |||||
| ' SQLite declared type -> string | int | real | bool | date | |||||
| Function ApiKind(declType) | |||||
| Dim t | |||||
| t = UCase("" & declType) | |||||
| If InStr(t, "BOOL") > 0 Then | |||||
| ApiKind = "bool" | |||||
| ElseIf InStr(t, "DATE") > 0 Or InStr(t, "TIME") > 0 Then | |||||
| ApiKind = "date" | |||||
| ElseIf InStr(t, "CHAR") > 0 Or InStr(t, "CLOB") > 0 Or InStr(t, "TEXT") > 0 Then | |||||
| ApiKind = "string" | |||||
| ElseIf InStr(t, "INT") > 0 Then | |||||
| ApiKind = "int" | |||||
| ElseIf InStr(t, "REAL") > 0 Or InStr(t, "FLOA") > 0 Or InStr(t, "DOUB") > 0 Or InStr(t, "NUM") > 0 Or InStr(t, "DEC") > 0 Then | |||||
| ApiKind = "real" | |||||
| Else | |||||
| ApiKind = "string" | |||||
| End If | |||||
| End Function | |||||
| ' CreatedAt / UpdatedAt text or date columns are filled in by the server, not accepted from clients | |||||
| Function IsStampCol(name, kind) | |||||
| IsStampCol = False | |||||
| If kind = "string" Or kind = "date" Then | |||||
| If LCase(name) = "createdat" Or LCase(name) = "updatedat" Then IsStampCol = True | |||||
| End If | |||||
| End Function | |||||
| Function Pick(cond, a, b) | |||||
| If cond Then | |||||
| Pick = a | |||||
| Else | |||||
| Pick = b | |||||
| End If | |||||
| End Function | |||||
| Function GetAppSetting(key, configFilePath) | |||||
| Dim xml, nodes, node, j | |||||
| If Not fso.FileExists(configFilePath) Then | |||||
| GetAppSetting = "nothing" | |||||
| Exit Function | |||||
| End If | |||||
| Set xml = CreateObject("Microsoft.XMLDOM") | |||||
| xml.Async = False | |||||
| xml.Load(configFilePath) | |||||
| Set nodes = xml.selectNodes("//appSettings/add") | |||||
| For j = 0 To nodes.Length - 1 | |||||
| Set node = nodes.Item(j) | |||||
| If node.getAttribute("key") = key Then | |||||
| GetAppSetting = node.getAttribute("value") | |||||
| Exit Function | |||||
| End If | |||||
| Next | |||||
| GetAppSetting = "nothing" | |||||
| End Function | |||||
| Function StrEqualCI(a, b) | |||||
| StrEqualCI = (LCase(CStr(a)) = LCase(CStr(b))) | |||||
| End Function | |||||
| Function IsValidIdentifier(name) | |||||
| Dim n, ch | |||||
| IsValidIdentifier = False | |||||
| If Len(name) = 0 Then Exit Function | |||||
| For n = 1 To Len(name) | |||||
| ch = Mid(name, n, 1) | |||||
| If Not ((ch >= "a" And ch <= "z") Or (ch >= "A" And ch <= "Z") Or (ch >= "0" And ch <= "9") Or ch = "_") Then Exit Function | |||||
| Next | |||||
| IsValidIdentifier = True | |||||
| End Function | |||||
| @@ -0,0 +1,343 @@ | |||||
| '============================================================== | |||||
| ' GenerateRepo.vbs (AxonASP CLI + G3DB edition) | |||||
| ' | |||||
| ' Usage (runs under the AxonASP CLI in the container): | |||||
| ' scripts\gen.cmd repo /table:Products /pk:Id | |||||
| ' | |||||
| ' Reads the connection string from public\web.config (<appSettings> ConnectionString = "<driver>:<dsn>"), | |||||
| ' discovers the table schema, and generates into app/models/: | |||||
| ' POBO_<Table>.asp (class with typed Property Let/Get) | |||||
| ' <Table>Repository.asp (parameterized CRUD + filter + paging + search, via DAL()) | |||||
| ' | |||||
| ' 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, outDir | |||||
| Set fso = CreateObject("Scripting.FileSystemObject") | |||||
| Set args = WScript.Arguments | |||||
| csKey = "ConnectionString" | |||||
| configPath = Server.MapPath("/public/web.config") | |||||
| outDir = Server.MapPath("/app/models") | |||||
| 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) | |||||
| Case "cs": csKey = parts(1) | |||||
| Case "config": configPath = parts(1) | |||||
| End Select | |||||
| End If | |||||
| Next | |||||
| If Len(tableName) = 0 Or Len(primaryKey) = 0 Then | |||||
| WScript.Echo "Usage: scripts\gen.cmd repo /table:<TableName> /pk:<PrimaryKey>" | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| If Not IsValidIdentifier(tableName) Then | |||||
| WScript.Echo "Error: Invalid table name format. Only letters, numbers, and underscores are allowed." | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| 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, 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 | |||||
| p = InStr(connStr, ":") | |||||
| If p < 2 Then | |||||
| WScript.Echo "Error: ConnectionString must look like '<driver>:<dsn>'. Got: " & connStr | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| 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 | |||||
| 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 | |||||
| '---------------- 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 | |||||
| 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 | |||||
| If Not InArrayInsensitive(cols, primaryKey) Then | |||||
| WScript.Echo "Primary key '" & primaryKey & "' not found in table [" & tableName & "]." | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| '---------------- Generate files from templates ---------------- | |||||
| If Not fso.FolderExists(outDir) Then fso.CreateFolder outDir | |||||
| Dim poboPath, repoPath | |||||
| poboPath = outDir & "/POBO_" & tableName & ".asp" | |||||
| repoPath = outDir & "/" & tableName & "Repository.asp" | |||||
| WriteFile poboPath, BuildPOBO(cols, kinds, tableName, primaryKey) | |||||
| WScript.Echo "POBO class written to: " & poboPath | |||||
| WriteFile repoPath, BuildRepository(cols, tableName, primaryKey) | |||||
| WScript.Echo "Repository written to: " & repoPath | |||||
| WScript.Echo "" | |||||
| WScript.Echo "Next steps:" | |||||
| WScript.Echo "1. Include both files from app/models/autoload_models.asp:" | |||||
| WScript.Echo " <!--#include file=""POBO_" & tableName & ".asp""-->" | |||||
| WScript.Echo " <!--#include file=""" & tableName & "Repository.asp""-->" | |||||
| Set fso = Nothing | |||||
| '============================================================== | |||||
| ' Generators | |||||
| '============================================================== | |||||
| Function ReadTemplate(name) | |||||
| Dim ts | |||||
| Set ts = fso.OpenTextFile(Server.MapPath("/scripts/templates/" & name), 1) | |||||
| ReadTemplate = 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 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) | |||||
| 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 | |||||
| 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 | |||||
| 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 | |||||
| Function BuildRepository(colsArr, tName, pk) | |||||
| Dim selectList, colList, mapLines, insCols, insPh, insParams, updSet, updParams, k, c | |||||
| selectList = "" : colList = "" : mapLines = "" : insCols = "" : insPh = "" : insParams = "" : updSet = "" : updParams = "" | |||||
| For k = 0 To UBound(colsArr) | |||||
| c = colsArr(k) | |||||
| If k > 0 Then | |||||
| selectList = selectList & ", " | |||||
| colList = colList & "|" | |||||
| End If | |||||
| 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 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 | |||||
| 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 InArrayInsensitive(a, val) | |||||
| Dim z | |||||
| InArrayInsensitive = False | |||||
| For z = 0 To UBound(a) | |||||
| If StrEqualCI(a(z), val) Then | |||||
| InArrayInsensitive = True | |||||
| Exit Function | |||||
| End If | |||||
| Next | |||||
| End Function | |||||
| Function StrEqualCI(a, b) | |||||
| StrEqualCI = (LCase(CStr(a)) = LCase(CStr(b))) | |||||
| End Function | |||||
| ' Validate identifier (table name, column name, etc.) | |||||
| Function IsValidIdentifier(name) | |||||
| Dim n, ch | |||||
| If IsEmpty(name) Then | |||||
| IsValidIdentifier = False | |||||
| Exit Function | |||||
| End If | |||||
| 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 | |||||
| @@ -0,0 +1,33 @@ | |||||
| '======================================================================================================================= | |||||
| ' WScript compatibility shim for AxonASP CLI (axonasp-cli -m vbscript) | |||||
| '======================================================================================================================= | |||||
| ' AxonASP has no WScript host object. This defines the parts the generator scripts use: | |||||
| ' WScript.Arguments (Count, Item) - read from environment variables ARG1..ARG9 (set by scripts\gen.cmd) | |||||
| ' WScript.ScriptFullName - a path inside scripts/ (only its folder is used) | |||||
| ' WScript.Echo / WScript.Quit - Quit stops the script (exit code is not propagated by the CLI) | |||||
| ' Loaded by each generator with: ExecuteGlobal <contents of _cli.vbs> | |||||
| Class WScript_Shim | |||||
| Public Arguments | |||||
| Public ScriptFullName | |||||
| Private Sub Class_Initialize() | |||||
| Dim sh, i, v | |||||
| Set sh = CreateObject("WScript.Shell") | |||||
| Set Arguments = CreateObject("Scripting.Dictionary") | |||||
| For i = 1 To 9 | |||||
| v = sh.ExpandEnvironmentStrings("%ARG" & i & "%") | |||||
| If v = "%ARG" & i & "%" Then Exit For | |||||
| Arguments.Add Arguments.Count, v | |||||
| Next | |||||
| ScriptFullName = Server.MapPath("/scripts/generator.vbs") | |||||
| End Sub | |||||
| Public Sub Echo(s) | |||||
| Response.Write s & vbCrLf | |||||
| End Sub | |||||
| Public Sub Quit(code) | |||||
| Response.End | |||||
| End Sub | |||||
| End Class | |||||
| Dim WScript : Set WScript = New WScript_Shim | |||||
| @@ -0,0 +1,43 @@ | |||||
| @echo off | |||||
| rem Runs a code generator inside the running "axonasp" container with the AxonASP CLI. | |||||
| rem | |||||
| rem scripts\gen.cmd migration <migration_name> | |||||
| rem scripts\gen.cmd controller <Name> Index "Show(id)" NewForm Create "Edit(id)" "Update(id)" "Delete(id)" | |||||
| rem scripts\gen.cmd repo /table:<Table> /pk:<PrimaryKey> | |||||
| rem scripts\gen.cmd api /table:<Table> /pk:<PrimaryKey> (repo + JSON API controller, routes, OpenAPI spec) | |||||
| rem | |||||
| rem Controller actions are separate arguments (quote the ones with parentheses). | |||||
| setlocal | |||||
| set "GEN=%~1" | |||||
| set "SCRIPT=" | |||||
| if "%GEN%"=="migration" set "SCRIPT=generateMigration.vbs" | |||||
| if "%GEN%"=="controller" set "SCRIPT=generateController.vbs" | |||||
| if "%GEN%"=="repo" set "SCRIPT=GenerateRepo.vbs" | |||||
| if "%GEN%"=="api" set "SCRIPT=GenerateRepo.vbs" | |||||
| if not defined SCRIPT goto usage | |||||
| set "A1=%~2" | |||||
| set "A2=%~3" | |||||
| if not "%GEN%"=="controller" goto run | |||||
| set "A2=" | |||||
| shift | |||||
| shift | |||||
| :collect | |||||
| set "CUR=%~1" | |||||
| if not defined CUR goto run | |||||
| if defined A2 goto join | |||||
| set "A2=%CUR%" | |||||
| goto next | |||||
| :join | |||||
| set "A2=%A2%;%CUR%" | |||||
| :next | |||||
| shift | |||||
| goto collect | |||||
| :run | |||||
| docker exec -e SERVER_WEB_ROOT=/opt/axonasp/site -e "ARG1=%A1%" -e "ARG2=%A2%" axonasp ./axonasp-cli -m vbscript -r /opt/axonasp/site/scripts/%SCRIPT% | |||||
| if not "%GEN%"=="api" exit /b %errorlevel% | |||||
| rem api: the repo/POBO were generated above, now the controller, routes and spec | |||||
| docker exec -e SERVER_WEB_ROOT=/opt/axonasp/site -e "ARG1=%A1%" -e "ARG2=%A2%" axonasp ./axonasp-cli -m vbscript -r /opt/axonasp/site/scripts/GenerateApi.vbs | |||||
| exit /b %errorlevel% | |||||
| :usage | |||||
| echo Usage: scripts\gen.cmd (migration^|controller^|repo^|api) args... | |||||
| exit /b 1 | |||||
| @@ -0,0 +1,352 @@ | |||||
| '============================================================== | |||||
| ' generateController.vbs | |||||
| ' | |||||
| ' Usage (runs under the AxonASP CLI in the container): | |||||
| ' scripts\gen.cmd controller ControllerName "Sub1;Sub2(param1,param2);Sub3" | |||||
| ' | |||||
| ' Generates a controller class file with specified action methods | |||||
| '============================================================== | |||||
| 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 args, controllerName, subsList, subs, fso, fileName, outputPath | |||||
| ' Parse arguments | |||||
| Set args = WScript.Arguments | |||||
| If args.Count < 2 Then | |||||
| WScript.Echo "Usage: scripts\gen.cmd controller ControllerName ""Sub1;Sub2(param1,param2);...""" | |||||
| WScript.Echo "" | |||||
| WScript.Echo "Example: scripts\gen.cmd controller User ""Index;Show(id);Create;Update(id)""" | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| controllerName = args(0) | |||||
| subsList = args(1) | |||||
| ' Validate controller name format (alphanumeric and underscore only) | |||||
| If Not IsValidIdentifier(controllerName) Then | |||||
| WScript.Echo "Error: Invalid controller name format. Only letters, numbers, and underscores are allowed." | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| ' Parse action methods | |||||
| ' (stray double quotes are dropped: cmd/bash quoting can pass them through literally) | |||||
| subs = Split(Replace(subsList, """", ""), ";") | |||||
| ' Determine output path | |||||
| Set fso = CreateObject("Scripting.FileSystemObject") | |||||
| outputPath = Server.MapPath("/app/controllers") | |||||
| fileName = fso.BuildPath(outputPath, controllerName & "Controller.asp") | |||||
| ' Check if file already exists | |||||
| If fso.FileExists(fileName) Then | |||||
| WScript.Echo "Error: Controller file already exists: " & fileName | |||||
| WScript.Echo "Delete the existing file or choose a different controller name." | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| ' Generate the controller file | |||||
| Dim content | |||||
| content = BuildController(controllerName, subs) | |||||
| ' Write to file | |||||
| Dim file | |||||
| Set file = fso.CreateTextFile(fileName, True, False) | |||||
| file.Write content | |||||
| file.Close | |||||
| Set file = Nothing | |||||
| WScript.Echo "Controller file created: " & fileName | |||||
| ' ---- wire it up: include, whitelist, routes | |||||
| AppendIfMissing "/app/controllers/autoload_controllers.asp", controllerName & "Controller.asp", "<!--#include file=""" & controllerName & "Controller.asp"" -->" | |||||
| InsertAfterLine "/core/lib.ControllerRegistry.asp", "RegisterController ""errorcontroller""", """" & LCase(controllerName) & "controller""", _ | |||||
| " RegisterController """ & LCase(controllerName) & "controller""" | |||||
| Dim routeText | |||||
| routeText = BuildRoutes(controllerName, subs) | |||||
| InsertBeforeLine "/public/Default.asp", "' Dispatch the request", """" & controllerName & "Controller""", routeText | |||||
| WScript.Echo "Wired: autoload_controllers.asp, ControllerRegistry, and these routes in public/Default.asp:" | |||||
| WScript.Echo routeText | |||||
| WScript.Echo "Next: fill in the actions, add views under app/views/" & controllerName & "/, restart the container (docker restart axonasp)." | |||||
| '============================================================== | |||||
| ' Build controller content using array-based string building | |||||
| '============================================================== | |||||
| Function BuildController(ctrlName, actionsArray) | |||||
| Dim parts() | |||||
| ReDim parts(500) ' Pre-allocate for performance | |||||
| Dim partIdx : partIdx = 0 | |||||
| Dim className : className = ctrlName & "Controller_Class" | |||||
| Dim funcName : funcName = ctrlName & "Controller" | |||||
| ' Header comments | |||||
| parts(partIdx) = "<%" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = "' Auto-generated Controller: " & ctrlName & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = "' Generated on " & Now() & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = "' Generator: generateController.vbs v1.0" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = "'" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = "' The include, whitelist entry and routes were added automatically (see public/Default.asp)." & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = vbCrLf & vbCrLf : partIdx = partIdx + 1 | |||||
| ' Class definition | |||||
| parts(partIdx) = "Class " & className & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " Private m_useLayout" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " Private m_title" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = vbCrLf : partIdx = partIdx + 1 | |||||
| ' Class_Initialize | |||||
| parts(partIdx) = " Private Sub Class_Initialize()" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " m_useLayout = True" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " m_title = """ & ctrlName & """" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " End Sub" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = vbCrLf : partIdx = partIdx + 1 | |||||
| ' useLayout property | |||||
| parts(partIdx) = " Public Property Get useLayout" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " useLayout = m_useLayout" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " End Property" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " Public Property Let useLayout(v)" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " m_useLayout = v" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " End Property" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = vbCrLf : partIdx = partIdx + 1 | |||||
| ' Title property | |||||
| parts(partIdx) = " Public Property Get Title" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " Title = m_title" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " End Property" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " Public Property Let Title(v)" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " m_title = v" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " End Property" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = vbCrLf : partIdx = partIdx + 1 | |||||
| ' Generate action methods | |||||
| Dim i, actionDef, namePart, paramsPart, paramsArr | |||||
| For i = 0 To UBound(actionsArray) | |||||
| actionDef = Trim(actionsArray(i)) | |||||
| ' Skip empty entries | |||||
| If Len(actionDef) > 0 Then | |||||
| ' Parse action name and parameters | |||||
| If InStr(actionDef, "(") > 0 Then | |||||
| namePart = Trim(Left(actionDef, InStr(actionDef, "(") - 1)) | |||||
| paramsPart = Mid(actionDef, InStr(actionDef, "(") + 1) | |||||
| paramsPart = Left(paramsPart, Len(paramsPart) - 1) ' Strip trailing ')' | |||||
| paramsPart = Trim(paramsPart) | |||||
| ' Validate parameter names | |||||
| If Len(paramsPart) > 0 Then | |||||
| paramsArr = Split(paramsPart, ",") | |||||
| Dim j, paramName | |||||
| For j = 0 To UBound(paramsArr) | |||||
| paramName = Trim(paramsArr(j)) | |||||
| If Not IsValidIdentifier(paramName) Then | |||||
| WScript.Echo "Error: Invalid parameter name '" & paramName & "' in action '" & actionDef & "'" | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| Next | |||||
| End If | |||||
| Else | |||||
| namePart = Trim(actionDef) | |||||
| paramsPart = "" | |||||
| End If | |||||
| ' Validate action name | |||||
| If Not IsValidIdentifier(namePart) Then | |||||
| WScript.Echo "Error: Invalid action name '" & namePart & "'" | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| ' Generate method stub | |||||
| parts(partIdx) = " '---------------------------------------------------------------" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " ' Action: " & namePart & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " '---------------------------------------------------------------" & vbCrLf : partIdx = partIdx + 1 | |||||
| If paramsPart = "" Then | |||||
| parts(partIdx) = " Public Sub " & namePart & "()" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " ' TODO: Implement " & namePart & " action" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " Response.Write """ & namePart & " action called""" & vbCrLf : partIdx = partIdx + 1 | |||||
| Else | |||||
| parts(partIdx) = " Public Sub " & namePart & "(" & paramsPart & ")" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " ' TODO: Implement " & namePart & " action" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " Response.Write ""<strong>" & namePart & " called</strong><br>""" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " Response.Write ""Parameters:<br>""" & vbCrLf : partIdx = partIdx + 1 | |||||
| ' Echo each parameter | |||||
| paramsArr = Split(paramsPart, ",") | |||||
| For j = 0 To UBound(paramsArr) | |||||
| paramName = Trim(paramsArr(j)) | |||||
| parts(partIdx) = " Response.Write """ & paramName & " = "" & Server.HTMLEncode(CStr(" & paramName & ")) & ""<br>""" & vbCrLf : partIdx = partIdx + 1 | |||||
| Next | |||||
| End If | |||||
| parts(partIdx) = " End Sub" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = vbCrLf : partIdx = partIdx + 1 | |||||
| End If | |||||
| Next | |||||
| ' End class | |||||
| parts(partIdx) = "End Class" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = vbCrLf : partIdx = partIdx + 1 | |||||
| ' Singleton pattern | |||||
| parts(partIdx) = "' Singleton instance" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = "Dim " & className & "__Singleton" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = "Function " & funcName & "()" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " If IsEmpty(" & className & "__Singleton) Then" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " Set " & className & "__Singleton = New " & className & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " End If" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = " Set " & funcName & " = " & className & "__Singleton" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = "End Function" & vbCrLf : partIdx = partIdx + 1 | |||||
| parts(partIdx) = "%>" & vbCrLf : partIdx = partIdx + 1 | |||||
| ' Join array for performance | |||||
| ReDim Preserve parts(partIdx - 1) | |||||
| BuildController = Join(parts, "") | |||||
| End Function | |||||
| '============================================================== | |||||
| ' Validate identifier (controller name, action name, parameter name) | |||||
| '============================================================== | |||||
| Function IsValidIdentifier(name) | |||||
| If IsEmpty(name) Or Len(name) = 0 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 | |||||
| IsValidIdentifier = False | |||||
| Exit Function | |||||
| End If | |||||
| Next | |||||
| IsValidIdentifier = True | |||||
| End Function | |||||
| '============================================================== | |||||
| ' Routes: conventional action names map to REST-style routes, anything else is GET /<controller>/<action>[/:param] | |||||
| '============================================================== | |||||
| Function BuildRoutes(ctrlName, actionsArray) | |||||
| Dim r, base, i, def, nm, prm, verb, path, line, k, pa | |||||
| base = "/" & LCase(ctrlName) | |||||
| r = vbTab & "' " & ctrlName & " (generated by generateController.vbs)" & vbCrLf | |||||
| For i = 0 To UBound(actionsArray) | |||||
| def = Trim(actionsArray(i)) | |||||
| If Len(def) > 0 Then | |||||
| nm = def | |||||
| prm = "" | |||||
| If InStr(def, "(") > 0 Then | |||||
| nm = Trim(Left(def, InStr(def, "(") - 1)) | |||||
| prm = Trim(Replace(Mid(def, InStr(def, "(") + 1), ")", "")) | |||||
| End If | |||||
| verb = "GET" | |||||
| Select Case LCase(nm) | |||||
| Case "index": path = base | |||||
| Case "newform": path = base & "/new" | |||||
| Case "create": path = base : verb = "POST" | |||||
| Case "show": path = base & "/:id" | |||||
| Case "edit": path = base & "/:id/edit" | |||||
| Case "update": path = base & "/:id" : verb = "POST" | |||||
| Case "delete": path = base & "/:id/delete" : verb = "POST" | |||||
| Case Else | |||||
| path = base & "/" & LCase(nm) | |||||
| If Len(prm) > 0 Then | |||||
| pa = Split(prm, ",") | |||||
| For k = 0 To UBound(pa) | |||||
| path = path & "/:" & Trim(pa(k)) | |||||
| Next | |||||
| End If | |||||
| End Select | |||||
| r = r & vbTab & "router.AddRoute """ & verb & """, """ & path & """, """ & ctrlName & "Controller"", """ & nm & """" & vbCrLf | |||||
| End If | |||||
| Next | |||||
| BuildRoutes = r & vbCrLf | |||||
| End Function | |||||
| '============================================================== | |||||
| ' File helpers (wiring) | |||||
| '============================================================== | |||||
| Function ReadFile(path) | |||||
| Dim ts | |||||
| Set ts = fso.OpenTextFile(Server.MapPath(path), 1) | |||||
| ReadFile = ts.ReadAll | |||||
| ts.Close | |||||
| End Function | |||||
| Sub WriteWhole(path, text) | |||||
| Dim tf | |||||
| Set tf = fso.CreateTextFile(Server.MapPath(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 unless marker is already in the file | |||||
| 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 | |||||
| WriteWhole 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 this yourself: " & newText | |||||
| Exit Sub | |||||
| End If | |||||
| eolPos = InStr(pos, s, eol) | |||||
| WriteWhole path, Left(s, eolPos - 1) & eol & newText & Mid(s, eolPos) | |||||
| 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 | |||||
| WriteWhole path, Left(s, lineStart - 1) & WithEol(newText, eol) & Mid(s, lineStart) | |||||
| End Sub | |||||
| @@ -0,0 +1,166 @@ | |||||
| '======================================================================================================================= | |||||
| ' MIGRATION GENERATOR | |||||
| '======================================================================================================================= | |||||
| ' Generates a new migration file with timestamp-based versioning. | |||||
| ' | |||||
| ' Usage: | |||||
| ' scripts\gen.cmd migration migration_name (runs under the AxonASP CLI in the container) | |||||
| ' | |||||
| ' Example: | |||||
| ' 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: scripts\gen.cmd migration migration_name" | |||||
| WScript.Echo "" | |||||
| WScript.Echo "Example:" | |||||
| WScript.Echo " scripts\gen.cmd migration create_users_table" | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| migrationName = WScript.Arguments(0) | |||||
| ' Validate migration name (alphanumeric and underscore only) | |||||
| If Not IsValidMigrationName(migrationName) Then | |||||
| WScript.Echo "Error: Migration name must contain only letters, numbers, and underscores" | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| ' Generate timestamp (YYYYMMDDHHMMSS) | |||||
| timestamp = GetTimestamp() | |||||
| ' Create filename | |||||
| filename = timestamp & "_" & migrationName & ".asp" | |||||
| ' Ensure migrations directory exists | |||||
| Dim migrationsDir | |||||
| migrationsDir = Server.MapPath("/db/migrations") | |||||
| If Not fso.FolderExists(migrationsDir) Then | |||||
| CreateDirectoryPath migrationsDir | |||||
| End If | |||||
| filepath = migrationsDir & "/" & filename | |||||
| ' Check if file already exists | |||||
| If fso.FileExists(filepath) Then | |||||
| WScript.Echo "Error: Migration file already exists: " & filename | |||||
| WScript.Quit 1 | |||||
| End If | |||||
| ' Generate migration content | |||||
| content = GenerateMigrationContent(migrationName) | |||||
| ' Write the file | |||||
| Dim file | |||||
| Set file = fso.CreateTextFile(filepath, True) | |||||
| file.Write content | |||||
| file.Close | |||||
| 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 " scripts\migrate.cmd up" | |||||
| WScript.Quit 0 | |||||
| '======================================================================================================================= | |||||
| ' HELPER FUNCTIONS | |||||
| '======================================================================================================================= | |||||
| Function GetTimestamp() | |||||
| Dim dtNow, sYear, sMonth, sDay, sHour, sMinute, sSecond | |||||
| dtNow = Now() | |||||
| sYear = Year(dtNow) | |||||
| sMonth = Right("0" & Month(dtNow), 2) | |||||
| sDay = Right("0" & Day(dtNow), 2) | |||||
| sHour = Right("0" & Hour(dtNow), 2) | |||||
| sMinute = Right("0" & Minute(dtNow), 2) | |||||
| sSecond = Right("0" & Second(dtNow), 2) | |||||
| GetTimestamp = sYear & sMonth & sDay & sHour & sMinute & sSecond | |||||
| End Function | |||||
| Function IsValidMigrationName(name) | |||||
| Dim regex | |||||
| Set regex = New RegExp | |||||
| regex.Pattern = "^[a-zA-Z0-9_]+$" | |||||
| IsValidMigrationName = regex.Test(name) | |||||
| End Function | |||||
| Function GenerateMigrationContent(name) | |||||
| Dim template | |||||
| template = "<%"& vbCrLf | |||||
| template = template & "'======================================================================================================================="& vbCrLf | |||||
| template = template & "' MIGRATION: " & name & vbCrLf | |||||
| template = template & "'======================================================================================================================="& vbCrLf | |||||
| template = template & "' This migration was auto-generated. Add your migration logic below."& vbCrLf | |||||
| template = template & "'"& vbCrLf | |||||
| template = template & "' The migration object provides these helper methods:"& vbCrLf | |||||
| template = template & "' - migration.ExecuteSQL(sql) - Execute raw SQL"& vbCrLf | |||||
| template = template & "' - migration.CreateTable(name, columns) - Create a table"& vbCrLf | |||||
| template = template & "' - migration.DropTable(name) - Drop a table"& vbCrLf | |||||
| template = template & "' - migration.AddColumn(table, column, type) - Add a column"& vbCrLf | |||||
| template = template & "' - migration.DropColumn(table, column) - Drop a column"& vbCrLf | |||||
| template = template & "' - migration.CreateIndex(name, table, columns) - Create an index"& vbCrLf | |||||
| template = template & "' - migration.DropIndex(name, table) - Drop an index"& vbCrLf | |||||
| template = template & "'"& vbCrLf | |||||
| template = template & "' For complex operations, use migration.DB to access the database directly:"& vbCrLf | |||||
| template = template & "' migration.DB.Execute ""INSERT INTO users (name) VALUES (?)"", Array(""John"")"& vbCrLf | |||||
| template = template & "'"& vbCrLf | |||||
| template = template & ""& vbCrLf | |||||
| template = template & "'-----------------------------------------------------------------------------------------------------------------------"& vbCrLf | |||||
| template = template & "' UP - Apply the migration"& vbCrLf | |||||
| template = template & "'-----------------------------------------------------------------------------------------------------------------------"& vbCrLf | |||||
| template = template & "Sub Migration_Up(migration)"& vbCrLf | |||||
| template = template & " ' Example: Create a table"& 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 | |||||
| template = template & " "& vbCrLf | |||||
| template = template & " ' TODO: Add your migration logic here"& vbCrLf | |||||
| template = template & " "& vbCrLf | |||||
| template = template & "End Sub"& vbCrLf | |||||
| template = template & ""& vbCrLf | |||||
| template = template & "'-----------------------------------------------------------------------------------------------------------------------"& vbCrLf | |||||
| template = template & "' DOWN - Rollback the migration"& vbCrLf | |||||
| template = template & "'-----------------------------------------------------------------------------------------------------------------------"& vbCrLf | |||||
| template = template & "Sub Migration_Down(migration)"& vbCrLf | |||||
| template = template & " ' Example: Drop the table"& vbCrLf | |||||
| template = template & " ' migration.DropTable ""users"""& vbCrLf | |||||
| template = template & " "& vbCrLf | |||||
| template = template & " ' TODO: Add your rollback logic here (reverse the Up migration)"& vbCrLf | |||||
| template = template & " "& vbCrLf | |||||
| template = template & "End Sub"& vbCrLf | |||||
| template = template & "%>"& vbCrLf | |||||
| GenerateMigrationContent = template | |||||
| End Function | |||||
| Sub CreateDirectoryPath(path) | |||||
| Dim parentPath | |||||
| If Not fso.FolderExists(path) Then | |||||
| parentPath = fso.GetParentFolderName(path) | |||||
| If parentPath <> "" Then | |||||
| CreateDirectoryPath parentPath | |||||
| End If | |||||
| fso.CreateFolder path | |||||
| End If | |||||
| End Sub | |||||
| @@ -0,0 +1,27 @@ | |||||
| <% | |||||
| ' Migration runner for AxonASP CLI (the WSH runMigrations.vbs cannot run on Linux/AxonASP). | |||||
| ' | |||||
| ' docker exec -e SERVER_WEB_ROOT=/opt/axonasp/site -e MIGRATE=status axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/migrate.asp | |||||
| ' MIGRATE = up (default) | down | status | |||||
| ' | |||||
| Dim cmd : cmd = LCase(CreateObject("WScript.Shell").ExpandEnvironmentStrings("%MIGRATE%")) | |||||
| If cmd = "%migrate%" Or cmd = "" Then cmd = "up" | |||||
| %> | |||||
| <!--#include file="../core/autoload_core.asp" --> | |||||
| <% | |||||
| Dim m : Set m = Migrator() | |||||
| m.MigrationsPath = Server.MapPath("/db/migrations") ' requires SERVER_WEB_ROOT=<framework folder> | |||||
| m.EnsureSchemaMigrationsTable | |||||
| Select Case cmd | |||||
| Case "up" : m.ApplyAllPending | |||||
| Case "down" : m.RollbackLast | |||||
| Case "status" | |||||
| Dim k | |||||
| Response.Write "Applied:" & vbCrLf | |||||
| For Each k In m.GetAppliedMigrations().Keys : Response.Write " " & k & vbCrLf : Next | |||||
| Response.Write "Pending:" & vbCrLf | |||||
| For Each k In m.GetPendingMigrations().Keys : Response.Write " " & k & vbCrLf : Next | |||||
| Case Else | |||||
| Response.Write "Unknown command: " & cmd & " (use up, down, status)" & vbCrLf | |||||
| End Select | |||||
| %> | |||||
| @@ -0,0 +1,6 @@ | |||||
| @echo off | |||||
| rem Usage: scripts\migrate.cmd [up|down|status] (default: up) | |||||
| rem Runs the migrator inside the running "axonasp" container. | |||||
| set CMD=%1 | |||||
| if "%CMD%"=="" set CMD=up | |||||
| docker exec -e SERVER_WEB_ROOT=/opt/axonasp/site -e MIGRATE=%CMD% axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/migrate.asp | |||||
| @@ -0,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 | |||||
| %> | |||||
| @@ -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 | |||||
| %> | |||||
| @@ -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 | |||||
| %> | |||||
Powered by TurnKey Linux.