mirror of https://github.com/abpframework/abp.git
Browse Source
- Add end-to-end benchmark suite comparing ABP 10 (.NET 10) vs ABP 11 (.NET 11) under test/AbpNet10vsNet11PerfTest/. - Include net10 and net11 projects, k6 load test scenarios, PowerShell runners, database seed scripts, and benchmark reports. - Include openiddict.pfx certificates and Directory.Packages.props to enable complete independent reproducibility.pull/26446/head
396 changed files with 73407 additions and 0 deletions
@ -0,0 +1,7 @@ |
|||
NOTES.md |
|||
publish/ |
|||
results/ |
|||
|
|||
# raw k6 Studio recordings (contain passwords and session cookies) |
|||
*.raw.har |
|||
*.raw.js |
|||
@ -0,0 +1,5 @@ |
|||
<Project> |
|||
<PropertyGroup> |
|||
<ManagePackageVersionsCentrally>false</ManagePackageVersionsCentrally> |
|||
</PropertyGroup> |
|||
</Project> |
|||
@ -0,0 +1,204 @@ |
|||
# ABP .NET 10 vs .NET 11 Performance Benchmark |
|||
|
|||
End-to-end load test comparing an empty ABP MVC application on stable ABP 10.7.1 + .NET 10 (`net10`) against preview ABP 11.0.0-rc.1 + .NET 11 (`net11`) under identical hardware, database, data set, and workload conditions: |
|||
|
|||
| Target | Application Build | Runtime | Role | |
|||
|---|---|---|---| |
|||
| `net10` | ABP `10.7.1` (`net10.0`) | .NET `10.0.13` | Primary — Stable baseline | |
|||
| `net11` | ABP `11.0.0-rc.1` (`net11.0`) | .NET `11.0.0-rc.3` | Primary — Preview stack | |
|||
| `net10-rt11` | ABP `10.7.1` (`net10.0`) | .NET `11.0.0-rc.3` (`DOTNET_ROLL_FORWARD=LatestMajor`) | Supplementary — Isolates the .NET runtime difference from ABP package changes | |
|||
|
|||
 |
|||
|
|||
### Key Findings Summary |
|||
|
|||
| Metric / Test | `net10` (ABP 10 + .NET 10) | `net10-rt11` (ABP 10 on .NET 11) | `net11` (ABP 11 + .NET 11) | .NET 11 Advantage | |
|||
|---|---|---|---|---| |
|||
| **6 it/s p95 Latency (27-run Marathon)** | 38.3 ms | 34.5 ms | **34.7 ms** | **~9.5% faster** | |
|||
| **6 it/s Web CPU Usage** | 55.0% | 50.3% | **50.6%** | **~4.4% CPU saving** | |
|||
| **6 it/s GC Heap Size** | 355 MB | 321 MB | **311 MB** | **~44 MB less heap** | |
|||
| **7 it/s Saturation Knee (p95)** | 39.5 ms | 40.3 ms | **40.2 ms** | Rock-solid at capacity edge | |
|||
| **ABP 11 Package Overhead** | — | Baseline | **+0.2 ms** (0.5%) | **Zero package regression** | |
|||
|
|||
 |
|||
|
|||
Full benchmark methodology, tool evaluation, scenario correlation analysis, and findings are documented in [`report/README.md`](report/README.md). Exact package, runtime, and hardware versions are recorded in [`report/versions.md`](report/versions.md). |
|||
|
|||
--- |
|||
## Repository Structure |
|||
|
|||
```text |
|||
. |
|||
├── docker-compose.yml # PostgreSQL 18.6 (digest-pinned) on port 5433 |
|||
├── net10/ # ABP 10.7.1 + .NET 10 MVC project (EF Core, PostgreSQL, LeptonX Lite) |
|||
├── net11/ # ABP 11.0.0-rc.1 + .NET 11 MVC project (upgraded copy of net10) |
|||
├── k6/ |
|||
│ ├── recordings/ |
|||
│ │ └── abp-mvc.har # Sanitized k6 Studio browser recording (passwords/cookies redacted) |
|||
│ ├── studio/ |
|||
│ │ ├── abp-mvc-correlated.k6g # k6 Studio generator with 7 correlation/verification rules |
|||
│ │ └── abp-mvc-correlated.js # Correlated script exported from k6 Studio |
|||
│ ├── tools/ |
|||
│ │ ├── sanitize-har.mjs # Strips non-app requests, static bodies, and secrets from raw HAR |
|||
│ │ └── summarize.mjs # Aggregates k6, dotnet-counters, and docker stats into Markdown tables |
|||
│ └── scenario.js # Parameterized multi-VU load-test scenario (smoke, probe, fixed modes) |
|||
├── scripts/ |
|||
│ ├── env.ps1 # Shared Production measurement environment variables |
|||
│ ├── publish.ps1 # Release-publishes Web and DbMigrator for net10 and net11 |
|||
│ ├── db.ps1 # Seeds or resets the database from Bench_seed_<target> template DBs |
|||
│ ├── seed-bench-data.sql # Seeds 1,000 test accounts (bench_vu_1..1000) and global email settings |
|||
│ ├── start-app.ps1 # Starts a target with optional CPU affinity mask and background logging |
|||
│ ├── run-bench.ps1 # Automated benchmark runner (DB reset, affinity, counters, docker stats, k6) |
|||
│ └── versions.ps1 # Generates report/versions.md from published artifacts and system info |
|||
└── report/ |
|||
├── README.md # Benchmark report (methodology, tool evaluation, results, limitations) |
|||
├── versions.md # Generated environment, SDK, runtime, and package version table |
|||
├── probe.md # Capacity probe results (2 to 32 it/s) |
|||
├── results-main.md # Initial main comparison (net10 vs net11, 2, 4, 6 it/s) |
|||
├── results-main-validation.md # Full 27-run marathon re-validation (net10 vs net10-rt11 vs net11) |
|||
├── results-runtime.md # Runtime isolation at 4 it/s |
|||
├── results-runtime6.md # Runtime isolation at 6 it/s |
|||
├── results-verify-knee.md # Saturation knee validation at 7 it/s (9 runs) |
|||
└── results-verify-marathon6.md # Targeted 6 it/s marathon validation (9 runs) |
|||
``` |
|||
|
|||
--- |
|||
|
|||
## Prerequisites |
|||
|
|||
* **OS:** Windows 11 (CPU affinity and power mode inspection in scripts use Windows commands) |
|||
* **.NET SDKs & Runtimes:** |
|||
* .NET 10 SDK (`10.0.402`) and ASP.NET Core Runtime (`10.0.13`) |
|||
* .NET 11 Preview/RC SDK and ASP.NET Core Runtime (`11.0.100-rc.3` / `11.0.0-rc.3`) |
|||
* **Diagnostics:** `dotnet-counters` (`dotnet tool install --global dotnet-counters`) |
|||
* **Database:** Docker Desktop (runs `postgres:18.6` via `docker compose`) |
|||
* **Load Generator:** [Grafana k6](https://grafana.com/docs/k6/latest/set-up/install-k6/) (`v2.3.0+`) |
|||
* **Node.js:** `v20+` (for `k6/tools/summarize.mjs` and `k6/tools/sanitize-har.mjs`) |
|||
|
|||
--- |
|||
|
|||
## Setup & Preparation |
|||
|
|||
Run all commands from the repository root in PowerShell. |
|||
|
|||
### 1. Start PostgreSQL |
|||
|
|||
```powershell |
|||
docker compose up -d |
|||
``` |
|||
|
|||
### 2. Publish Both Projects (Release) |
|||
|
|||
Publishes `Bench.Web` and `Bench.DbMigrator` for both `net10` and `net11` into `publish/<target>/`: |
|||
|
|||
```powershell |
|||
./scripts/publish.ps1 |
|||
``` |
|||
|
|||
### 3. Seed Template Databases |
|||
|
|||
Runs `Bench.DbMigrator`, applies `scripts/seed-bench-data.sql` (`bench_vu_1..1000` + global email setting rows), and snapshots the result into `Bench_seed_net10` and `Bench_seed_net11`. Subsequent runs use `-Action reset` to recreate `Bench` from the template in seconds: |
|||
|
|||
```powershell |
|||
./scripts/db.ps1 -Target net10 -Action seed |
|||
./scripts/db.ps1 -Target net11 -Action seed |
|||
``` |
|||
|
|||
### 4. Generate the Versions Report |
|||
|
|||
```powershell |
|||
./scripts/versions.ps1 |
|||
``` |
|||
|
|||
--- |
|||
|
|||
## Running the Scenario Manually (Smoke / Validation) |
|||
|
|||
Set the seeded admin/test user password in the environment: |
|||
|
|||
```powershell |
|||
$env:BENCH_PASSWORD = '<seeded_admin_password>' |
|||
``` |
|||
|
|||
Reset the database and start the desired target (`net10`, `net11`, or `net10-rt11`): |
|||
|
|||
```powershell |
|||
./scripts/db.ps1 -Target net10 -Action reset |
|||
./scripts/start-app.ps1 -Target net10 |
|||
``` |
|||
|
|||
In a second terminal, run the load-test scenario with 1 VU (1 iteration) or 20 concurrent VUs: |
|||
|
|||
```powershell |
|||
# Single-user verification (1 iteration = 92 HTTP requests, 107 checks) |
|||
k6 run -e BENCH_PASSWORD=$env:BENCH_PASSWORD --vus 1 --iterations 1 k6/scenario.js |
|||
|
|||
# Multi-user concurrency verification (20 VUs, 60 iterations, no think time) |
|||
k6 run -e BENCH_PASSWORD=$env:BENCH_PASSWORD -e THINK_TIME=0 -e SESSION_ITERATIONS=2 --vus 20 --iterations 60 k6/scenario.js |
|||
``` |
|||
|
|||
To run the raw correlated script exported from k6 Studio (requires `bench.localtest.me` resolving to `127.0.0.1`, which works out of the box via public DNS): |
|||
|
|||
```powershell |
|||
k6 run -e BENCH_PASSWORD=$env:BENCH_PASSWORD --insecure-skip-tls-verify --vus 1 --iterations 1 k6/studio/abp-mvc-correlated.js |
|||
``` |
|||
|
|||
--- |
|||
|
|||
## Running the Full Benchmark Suite |
|||
|
|||
Before running measurements: |
|||
* Plug the machine into AC power and set Windows Power Mode to **Best performance**. |
|||
* Close browsers, IDEs, k6 Studio, and background apps; leave only Docker Desktop and the PowerShell terminal open. |
|||
* Ensure `$env:BENCH_PASSWORD` is set. |
|||
|
|||
### Step 1: Capacity Probe (~32 minutes) |
|||
|
|||
Steps through arrival rates (`2,4,6,8,10,12,14,16,20,24,28,32` iterations/s, 60 s per step) on `net10` and `net11` to find the saturation point: |
|||
|
|||
```powershell |
|||
./scripts/run-bench.ps1 -Mode probe -Repeats 1 -Batch probe |
|||
node k6/tools/summarize.mjs results/probe report/probe.md |
|||
``` |
|||
|
|||
Inspect `report/probe.md` and pick three load levels (`a, b, c` iterations/s) corresponding to ~25%, ~50%, and ~75% of the lower saturation threshold before dropped iterations or error spikes occur. |
|||
|
|||
### Step 2: Main Comparison — `net10` vs `net11` (~2.5 hours) |
|||
|
|||
Runs 3 load levels × 2 targets × 3 repetitions (120 s warm-up + 300 s measured window per run, alternating target order between repetitions): |
|||
|
|||
```powershell |
|||
./scripts/run-bench.ps1 -Mode fixed -Rates 2,4,6 -Targets net10,net11 -Repeats 3 -Batch main |
|||
node k6/tools/summarize.mjs results/main report/results-main.md |
|||
``` |
|||
|
|||
### Step 3: Runtime Isolation — `net10` vs `net10-rt11` vs `net11` (~1 hour 15 minutes) |
|||
|
|||
Runs an arrival rate across all three targets × 3 repetitions to separate runtime gains/regressions from ABP package changes: |
|||
|
|||
```powershell |
|||
# Medium load (4 it/s): |
|||
./scripts/run-bench.ps1 -Mode fixed -Rates 4 -Targets net10,net10-rt11,net11 -Repeats 3 -Batch runtime |
|||
node k6/tools/summarize.mjs results/runtime report/results-runtime.md |
|||
|
|||
# High load (6 it/s): |
|||
./scripts/run-bench.ps1 -Mode fixed -Rates 6 -Targets net10,net10-rt11,net11 -Repeats 3 -Batch runtime6 |
|||
node k6/tools/summarize.mjs results/runtime6 report/results-runtime6.md |
|||
|
|||
### Step 4: Verification Batches — Knee & Marathon (~1 hour 15 minutes each) |
|||
|
|||
Targeted validation runs addressing saturation threshold and sustained-load endurance: |
|||
|
|||
```powershell |
|||
# Saturation Knee (7 it/s): |
|||
./scripts/run-bench.ps1 -Mode fixed -Rates 7 -Targets net10,net10-rt11,net11 -Repeats 3 -Batch verify-knee |
|||
node k6/tools/summarize.mjs results/verify-knee report/results-verify-knee.md |
|||
|
|||
# Sustained Marathon (6 it/s): |
|||
./scripts/run-bench.ps1 -Mode fixed -Rates 6 -Targets net10,net10-rt11,net11 -Repeats 3 -Batch verify-marathon6 |
|||
node k6/tools/summarize.mjs results/verify-marathon6 report/results-verify-marathon6.md |
|||
|
|||
# Full 3-Target Re-Validation Marathon (Rates 2, 4, 6 it/s, 27 runs, ~3.5 hours): |
|||
./scripts/run-bench.ps1 -Mode fixed -Rates 2,4,6 -Targets net10,net10-rt11,net11 -Repeats 3 -Batch main-validation |
|||
node k6/tools/summarize.mjs results/main-validation report/results-main-validation.md |
|||
``` |
|||
@ -0,0 +1,9 @@ |
|||
services: |
|||
postgres: |
|||
image: postgres:18.6@sha256:3a4264520e121176619f54ff867d12774bc81e95e7b84db58d63bccdb6144b81 |
|||
container_name: bench-postgres |
|||
environment: |
|||
POSTGRES_USER: bench |
|||
POSTGRES_PASSWORD: bench |
|||
ports: |
|||
- "5433:5432" # 5432 is taken by a local PostgreSQL service |
|||
File diff suppressed because one or more lines are too long
@ -0,0 +1,368 @@ |
|||
// Load-test scenario for the empty ABP MVC app, built from the k6 Studio recording (k6/recordings/abp-mvc.har).
|
|||
// One iteration visits every page and runs its functions; each virtual user (VU) works only on its own data:
|
|||
// - VU n logs in as bench_vu_n (seeded by scripts/seed-bench-data.sql) and keeps its session across iterations,
|
|||
// logging out and in again every SESSION_ITERATIONS iterations (password hashing would dominate otherwise).
|
|||
// - users/roles/tenants it creates get unique names per run, VU and iteration, so VUs never collide.
|
|||
// - every page also loads ABP's dynamic scripts (/Abp/...Script) like the browser does; static files are skipped.
|
|||
//
|
|||
// Run: k6 run -e BENCH_PASSWORD=<seed password> --vus 1 --iterations 1 k6/scenario.js
|
|||
// Env: BASE_URL (default https://localhost:44377), BENCH_PASSWORD (required), THINK_TIME seconds between groups
|
|||
// (default 1), SESSION_ITERATIONS (default 10), MAX_VUS (default and cap: seeded accounts).
|
|||
// Load profiles (open model: iterations started per second, so every target gets exactly the same load):
|
|||
// MODE=smoke (default) VUs/iterations from the CLI.
|
|||
// MODE=fixed RATE=<it/s> WARMUP_S=120 DURATION_S=300 warm-up, then the measured scenario "measure".
|
|||
// MODE=probe PROBE_RATES=2,4,... STEP_S=60 warm-up, then one scenario "step_NNN" per rate.
|
|||
// Measured scenarios get always-passing thresholds so their (and their groups') metrics appear in --summary-export.
|
|||
import http from 'k6/http'; |
|||
import exec from 'k6/execution'; |
|||
import { check, group, sleep } from 'k6'; |
|||
|
|||
const BASE = __ENV.BASE_URL || 'https://localhost:44377'; |
|||
const PASSWORD = __ENV.BENCH_PASSWORD; |
|||
const THINK_TIME = Number(__ENV.THINK_TIME ?? 1); |
|||
const SESSION_ITERATIONS = Number(__ENV.SESSION_ITERATIONS ?? 10); |
|||
const SEEDED_USERS = 1000; |
|||
// Unique per k6 process and VU, so names never repeat across runs on the same database either.
|
|||
const RUN = Date.now().toString(36); |
|||
|
|||
if (!PASSWORD) throw new Error('BENCH_PASSWORD is required (password of the seeded admin / bench_vu_n users)'); |
|||
|
|||
const MODE = __ENV.MODE || 'smoke'; |
|||
const MAX_VUS = Math.min(Number(__ENV.MAX_VUS ?? SEEDED_USERS), SEEDED_USERS); |
|||
const GROUPS = ['01_login', '02_home', '03_users', '04_roles', '05_tenants', '06_settings', '07_profile', '08_language', '09_logout']; |
|||
// Scenarios run back to back with this gap, so they never overlap and reuse the same (already logged-in) VUs.
|
|||
const GRACE_S = 10; |
|||
|
|||
function arrival(rate, durationS, startS) { |
|||
return { |
|||
executor: 'constant-arrival-rate', rate, timeUnit: '1s', duration: `${durationS}s`, startTime: `${startS}s`, |
|||
gracefulStop: `${GRACE_S}s`, |
|||
// One iteration takes ~10 s with THINK_TIME=1; keep headroom so slow responses don't drop iterations early.
|
|||
preAllocatedVUs: Math.min(MAX_VUS, Math.ceil(rate * 12)), maxVUs: MAX_VUS, |
|||
}; |
|||
} |
|||
|
|||
function buildScenarios() { |
|||
if (MODE === 'fixed') { |
|||
const rate = Number(__ENV.RATE); |
|||
if (!(rate > 0)) throw new Error('MODE=fixed needs RATE (iterations per second)'); |
|||
const warmup = Number(__ENV.WARMUP_S ?? 120); |
|||
return { warmup: arrival(rate, warmup, 0), measure: arrival(rate, Number(__ENV.DURATION_S ?? 300), warmup + GRACE_S) }; |
|||
} |
|||
if (MODE === 'probe') { |
|||
const rates = (__ENV.PROBE_RATES || '2,4,6,8,10,12,14,16,20,24,28,32').split(',').map(Number); |
|||
const step = Number(__ENV.STEP_S ?? 60); |
|||
const scenarios = { warmup: arrival(rates[0], step, 0) }; |
|||
rates.forEach((r, i) => { scenarios[`step_${String(r).padStart(3, '0')}`] = arrival(r, step, (i + 1) * (step + GRACE_S)); }); |
|||
return scenarios; |
|||
} |
|||
if (MODE !== 'smoke') throw new Error(`unknown MODE ${MODE}`); |
|||
return undefined; |
|||
} |
|||
|
|||
function summaryThresholds(scenarioNames) { |
|||
const thresholds = {}; |
|||
for (const s of scenarioNames) { |
|||
const add = (metric, expr) => { thresholds[`${metric}{scenario:${s}}`] = [expr]; }; |
|||
add('http_req_duration', 'max>=0'); |
|||
add('http_req_failed', 'rate>=0'); |
|||
add('http_reqs', 'count>=0'); |
|||
add('iterations', 'count>=0'); |
|||
add('dropped_iterations', 'count>=0'); |
|||
add('checks', 'rate>=0'); |
|||
for (const g of GROUPS) { |
|||
thresholds[`http_req_duration{scenario:${s},group:::${g}}`] = ['max>=0']; |
|||
thresholds[`group_duration{scenario:${s},group:::${g}}`] = ['max>=0']; |
|||
} |
|||
} |
|||
return thresholds; |
|||
} |
|||
|
|||
const scenarios = buildScenarios(); |
|||
|
|||
export const options = { |
|||
insecureSkipTLSVerify: true, // ASP.NET Core development certificate
|
|||
noCookiesReset: true, // k6 clears cookies every iteration by default, which would drop the session
|
|||
summaryTrendStats: ['avg', 'med', 'p(95)', 'p(99)', 'max'], |
|||
...(scenarios && { scenarios, thresholds: summaryThresholds(Object.keys(scenarios).filter((s) => s !== 'warmup')) }), |
|||
}; |
|||
|
|||
const HTML = { accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' }; |
|||
const TOKEN_RE = /name="__RequestVerificationToken" type="hidden" value="([^"]+)"/; |
|||
|
|||
// Per-VU state (module scope lives as long as the VU).
|
|||
let loggedIn = false; |
|||
let culture = 'en'; |
|||
let formToken = ''; // latest anti-forgery token from a page or modal form
|
|||
|
|||
function remember(res) { |
|||
const m = TOKEN_RE.exec(res.body || ''); |
|||
if (m) formToken = m[1]; |
|||
return res; |
|||
} |
|||
|
|||
function stampOf(res) { |
|||
const m = /name="(?:\w+\.)?ConcurrencyStamp" value="([^"]+)"/.exec(res.body || ''); |
|||
return m ? m[1] : ''; |
|||
} |
|||
|
|||
// ABP's JS sends the XSRF-TOKEN cookie (set by ApplicationConfigurationScript) as the RequestVerificationToken header.
|
|||
function xsrf() { |
|||
const values = http.cookieJar().cookiesForURL(BASE)['XSRF-TOKEN']; |
|||
return values ? values[0] : ''; |
|||
} |
|||
|
|||
function ok(res, name, expectedStatus = 200, extra) { |
|||
const statusOk = res.status === expectedStatus; |
|||
return check(res, { |
|||
[`${name} -> ${expectedStatus}`]: () => statusOk, |
|||
// Content is only inspected on the expected status; a login/error page would not even be JSON.
|
|||
...(extra ? { [`${name} content`]: (r) => statusOk && extra(r) } : {}), |
|||
}); |
|||
} |
|||
|
|||
const jsonOr = (res, path, fallback) => (res.status === 200 ? res.json(path) : fallback); |
|||
|
|||
// Full page: the HTML plus the three dynamic ABP scripts the layout loads on every page (in parallel, like a browser).
|
|||
function page(path, name = path, { anonymous = false } = {}) { |
|||
const res = remember(http.get(`${BASE}${path}`, { headers: HTML, tags: { name: `GET ${name}` } })); |
|||
ok(res, `GET ${name}`, 200, anonymous ? undefined : (r) => !r.url.includes('/Account/Login')); |
|||
const scripts = http.batch([ |
|||
['GET', `${BASE}/Abp/ApplicationConfigurationScript`, null, { tags: { name: 'GET /Abp/ApplicationConfigurationScript' } }], |
|||
['GET', `${BASE}/Abp/ApplicationLocalizationScript?cultureName=${culture}`, null, { tags: { name: 'GET /Abp/ApplicationLocalizationScript' } }], |
|||
['GET', `${BASE}/Abp/ServiceProxyScript`, null, { tags: { name: 'GET /Abp/ServiceProxyScript' } }], |
|||
]); |
|||
scripts.forEach((r) => ok(r, r.request.url.includes('Configuration') ? 'GET /Abp/ApplicationConfigurationScript' |
|||
: r.request.url.includes('Localization') ? 'GET /Abp/ApplicationLocalizationScript' : 'GET /Abp/ServiceProxyScript')); |
|||
return res; |
|||
} |
|||
|
|||
// Requests ABP's JS makes from a page (jQuery AJAX): JSON API calls, modal HTML and modal form posts.
|
|||
function ajax(method, path, { name = path, json, form, accept } = {}) { |
|||
const headers = { |
|||
'x-requested-with': 'XMLHttpRequest', |
|||
requestverificationtoken: xsrf(), |
|||
accept: accept || (form || method === 'GET' && path.includes('Modal') ? 'text/html, */*; q=0.01' : 'application/json, text/javascript, */*; q=0.01'), |
|||
}; |
|||
let body = null; |
|||
if (json !== undefined) { |
|||
headers['content-type'] = 'application/json'; |
|||
body = JSON.stringify(json); |
|||
} else if (form) { |
|||
// Modal forms are posted as FormData (multipart), including the form's own anti-forgery field.
|
|||
const boundary = `----k6Boundary${Math.random().toString(16).slice(2)}`; |
|||
headers['content-type'] = `multipart/form-data; boundary=${boundary}`; |
|||
body = Object.entries({ ...form, __RequestVerificationToken: formToken }) |
|||
.map(([k, v]) => `--${boundary}\r\nContent-Disposition: form-data; name="${k}"\r\n\r\n${v}\r\n`) |
|||
.join('') + `--${boundary}--\r\n`; |
|||
} |
|||
return remember(http.request(method, `${BASE}${path}`, body, { headers, tags: { name: `${method} ${name}` } })); |
|||
} |
|||
|
|||
function switchLanguage(to, returnUrl) { |
|||
const res = http.get(`${BASE}/Abp/Languages/Switch?culture=${to}&uiCulture=${to}&returnUrl=${encodeURIComponent(returnUrl)}`, |
|||
{ headers: HTML, redirects: 0, tags: { name: 'GET /Abp/Languages/Switch' } }); |
|||
ok(res, 'GET /Abp/Languages/Switch', 302); |
|||
culture = to; |
|||
} |
|||
|
|||
function login(userName) { |
|||
page('/Account/Login', '/Account/Login', { anonymous: true }); |
|||
switchLanguage('en', '/Account/Login'); |
|||
page('/Account/Login', '/Account/Login', { anonymous: true }); |
|||
const res = http.post(`${BASE}/Account/Login`, { |
|||
'LoginInput.UserNameOrEmailAddress': userName, |
|||
'LoginInput.Password': PASSWORD, |
|||
Action: 'Login', |
|||
__RequestVerificationToken: formToken, |
|||
'LoginInput.RememberMe': 'false', |
|||
}, { headers: HTML, redirects: 0, tags: { name: 'POST /Account/Login' } }); |
|||
ok(res, 'POST /Account/Login', 302, (r) => r.headers.Location === '/'); |
|||
page('/', '/', { anonymous: true }); |
|||
loggedIn = true; |
|||
} |
|||
|
|||
function users(n) { |
|||
const name = `u_${n}`; |
|||
const search = (filter, label) => ajax('GET', `/api/identity/users?filter=${filter}&skipCount=0&maxResultCount=10`, |
|||
{ name: `/api/identity/users?filter=${label}` }); |
|||
|
|||
page('/Identity/Users'); |
|||
ok(search('', ''), 'GET /api/identity/users', 200, (r) => r.json('totalCount') >= SEEDED_USERS); |
|||
ok(search('bench', 'bench'), 'GET /api/identity/users?filter=bench'); |
|||
ok(ajax('GET', '/Identity/Users/CreateModal'), 'GET /Identity/Users/CreateModal'); |
|||
const userInfo = { |
|||
'UserInfo.UserName': name, 'UserInfo.Name': '', 'UserInfo.Surname': '', 'UserInfo.Password': PASSWORD, |
|||
'UserInfo.Email': `${name}@bench.local`, 'UserInfo.PhoneNumber': '', 'UserInfo.IsActive': 'true', |
|||
'UserInfo.LockoutEnabled': 'true', 'Roles[0].Name': 'admin', |
|||
}; |
|||
ok(ajax('POST', '/Identity/Users/CreateModal', { form: userInfo }), 'POST /Identity/Users/CreateModal', 204); |
|||
search('bench', 'bench'); |
|||
const found = search(name, '{name}'); |
|||
ok(found, 'GET /api/identity/users?filter={name}', 200, (r) => r.json('totalCount') === 1); |
|||
const id = jsonOr(found, 'items.0.id'); |
|||
|
|||
const edit = ajax('GET', `/Identity/Users/EditModal?id=${id}`, { name: '/Identity/Users/EditModal?id={id}' }); |
|||
ok(edit, 'GET /Identity/Users/EditModal', 200, (r) => r.body.includes(name)); |
|||
ok(ajax('POST', '/Identity/Users/EditModal', { |
|||
form: { 'UserInfo.Id': id, 'UserInfo.ConcurrencyStamp': stampOf(edit), ...userInfo, 'UserInfo.Name': 'Rec', 'UserInfo.Password': '' }, |
|||
}), 'POST /Identity/Users/EditModal', 204); |
|||
search(name, '{name}'); |
|||
|
|||
ok(ajax('GET', `/AbpPermissionManagement/PermissionManagementModal?providerName=U&providerKey=${id}&providerKeyDisplayName=${name}`, |
|||
{ name: '/AbpPermissionManagement/PermissionManagementModal?providerName=U' }), 'GET PermissionManagementModal (user)'); |
|||
ok(ajax('POST', '/AbpPermissionManagement/PermissionManagementModal', { |
|||
form: { ProviderKey: id, ProviderName: 'U', SelectAllInAllTabs: 'false', OnlyChangedPermissions: 'true', |
|||
GrantedPermissionNames: 'FeatureManagement.ManageHostFeatures', RevokedPermissionNames: '' }, |
|||
}), 'POST PermissionManagementModal (user)', 204); |
|||
|
|||
ok(ajax('DELETE', `/api/identity/users/${id}`, { name: '/api/identity/users/{id}' }), 'DELETE /api/identity/users/{id}', 204); |
|||
ok(search(name, '{name}'), 'GET /api/identity/users?filter={name} (deleted)', 200, (r) => r.json('totalCount') === 0); |
|||
} |
|||
|
|||
function roles(n) { |
|||
const name = `r_${n}`; |
|||
const list = () => ajax('GET', '/api/identity/roles?skipCount=0&maxResultCount=10'); |
|||
// The page lists 10 roles; with many VUs ours may not be among them, so look it up by name.
|
|||
const find = () => ajax('GET', `/api/identity/roles?filter=${name}&skipCount=0&maxResultCount=10`, { name: '/api/identity/roles?filter={name}' }); |
|||
|
|||
page('/Identity/Roles'); |
|||
ok(list(), 'GET /api/identity/roles'); |
|||
ok(ajax('GET', '/Identity/Roles/CreateModal'), 'GET /Identity/Roles/CreateModal'); |
|||
const role = { 'Role.Name': name, 'Role.IsDefault': 'false', 'Role.IsPublic': 'false' }; |
|||
ok(ajax('POST', '/Identity/Roles/CreateModal', { form: role }), 'POST /Identity/Roles/CreateModal', 204); |
|||
list(); |
|||
const found = find(); |
|||
const id = jsonOr(found, 'items', []).find((x) => x.name === name)?.id; |
|||
ok(found, 'GET /api/identity/roles?filter={name}', 200, () => id !== undefined); |
|||
|
|||
const edit = ajax('GET', `/Identity/Roles/EditModal?id=${id}`, { name: '/Identity/Roles/EditModal?id={id}' }); |
|||
ok(edit, 'GET /Identity/Roles/EditModal', 200, (r) => r.body.includes(name)); |
|||
ok(ajax('POST', '/Identity/Roles/EditModal', { form: { 'Role.Id': id, 'Role.ConcurrencyStamp': stampOf(edit), ...role } }), |
|||
'POST /Identity/Roles/EditModal', 204); |
|||
list(); |
|||
|
|||
ok(ajax('GET', `/AbpPermissionManagement/PermissionManagementModal?providerName=R&providerKey=${name}&providerKeyDisplayName=${name}`, |
|||
{ name: '/AbpPermissionManagement/PermissionManagementModal?providerName=R' }), 'GET PermissionManagementModal (role)'); |
|||
ok(ajax('POST', '/AbpPermissionManagement/PermissionManagementModal', { |
|||
form: { ProviderKey: name, ProviderName: 'R', SelectAllInAllTabs: 'false', OnlyChangedPermissions: 'true', |
|||
GrantedPermissionNames: 'FeatureManagement.ManageHostFeatures', RevokedPermissionNames: '' }, |
|||
}), 'POST PermissionManagementModal (role)', 204); |
|||
|
|||
ok(ajax('DELETE', `/api/identity/roles/${id}`, { name: '/api/identity/roles/{id}' }), 'DELETE /api/identity/roles/{id}', 204); |
|||
ok(find(), 'GET /api/identity/roles?filter={name} (deleted)', 200, (r) => r.json('totalCount') === 0); |
|||
} |
|||
|
|||
function tenants(n) { |
|||
const name = `t_${n}`; |
|||
const list = () => ajax('GET', '/api/multi-tenancy/tenants?filter=&sorting=name%20asc&skipCount=0&maxResultCount=10'); |
|||
const find = () => ajax('GET', `/api/multi-tenancy/tenants?filter=${name}&sorting=name%20asc&skipCount=0&maxResultCount=10`, |
|||
{ name: '/api/multi-tenancy/tenants?filter={name}' }); |
|||
|
|||
page('/TenantManagement/Tenants'); |
|||
ok(list(), 'GET /api/multi-tenancy/tenants'); |
|||
ok(ajax('GET', '/TenantManagement/Tenants/CreateModal'), 'GET /TenantManagement/Tenants/CreateModal'); |
|||
ok(ajax('POST', '/TenantManagement/Tenants/CreateModal', { |
|||
form: { 'Tenant.Name': name, 'Tenant.AdminEmailAddress': `admin@${name}.local`, 'Tenant.AdminPassword': PASSWORD }, |
|||
}), 'POST /TenantManagement/Tenants/CreateModal', 204); |
|||
list(); |
|||
const found = find(); |
|||
ok(found, 'GET /api/multi-tenancy/tenants?filter={name}', 200, (r) => r.json('totalCount') === 1); |
|||
const id = jsonOr(found, 'items.0.id'); |
|||
|
|||
const edit = ajax('GET', `/TenantManagement/Tenants/EditModal?id=${id}`, { name: '/TenantManagement/Tenants/EditModal?id={id}' }); |
|||
ok(edit, 'GET /TenantManagement/Tenants/EditModal', 200, (r) => r.body.includes(name)); |
|||
ok(ajax('POST', '/TenantManagement/Tenants/EditModal', { |
|||
form: { 'Tenant.Id': id, 'Tenant.ConcurrencyStamp': stampOf(edit), 'Tenant.Name': name }, |
|||
}), 'POST /TenantManagement/Tenants/EditModal', 204); |
|||
list(); |
|||
|
|||
ok(ajax('GET', `/FeatureManagement/FeatureManagementModal?providerName=T&providerKey=${id}&providerKeyDisplayName=${name}`, |
|||
{ name: '/FeatureManagement/FeatureManagementModal?providerName=T&providerKey={id}' }), 'GET FeatureManagementModal (tenant)'); |
|||
ok(ajax('POST', '/FeatureManagement/FeatureManagementModal', { |
|||
form: { |
|||
ProviderKey: id, ProviderName: 'T', |
|||
'FeatureGroups[0].Features[0].IsDisabled': 'False', 'FeatureGroups[0].Features[0].Type': 'ToggleStringValueType', |
|||
'FeatureGroups[0].Features[0].BoolValue': 'true', 'FeatureGroups[0].Features[0].Name': 'SettingManagement.Enable', |
|||
'FeatureGroups[0].Features[1].IsDisabled': 'False', 'FeatureGroups[0].Features[1].Type': 'ToggleStringValueType', |
|||
'FeatureGroups[0].Features[1].Name': 'SettingManagement.AllowChangingEmailSettings', |
|||
}, |
|||
}), 'POST FeatureManagementModal (tenant)', 204); |
|||
|
|||
ok(ajax('DELETE', `/api/multi-tenancy/tenants/${id}`, { name: '/api/multi-tenancy/tenants/{id}' }), 'DELETE /api/multi-tenancy/tenants/{id}', 204); |
|||
ok(find(), 'GET /api/multi-tenancy/tenants?filter={name} (deleted)', 200, (r) => r.json('totalCount') === 0); |
|||
} |
|||
|
|||
function settings() { |
|||
page('/SettingManagement'); |
|||
ok(ajax('POST', '/SettingManagement?handler=RenderView&id=Volo.Abp.EmailSetting', { accept: 'text/html, */*; q=0.01' }), |
|||
'POST /SettingManagement?handler=RenderView (email)', 200, (r) => TOKEN_RE.test(r.body)); |
|||
ok(ajax('POST', '/api/setting-management/emailing', { |
|||
json: { |
|||
defaultFromDisplayName: 'ABP application', defaultFromAddress: 'noreply@abp.io', smtpHost: '127.0.0.1', smtpPort: '25', |
|||
__Invariant: 'SmtpPort', smtpUseDefaultCredentials: 'true', smtpDomain: '', smtpUserName: '', smtpPassword: '', |
|||
__RequestVerificationToken: formToken, smtpEnableSsl: 'false', |
|||
}, |
|||
}), 'POST /api/setting-management/emailing', 204); |
|||
ok(ajax('POST', '/SettingManagement?handler=RefreshConfiguration', { json: undefined }), 'POST /SettingManagement?handler=RefreshConfiguration', 204); |
|||
ok(ajax('POST', '/SettingManagement?handler=RenderView&id=Volo.Abp.FeatureManagement', { accept: 'text/html, */*; q=0.01' }), |
|||
'POST /SettingManagement?handler=RenderView (features)'); |
|||
ok(ajax('GET', '/FeatureManagement/FeatureManagementModal?providerName=T', { name: '/FeatureManagement/FeatureManagementModal?providerName=T' }), |
|||
'GET FeatureManagementModal (host)'); |
|||
} |
|||
|
|||
function profile(userName, vu) { |
|||
const manage = page('/Account/Manage'); |
|||
ok(ajax('PUT', '/api/account/my-profile', { |
|||
json: { |
|||
ConcurrencyStamp: stampOf(manage), UserName: userName, Name: 'Bench Rec', Surname: `VU ${vu}`, |
|||
Email: `${userName}@bench.local`, PhoneNumber: '', __RequestVerificationToken: formToken, |
|||
}, |
|||
}), 'PUT /api/account/my-profile', 200, (r) => r.json('userName') === userName); |
|||
ok(ajax('GET', '/api/account/my-profile'), 'GET /api/account/my-profile'); |
|||
} |
|||
|
|||
function language() { |
|||
switchLanguage('tr', '/Account/Manage'); |
|||
page('/Account/Manage'); |
|||
switchLanguage('en', '/Account/Manage'); |
|||
page('/Account/Manage'); |
|||
} |
|||
|
|||
function logout() { |
|||
const res = http.get(`${BASE}/Account/Logout`, { headers: HTML, redirects: 0, tags: { name: 'GET /Account/Logout' } }); |
|||
ok(res, 'GET /Account/Logout', 302); |
|||
page('/Account/Login', '/Account/Login', { anonymous: true }); |
|||
loggedIn = false; |
|||
} |
|||
|
|||
export default function () { |
|||
const vu = exec.vu.idInTest; |
|||
if (vu > SEEDED_USERS) exec.test.abort(`VU ${vu} has no seeded account (bench_vu_1..${SEEDED_USERS})`); |
|||
const userName = `bench_vu_${vu}`; |
|||
const iteration = exec.vu.iterationInInstance; |
|||
const n = `${RUN}_${vu}_${iteration}`; |
|||
|
|||
if (!loggedIn) { |
|||
group('01_login', () => login(userName)); |
|||
sleep(THINK_TIME); |
|||
} |
|||
group('02_home', () => page('/', '/', {})); |
|||
sleep(THINK_TIME); |
|||
group('03_users', () => users(n)); |
|||
sleep(THINK_TIME); |
|||
group('04_roles', () => roles(n)); |
|||
sleep(THINK_TIME); |
|||
group('05_tenants', () => tenants(n)); |
|||
sleep(THINK_TIME); |
|||
group('06_settings', () => settings()); |
|||
sleep(THINK_TIME); |
|||
group('07_profile', () => profile(userName, vu)); |
|||
sleep(THINK_TIME); |
|||
group('08_language', () => language()); |
|||
sleep(THINK_TIME); |
|||
if ((iteration + 1) % SESSION_ITERATIONS === 0) { |
|||
group('09_logout', () => logout()); |
|||
sleep(THINK_TIME); |
|||
} |
|||
} |
|||
File diff suppressed because it is too large
@ -0,0 +1,188 @@ |
|||
{ |
|||
"version": "3.0", |
|||
"recordingPath": "../Recordings/abp-mvc.har", |
|||
"options": { |
|||
"loadProfile": { |
|||
"executor": "ramping-vus", |
|||
"stages": [ |
|||
{ |
|||
"target": 1, |
|||
"duration": "10s" |
|||
} |
|||
] |
|||
}, |
|||
"thinkTime": { |
|||
"sleepType": "groups", |
|||
"timing": { |
|||
"type": "fixed", |
|||
"value": 1 |
|||
} |
|||
}, |
|||
"thresholds": [], |
|||
"cloud": { |
|||
"loadZones": { |
|||
"distribution": "even", |
|||
"zones": [] |
|||
} |
|||
} |
|||
}, |
|||
"testData": { |
|||
"variables": [], |
|||
"files": [] |
|||
}, |
|||
"rules": [ |
|||
{ |
|||
"id": "a20afe1c-16b7-4ec5-aa39-7785e7163d4a", |
|||
"enabled": true, |
|||
"type": "verification", |
|||
"filter": { |
|||
"path": "" |
|||
}, |
|||
"target": "status", |
|||
"operator": "equals", |
|||
"value": { |
|||
"type": "recordedValue" |
|||
} |
|||
}, |
|||
{ |
|||
"id": "6b0c1f4e-1a01-4d6e-9b1a-000000000001", |
|||
"enabled": true, |
|||
"type": "correlation", |
|||
"extractor": { |
|||
"filter": { |
|||
"path": "" |
|||
}, |
|||
"selector": { |
|||
"type": "begin-end", |
|||
"from": "body", |
|||
"begin": "name=\"__RequestVerificationToken\" type=\"hidden\" value=\"", |
|||
"end": "\"" |
|||
}, |
|||
"extractionMode": "multiple" |
|||
}, |
|||
"replacer": { |
|||
"filter": { |
|||
"path": "" |
|||
} |
|||
} |
|||
}, |
|||
{ |
|||
"id": "6b0c1f4e-1a01-4d6e-9b1a-000000000002", |
|||
"enabled": true, |
|||
"type": "correlation", |
|||
"extractor": { |
|||
"filter": { |
|||
"path": "" |
|||
}, |
|||
"selector": { |
|||
"type": "begin-end", |
|||
"from": "body", |
|||
"begin": "name=\"__RequestVerificationToken\" type=\"hidden\" value=\"", |
|||
"end": "\"" |
|||
}, |
|||
"extractionMode": "multiple" |
|||
}, |
|||
"replacer": { |
|||
"filter": { |
|||
"path": "" |
|||
}, |
|||
"selector": { |
|||
"type": "header-name", |
|||
"from": "headers", |
|||
"name": "RequestVerificationToken" |
|||
} |
|||
} |
|||
}, |
|||
{ |
|||
"id": "6b0c1f4e-1a01-4d6e-9b1a-000000000003", |
|||
"enabled": true, |
|||
"type": "correlation", |
|||
"extractor": { |
|||
"filter": { |
|||
"path": "/api/identity/users?filter=rec_user" |
|||
}, |
|||
"selector": { |
|||
"type": "json", |
|||
"from": "body", |
|||
"path": "items[0].id" |
|||
}, |
|||
"extractionMode": "multiple" |
|||
}, |
|||
"replacer": { |
|||
"filter": { |
|||
"path": "" |
|||
} |
|||
} |
|||
}, |
|||
{ |
|||
"id": "6b0c1f4e-1a01-4d6e-9b1a-000000000004", |
|||
"enabled": true, |
|||
"type": "correlation", |
|||
"extractor": { |
|||
"filter": { |
|||
"path": "/api/identity/roles" |
|||
}, |
|||
"selector": { |
|||
"type": "regex", |
|||
"from": "body", |
|||
"regex": "\"name\":\"rec_role\"[^}]*?\"id\":\"([^\"]+)\"" |
|||
}, |
|||
"extractionMode": "multiple" |
|||
}, |
|||
"replacer": { |
|||
"filter": { |
|||
"path": "" |
|||
} |
|||
} |
|||
}, |
|||
{ |
|||
"id": "6b0c1f4e-1a01-4d6e-9b1a-000000000005", |
|||
"enabled": true, |
|||
"type": "correlation", |
|||
"extractor": { |
|||
"filter": { |
|||
"path": "/api/multi-tenancy/tenants" |
|||
}, |
|||
"selector": { |
|||
"type": "json", |
|||
"from": "body", |
|||
"path": "items[0].id" |
|||
}, |
|||
"extractionMode": "multiple" |
|||
}, |
|||
"replacer": { |
|||
"filter": { |
|||
"path": "" |
|||
} |
|||
} |
|||
}, |
|||
{ |
|||
"id": "6b0c1f4e-1a01-4d6e-9b1a-000000000006", |
|||
"enabled": true, |
|||
"type": "correlation", |
|||
"extractor": { |
|||
"filter": { |
|||
"path": "" |
|||
}, |
|||
"selector": { |
|||
"type": "regex", |
|||
"from": "body", |
|||
"regex": "name=\"(?:\\w+\\.)?ConcurrencyStamp\" value=\"([^\"]+)\"" |
|||
}, |
|||
"extractionMode": "multiple" |
|||
}, |
|||
"replacer": { |
|||
"filter": { |
|||
"path": "" |
|||
} |
|||
} |
|||
} |
|||
], |
|||
"allowlist": [ |
|||
"bench.localtest.me", |
|||
"bench.localtest.me:44377" |
|||
], |
|||
"includeStaticAssets": false, |
|||
"scriptName": "abp-mvc-correlated.js", |
|||
"wizardUsed": false |
|||
} |
|||
@ -0,0 +1,49 @@ |
|||
// Makes a k6 Studio recording safe to commit:
|
|||
// keeps only the app's requests, drops static response bodies, and redacts passwords and cookie values.
|
|||
// Usage: node k6/tools/sanitize-har.mjs <raw.har> <out.har> [host]
|
|||
import { readFileSync, writeFileSync } from 'node:fs'; |
|||
|
|||
const [input, output, host = 'bench.localtest.me:44377'] = process.argv.slice(2); |
|||
if (!input || !output) throw new Error('usage: sanitize-har.mjs <raw.har> <out.har> [host]'); |
|||
|
|||
const REDACTED = '<redacted>'; |
|||
const isStatic = (path) => /^\/(libs|__bundles|Themes|images|fonts|favicon)|\.(js|css|woff2?|png|svg|ico|map)$/i.test(path); |
|||
const isPasswordField = (name) => /password/i.test(name); |
|||
|
|||
const redactCookies = (list = []) => list.forEach((c) => { c.value = REDACTED; }); |
|||
const redactHeaders = (list = []) => list.forEach((h) => { |
|||
if (/^(cookie|set-cookie|requestverificationtoken)$/i.test(h.name)) h.value = REDACTED; |
|||
}); |
|||
const redactText = (text) => text |
|||
// JSON bodies: "somePassword":"value"
|
|||
.replace(/("[^"]*password[^"]*"\s*:\s*")[^"]*/gi, `$1${REDACTED}`) |
|||
// multipart bodies: name="X.Password"\r\n\r\nvalue
|
|||
.replace(/(name="[^"]*password[^"]*"\r?\n\r?\n)[^\r\n]*/gi, `$1${REDACTED}`); |
|||
|
|||
const har = JSON.parse(readFileSync(input, 'utf8')); |
|||
const log = har.log; |
|||
|
|||
log.entries = log.entries.filter((e) => new URL(e.request.url).host === host); |
|||
for (const e of log.entries) { |
|||
const { pathname } = new URL(e.request.url); |
|||
redactHeaders(e.request.headers); |
|||
redactHeaders(e.response.headers); |
|||
redactCookies(e.request.cookies); |
|||
redactCookies(e.response.cookies); |
|||
const post = e.request.postData; |
|||
if (post?.params) post.params.forEach((p) => { if (isPasswordField(p.name)) p.value = REDACTED; }); |
|||
if (post?.text) post.text = redactText(post.text); |
|||
if (isStatic(pathname) && e.response.content) { |
|||
delete e.response.content.text; |
|||
delete e.response.content.encoding; |
|||
} |
|||
} |
|||
|
|||
const events = log._browserEvents?.events ?? []; |
|||
log._browserEvents.events = events.filter((ev) => !ev.url || new URL(ev.url).host === host); |
|||
for (const ev of log._browserEvents.events) { |
|||
if (ev.sensitive || isPasswordField(JSON.stringify(ev.target ?? {}))) ev.value = REDACTED; |
|||
} |
|||
|
|||
writeFileSync(output, JSON.stringify(har, null, 1)); |
|||
console.log(`${log.entries.length} entries, ${log._browserEvents.events.length} browser events -> ${output}`); |
|||
@ -0,0 +1,139 @@ |
|||
// Summarizes a results/<batch> folder written by scripts/run-bench.ps1 into Markdown tables.
|
|||
// probe batch: one row per target and load step (to find the saturation point)
|
|||
// fixed batch: one row per target and rate, median over the repetitions (min-max in brackets)
|
|||
// Usage: node k6/tools/summarize.mjs results/<batch> [out.md]
|
|||
import { readFileSync, readdirSync, existsSync, writeFileSync } from 'node:fs'; |
|||
import { join } from 'node:path'; |
|||
|
|||
const [batchDir, outFile] = process.argv.slice(2); |
|||
if (!batchDir) throw new Error('usage: summarize.mjs results/<batch> [out.md]'); |
|||
const batch = JSON.parse(readFileSync(join(batchDir, 'batch.json'), 'utf8')); |
|||
const readJson = (f) => JSON.parse(readFileSync(f, 'utf8')); |
|||
const avg = (xs) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : NaN); |
|||
const median = (xs) => { const s = [...xs].sort((a, b) => a - b); const m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; }; |
|||
|
|||
// dotnet-counters CSV: Timestamp(local),Provider,Counter Name,Counter Type,Mean/Increment
|
|||
function readCounters(file) { |
|||
return readFileSync(file, 'utf8').split(/\r?\n/).slice(1).filter(Boolean).map((line) => { |
|||
const parts = line.split(','); |
|||
return { t: new Date(parts[0]).getTime(), name: parts.slice(2, -2).join(','), value: Number(parts.at(-1)) }; |
|||
}); |
|||
} |
|||
|
|||
// docker stats: <UTC ISO>\t{json}
|
|||
function readDocker(file) { |
|||
if (!existsSync(file)) return []; |
|||
return readFileSync(file, 'utf8').split(/\r?\n/).filter((l) => l.includes('\t{')).map((l) => { |
|||
const [t, json] = l.split('\t'); |
|||
const s = JSON.parse(json); |
|||
const mem = /([\d.]+)(\w+)/.exec(s.MemUsage); |
|||
const mib = mem ? Number(mem[1]) * ({ KiB: 1 / 1024, MiB: 1, GiB: 1024 }[mem[2]] ?? 1) : NaN; |
|||
return { t: new Date(t).getTime(), cpu: parseFloat(s.CPUPerc), memMiB: mib }; |
|||
}); |
|||
} |
|||
|
|||
// Server-side figures for one time window [from, to) in ms.
|
|||
function serverStats(counters, docker, from, to) { |
|||
const inWin = counters.filter((c) => c.t >= from && c.t < to); |
|||
const series = (prefix) => inWin.filter((c) => c.name.startsWith(prefix)); |
|||
const perSecond = (prefix) => { // sum the tagged series per timestamp, e.g. cpu.time user + system
|
|||
const byT = new Map(); |
|||
for (const c of series(prefix)) byT.set(c.t, (byT.get(c.t) ?? 0) + c.value); |
|||
return [...byT.values()]; |
|||
}; |
|||
const cpus = series('dotnet.process.cpu.count').map((c) => c.value).at(-1) || 1; |
|||
const cpu = perSecond('dotnet.process.cpu.time').map((v) => (v / cpus) * 100); |
|||
const ws = series('dotnet.process.memory.working_set').map((c) => c.value / 2 ** 20); |
|||
const heap = series('dotnet.gc.last_collection.heap.size').length ? perSecond('dotnet.gc.last_collection.heap.size').map((v) => v / 2 ** 20) : []; |
|||
const gcPause = perSecond('dotnet.gc.pause.time').map((v) => v * 1000); |
|||
const gen2 = series('dotnet.gc.collections ({collection} / 1 sec)[gc.heap.generation=gen2]').reduce((a, c) => a + c.value, 0); |
|||
const tpQueue = series('dotnet.thread_pool.queue.length').map((c) => c.value); |
|||
const db = docker.filter((d) => d.t >= from && d.t < to); |
|||
return { |
|||
cpuAvg: avg(cpu), cpuMax: Math.max(...cpu), wsAvg: avg(ws), wsMax: Math.max(...ws), heapAvg: avg(heap), |
|||
gcPauseMsPerS: avg(gcPause), gen2, tpQueueMax: Math.max(0, ...tpQueue), |
|||
dbCpuAvg: avg(db.map((d) => d.cpu)), dbMemAvg: avg(db.map((d) => d.memMiB)), |
|||
}; |
|||
} |
|||
|
|||
function k6Stats(metrics, scenario, seconds) { |
|||
const m = (name) => metrics[`${name}{scenario:${scenario}}`] ?? {}; |
|||
const d = m('http_req_duration'); |
|||
return { |
|||
rps: (m('http_reqs').count ?? 0) / seconds, itps: (m('iterations').count ?? 0) / seconds, |
|||
avg: d.avg, med: d.med, p95: d['p(95)'], p99: d['p(99)'], |
|||
failed: m('http_req_failed').value ?? 0, checks: m('checks').value ?? 0, dropped: m('dropped_iterations').count ?? 0, |
|||
groups: Object.fromEntries(Object.entries(metrics) |
|||
.filter(([k]) => k.startsWith(`http_req_duration{scenario:${scenario},group:::`)) |
|||
.map(([k, v]) => [k.match(/group:::(\w+)/)[1], v.max > 0 ? v['p(95)'] : NaN])), // max 0 = no requests
|
|||
}; |
|||
} |
|||
|
|||
function runs() { |
|||
const out = []; |
|||
for (const target of readdirSync(batchDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name)) { |
|||
for (const label of readdirSync(join(batchDir, target))) { |
|||
for (const rep of readdirSync(join(batchDir, target, label))) { |
|||
const dir = join(batchDir, target, label, rep); |
|||
if (!existsSync(join(dir, 'k6-summary.json'))) { console.error(`skipping ${dir}: no k6 summary`); continue; } |
|||
out.push({ target, label, rep, dir, run: readJson(join(dir, 'run.json')), metrics: readJson(join(dir, 'k6-summary.json')).metrics }); |
|||
} |
|||
} |
|||
} |
|||
return out; |
|||
} |
|||
|
|||
const f = (x, d = 1) => (Number.isFinite(x) ? x.toFixed(d) : '-'); |
|||
const pct = (x) => (Number.isFinite(x) ? `${(x * 100).toFixed(2)}%` : '-'); |
|||
const lines = [`# Results: ${batchDir.split(/[\\/]/).at(-1)}`, '', '```json', JSON.stringify(batch), '```', '']; |
|||
|
|||
if (batch.mode === 'probe') { |
|||
const rates = String(batch.probeRates).split(',').map(Number); |
|||
lines.push('| target | rate it/s | req/s | p95 ms | p99 ms | failed | dropped it | app CPU % (avg/max) | working set MB | GC pause ms/s | TP queue max | DB CPU % |', |
|||
'|---|---|---|---|---|---|---|---|---|---|---|---|'); |
|||
for (const r of runs()) { |
|||
const counters = readCounters(join(r.dir, 'counters.csv')); |
|||
const docker = readDocker(join(r.dir, 'docker-stats.tsv')); |
|||
const t0 = new Date(r.run.startedUtc).getTime(); |
|||
rates.forEach((rate, i) => { |
|||
const s = `step_${String(rate).padStart(3, '0')}`; |
|||
const from = t0 + (i + 1) * (batch.stepS + batch.graceS) * 1000; |
|||
const k = k6Stats(r.metrics, s, batch.stepS); |
|||
const srv = serverStats(counters, docker, from + 5000, from + batch.stepS * 1000); // skip the ramp-in seconds
|
|||
lines.push(`| ${r.target} | ${rate} | ${f(k.rps)} | ${f(k.p95)} | ${f(k.p99)} | ${pct(k.failed)} | ${k.dropped} | ${f(srv.cpuAvg)} / ${f(srv.cpuMax)} | ${f(srv.wsAvg, 0)} | ${f(srv.gcPauseMsPerS)} | ${srv.tpQueueMax} | ${f(srv.dbCpuAvg)} |`); |
|||
}); |
|||
} |
|||
} else { |
|||
const groups = new Map(); |
|||
for (const r of runs()) { |
|||
const counters = readCounters(join(r.dir, 'counters.csv')); |
|||
const docker = readDocker(join(r.dir, 'docker-stats.tsv')); |
|||
const from = new Date(r.run.startedUtc).getTime() + r.run.measureStartOffsetS * 1000; |
|||
const row = { ...k6Stats(r.metrics, 'measure', batch.durationS), ...serverStats(counters, docker, from, from + batch.durationS * 1000) }; |
|||
const key = `${r.label}|${r.target}`; |
|||
groups.set(key, [...(groups.get(key) ?? []), row]); |
|||
} |
|||
const cell = (rows, k, d = 1) => { |
|||
const xs = rows.map((r) => r[k]).filter(Number.isFinite); |
|||
return xs.length > 1 ? `${f(median(xs), d)} (${f(Math.min(...xs), d)}–${f(Math.max(...xs), d)})` : f(xs[0], d); |
|||
}; |
|||
const sorted = [...groups.entries()].sort(([a], [b]) => a.localeCompare(b, 'en', { numeric: true })); |
|||
lines.push('Median of repetitions (min–max).', '', |
|||
'| rate | target | reps | req/s | avg ms | p95 ms | p99 ms | failed | app CPU % | CPU max % | working set MB | GC heap MB | GC pause ms/s | gen2 GCs | DB CPU % |', |
|||
'|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|'); |
|||
for (const [key, rows] of sorted) { |
|||
const [label, target] = key.split('|'); |
|||
lines.push(`| ${label.replace('rate', '')} it/s | ${target} | ${rows.length} | ${cell(rows, 'rps')} | ${cell(rows, 'avg')} | ${cell(rows, 'p95')} | ${cell(rows, 'p99')} | ${pct(median(rows.map((r) => r.failed)))} | ${cell(rows, 'cpuAvg')} | ${cell(rows, 'cpuMax')} | ${cell(rows, 'wsAvg', 0)} | ${cell(rows, 'heapAvg', 0)} | ${cell(rows, 'gcPauseMsPerS')} | ${cell(rows, 'gen2', 0)} | ${cell(rows, 'dbCpuAvg')} |`); |
|||
} |
|||
lines.push('', '## p95 per page group (ms, median of repetitions)', ''); |
|||
const groupNames = [...new Set(sorted.flatMap(([, rows]) => Object.keys(rows[0].groups)))].sort(); |
|||
lines.push(`| rate | target | ${groupNames.join(' | ')} |`, `|---|---|${groupNames.map(() => '---').join('|')}|`); |
|||
for (const [key, rows] of sorted) { |
|||
const [label, target] = key.split('|'); |
|||
lines.push(`| ${label.replace('rate', '')} | ${target} | ${groupNames.map((g) => f(median(rows.map((r) => r.groups[g]).filter(Number.isFinite)))).join(' | ')} |`); |
|||
} |
|||
} |
|||
|
|||
const md = lines.join('\n') + '\n'; |
|||
if (outFile) writeFileSync(outFile, md); |
|||
process.stdout.write(md); |
|||
@ -0,0 +1,26 @@ |
|||
# Files listed here are hidden from ABP Studio AI Assistant. |
|||
# Syntax is identical to .gitignore. |
|||
|
|||
# Secrets and sensitive configuration |
|||
**/appsettings.secrets.json |
|||
|
|||
# Environment files |
|||
.env |
|||
.env.* |
|||
!.env.example |
|||
|
|||
# Certificates and private keys |
|||
*.pfx |
|||
*.p12 |
|||
*.pem |
|||
*.key |
|||
*.p8 |
|||
*.mobileprovision |
|||
|
|||
# Local development overrides (may contain credentials) |
|||
**/values.localdev.yaml |
|||
tunnel-config.json |
|||
|
|||
# Temporary signing keys |
|||
tempkey.rsa |
|||
tempkey.jwk |
|||
@ -0,0 +1,182 @@ |
|||
--- |
|||
description: "Core ABP Framework conventions - module system, dependency injection, and base classes" |
|||
alwaysApply: true |
|||
--- |
|||
|
|||
# ABP Core Conventions |
|||
|
|||
> **Documentation**: https://abp.io/docs/latest |
|||
> **API Reference**: https://abp.io/docs/api/ |
|||
|
|||
## Module System |
|||
Every ABP application/module has a module class that configures services: |
|||
|
|||
```csharp |
|||
[DependsOn( |
|||
typeof(AbpDddDomainModule), |
|||
typeof(AbpEntityFrameworkCoreModule) |
|||
)] |
|||
public class MyAppModule : AbpModule |
|||
{ |
|||
public override void ConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
// Service registration and configuration |
|||
} |
|||
} |
|||
``` |
|||
|
|||
> **Note**: Middleware configuration (`OnApplicationInitialization`) should only be done in the final host application, not in reusable modules. |
|||
|
|||
## Dependency Injection Conventions |
|||
|
|||
### Automatic Registration |
|||
ABP automatically registers services implementing marker interfaces: |
|||
- `ITransientDependency` → Transient lifetime |
|||
- `ISingletonDependency` → Singleton lifetime |
|||
- `IScopedDependency` → Scoped lifetime |
|||
|
|||
Classes inheriting from `ApplicationService`, `DomainService`, `AbpController` are also auto-registered. |
|||
|
|||
### Repository Usage |
|||
You can use the generic `IRepository<TEntity, TKey>` for simple CRUD operations. Define custom repository interfaces only when you need custom query methods: |
|||
|
|||
```csharp |
|||
// Simple CRUD - Generic repository is fine |
|||
public class BookAppService : ApplicationService |
|||
{ |
|||
private readonly IRepository<Book, Guid> _bookRepository; // ✅ OK for simple operations |
|||
} |
|||
|
|||
// Custom queries needed - Define custom interface |
|||
public interface IBookRepository : IRepository<Book, Guid> |
|||
{ |
|||
Task<Book> FindByNameAsync(string name); // Custom query |
|||
} |
|||
|
|||
public class BookAppService : ApplicationService |
|||
{ |
|||
private readonly IBookRepository _bookRepository; // ✅ Use custom when needed |
|||
} |
|||
``` |
|||
|
|||
### Exposing Services |
|||
```csharp |
|||
[ExposeServices(typeof(IMyService))] |
|||
public class MyService : IMyService, ITransientDependency { } |
|||
``` |
|||
|
|||
## Important Base Classes |
|||
|
|||
| Base Class | Purpose | |
|||
|------------|---------| |
|||
| `Entity<TKey>` | Basic entity with ID | |
|||
| `AggregateRoot<TKey>` | DDD aggregate root | |
|||
| `DomainService` | Domain business logic | |
|||
| `ApplicationService` | Use case orchestration | |
|||
| `AbpController` | REST API controller | |
|||
|
|||
ABP base classes already inject commonly used services as properties. Before injecting a service, check if it's already available: |
|||
|
|||
| Property | Available In | Description | |
|||
|----------|--------------|-------------| |
|||
| `GuidGenerator` | All base classes | Generate GUIDs | |
|||
| `Clock` | All base classes | Current time (use instead of `DateTime`) | |
|||
| `CurrentUser` | All base classes | Authenticated user info | |
|||
| `CurrentTenant` | All base classes | Multi-tenancy context | |
|||
| `L` (StringLocalizer) | `ApplicationService`, `AbpController` | Localization | |
|||
| `AuthorizationService` | `ApplicationService`, `AbpController` | Permission checks | |
|||
| `FeatureChecker` | `ApplicationService`, `AbpController` | Feature availability | |
|||
| `DataFilter` | All base classes | Data filtering (soft-delete, tenant) | |
|||
| `UnitOfWorkManager` | `ApplicationService`, `DomainService` | Unit of work management | |
|||
| `LoggerFactory` | All base classes | Create loggers | |
|||
| `Logger` | All base classes | Logging (auto-created) | |
|||
| `LazyServiceProvider` | All base classes | Lazy service resolution | |
|||
|
|||
**Useful methods from base classes:** |
|||
- `CheckPolicyAsync()` - Check permission and throw if not granted |
|||
- `IsGrantedAsync()` - Check permission without throwing |
|||
|
|||
## Async Best Practices |
|||
- Use async all the way - never use `.Result` or `.Wait()` |
|||
- All async methods should end with `Async` suffix |
|||
- ABP automatically handles `CancellationToken` in most cases (e.g., from `HttpContext.RequestAborted`) |
|||
- Only pass `CancellationToken` explicitly when implementing custom cancellation logic |
|||
|
|||
## Time Handling |
|||
Never use `DateTime.Now` or `DateTime.UtcNow` directly. Use ABP's `IClock` service: |
|||
|
|||
```csharp |
|||
// In classes inheriting from base classes (ApplicationService, DomainService, etc.) |
|||
public class BookAppService : ApplicationService |
|||
{ |
|||
public void DoSomething() |
|||
{ |
|||
var now = Clock.Now; // ✅ Already available as property |
|||
} |
|||
} |
|||
|
|||
// In other services - inject IClock |
|||
public class MyService : ITransientDependency |
|||
{ |
|||
private readonly IClock _clock; |
|||
|
|||
public MyService(IClock clock) => _clock = clock; |
|||
|
|||
public void DoSomething() |
|||
{ |
|||
var now = _clock.Now; // ✅ Correct |
|||
// var now = DateTime.Now; // ❌ Wrong - not testable, ignores timezone settings |
|||
} |
|||
} |
|||
``` |
|||
|
|||
> **Tip**: Before injecting a service, check if it's already available as a property in your base classes. |
|||
|
|||
## Business Exceptions |
|||
Use `BusinessException` for domain rule violations with namespaced error codes: |
|||
|
|||
```csharp |
|||
throw new BusinessException("MyModule:BookNameAlreadyExists") |
|||
.WithData("Name", bookName); |
|||
``` |
|||
|
|||
Configure localization mapping: |
|||
```csharp |
|||
Configure<AbpExceptionLocalizationOptions>(options => |
|||
{ |
|||
options.MapCodeNamespace("MyModule", typeof(MyModuleResource)); |
|||
}); |
|||
``` |
|||
|
|||
## Localization |
|||
- In base classes (`ApplicationService`, `AbpController`, etc.): Use `L["Key"]` - this is the `IStringLocalizer` property |
|||
- In other services: Inject `IStringLocalizer<TResource>` |
|||
- Always localize user-facing messages and exceptions |
|||
|
|||
**Localization file location**: `*.Domain.Shared/Localization/{ResourceName}/{lang}.json` |
|||
|
|||
```json |
|||
// Example: MyProject.Domain.Shared/Localization/MyProject/en.json |
|||
{ |
|||
"culture": "en", |
|||
"texts": { |
|||
"Menu:Home": "Home", |
|||
"Welcome": "Welcome", |
|||
"BookName": "Book Name" |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## ❌ Never Use (ABP Anti-Patterns) |
|||
|
|||
| Don't Use | Use Instead | |
|||
|-----------|-------------| |
|||
| Minimal APIs | ABP Controllers or Auto API Controllers | |
|||
| MediatR | Application Services | |
|||
| `DbContext` directly in App Services | `IRepository<T>` | |
|||
| `AddScoped/AddTransient/AddSingleton` | `ITransientDependency`, `ISingletonDependency` | |
|||
| `DateTime.Now` | `IClock` / `Clock.Now` | |
|||
| Custom UnitOfWork | ABP's `IUnitOfWorkManager` | |
|||
| Manual HTTP calls from UI | ABP client proxies (`generate-proxy`) | |
|||
| Hardcoded role checks | Permission-based authorization | |
|||
| Business logic in Controllers | Application Services | |
|||
@ -0,0 +1,236 @@ |
|||
--- |
|||
description: "ABP Application Services, DTOs, validation, and error handling patterns" |
|||
globs: |
|||
- "**/*.Application/**/*.cs" |
|||
- "**/Application/**/*.cs" |
|||
- "**/*AppService*.cs" |
|||
- "**/*Dto*.cs" |
|||
alwaysApply: false |
|||
--- |
|||
|
|||
# ABP Application Layer Patterns |
|||
|
|||
> **Docs**: https://abp.io/docs/latest/framework/architecture/domain-driven-design/application-services |
|||
|
|||
## Application Service Structure |
|||
|
|||
### Interface (Application.Contracts) |
|||
```csharp |
|||
public interface IBookAppService : IApplicationService |
|||
{ |
|||
Task<BookDto> GetAsync(Guid id); |
|||
Task<PagedResultDto<BookListItemDto>> GetListAsync(GetBookListInput input); |
|||
Task<BookDto> CreateAsync(CreateBookDto input); |
|||
Task<BookDto> UpdateAsync(Guid id, UpdateBookDto input); |
|||
Task DeleteAsync(Guid id); |
|||
} |
|||
``` |
|||
|
|||
### Implementation (Application) |
|||
```csharp |
|||
public class BookAppService : ApplicationService, IBookAppService |
|||
{ |
|||
private readonly IBookRepository _bookRepository; |
|||
private readonly BookManager _bookManager; |
|||
private readonly BookMapper _bookMapper; |
|||
|
|||
public BookAppService( |
|||
IBookRepository bookRepository, |
|||
BookManager bookManager, |
|||
BookMapper bookMapper) |
|||
{ |
|||
_bookRepository = bookRepository; |
|||
_bookManager = bookManager; |
|||
_bookMapper = bookMapper; |
|||
} |
|||
|
|||
public async Task<BookDto> GetAsync(Guid id) |
|||
{ |
|||
var book = await _bookRepository.GetAsync(id); |
|||
return _bookMapper.MapToDto(book); |
|||
} |
|||
|
|||
[Authorize(BookStorePermissions.Books.Create)] |
|||
public async Task<BookDto> CreateAsync(CreateBookDto input) |
|||
{ |
|||
var book = await _bookManager.CreateAsync(input.Name, input.Price); |
|||
await _bookRepository.InsertAsync(book); |
|||
return _bookMapper.MapToDto(book); |
|||
} |
|||
|
|||
[Authorize(BookStorePermissions.Books.Edit)] |
|||
public async Task<BookDto> UpdateAsync(Guid id, UpdateBookDto input) |
|||
{ |
|||
var book = await _bookRepository.GetAsync(id); |
|||
await _bookManager.ChangeNameAsync(book, input.Name); |
|||
book.SetPrice(input.Price); |
|||
await _bookRepository.UpdateAsync(book); |
|||
return _bookMapper.MapToDto(book); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Application Service Best Practices |
|||
- Don't repeat entity name in method names (`GetAsync` not `GetBookAsync`) |
|||
- Accept/return DTOs only, never entities |
|||
- ID not inside UpdateDto - pass separately |
|||
- Use custom repositories when you need custom queries, generic repository is fine for simple CRUD |
|||
- Call `UpdateAsync` explicitly (don't assume change tracking) |
|||
- Don't call other app services in same module |
|||
- Don't use `IFormFile`/`Stream` - pass `byte[]` from controllers |
|||
- Use base class properties (`Clock`, `CurrentUser`, `GuidGenerator`, `L`) instead of injecting these services |
|||
|
|||
## DTO Naming Conventions |
|||
|
|||
| Purpose | Convention | Example | |
|||
|---------|------------|---------| |
|||
| Query input | `Get{Entity}Input` | `GetBookInput` | |
|||
| List query input | `Get{Entity}ListInput` | `GetBookListInput` | |
|||
| Create input | `Create{Entity}Dto` | `CreateBookDto` | |
|||
| Update input | `Update{Entity}Dto` | `UpdateBookDto` | |
|||
| Single entity output | `{Entity}Dto` | `BookDto` | |
|||
| List item output | `{Entity}ListItemDto` | `BookListItemDto` | |
|||
|
|||
## DTO Location |
|||
- Define DTOs in `*.Application.Contracts` project |
|||
- This allows sharing with clients (Blazor, HttpApi.Client) |
|||
|
|||
## Validation |
|||
|
|||
### Data Annotations |
|||
```csharp |
|||
public class CreateBookDto |
|||
{ |
|||
[Required] |
|||
[StringLength(100, MinimumLength = 3)] |
|||
public string Name { get; set; } |
|||
|
|||
[Range(0, 999.99)] |
|||
public decimal Price { get; set; } |
|||
} |
|||
``` |
|||
|
|||
### Custom Validation with IValidatableObject |
|||
Before adding custom validation, decide if it's a **domain rule** or **application rule**: |
|||
- **Domain rule**: Put validation in entity constructor or domain service (enforces business invariants) |
|||
- **Application rule**: Use DTO validation (input format, required fields) |
|||
|
|||
Only use `IValidatableObject` for application-level validation that can't be expressed with data annotations: |
|||
|
|||
```csharp |
|||
public class CreateBookDto : IValidatableObject |
|||
{ |
|||
public string Name { get; set; } |
|||
public string Description { get; set; } |
|||
|
|||
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) |
|||
{ |
|||
if (Name == Description) |
|||
{ |
|||
yield return new ValidationResult( |
|||
"Name and Description cannot be the same!", |
|||
new[] { nameof(Name), nameof(Description) } |
|||
); |
|||
} |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### FluentValidation |
|||
```csharp |
|||
public class CreateBookDtoValidator : AbstractValidator<CreateBookDto> |
|||
{ |
|||
public CreateBookDtoValidator() |
|||
{ |
|||
RuleFor(x => x.Name).NotEmpty().Length(3, 100); |
|||
RuleFor(x => x.Price).GreaterThan(0); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Error Handling |
|||
|
|||
### Business Exceptions |
|||
```csharp |
|||
throw new BusinessException("BookStore:010001") |
|||
.WithData("BookName", name); |
|||
``` |
|||
|
|||
### Entity Not Found |
|||
```csharp |
|||
var book = await _bookRepository.FindAsync(id); |
|||
if (book == null) |
|||
{ |
|||
throw new EntityNotFoundException(typeof(Book), id); |
|||
} |
|||
``` |
|||
|
|||
### User-Friendly Exceptions |
|||
```csharp |
|||
throw new UserFriendlyException(L["BookNotAvailable"]); |
|||
``` |
|||
|
|||
### HTTP Status Code Mapping |
|||
Status code mapping is **configurable** in ABP (do not rely on a fixed mapping in business logic). |
|||
|
|||
| Exception | Typical HTTP Status | |
|||
|-----------|-------------| |
|||
| `AbpValidationException` | 400 | |
|||
| `AbpAuthorizationException` | 401/403 | |
|||
| `EntityNotFoundException` | 404 | |
|||
| `BusinessException` | 403 (but configurable) | |
|||
| Other exceptions | 500 | |
|||
|
|||
## Auto API Controllers |
|||
ABP automatically generates API controllers for application services: |
|||
- Interface must inherit `IApplicationService` (which already has `[RemoteService]` attribute) |
|||
- HTTP methods determined by method name prefix (Get, Create, Update, Delete) |
|||
- Use `[RemoteService(false)]` to disable auto API generation for specific methods |
|||
|
|||
## Object Mapping (Mapperly / AutoMapper) |
|||
ABP supports **both Mapperly and AutoMapper** integrations. But the default mapping library is Mapperly. You need to first check the project's active mapping library. |
|||
- Prefer the mapping provider already used in the solution (check existing mapping files / loaded modules). |
|||
- In mixed solutions, explicitly setting the default provider may be required (see `docs/en/release-info/migration-guides/AutoMapper-To-Mapperly.md`). |
|||
|
|||
### Mapperly (compile-time) |
|||
Define mappers as partial classes: |
|||
|
|||
```csharp |
|||
[Mapper] |
|||
public partial class BookMapper |
|||
{ |
|||
public partial BookDto MapToDto(Book book); |
|||
public partial List<BookDto> MapToDtoList(List<Book> books); |
|||
} |
|||
``` |
|||
|
|||
Register in module: |
|||
```csharp |
|||
public override void ConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
context.Services.AddSingleton<BookMapper>(); |
|||
} |
|||
``` |
|||
|
|||
Usage in application service: |
|||
```csharp |
|||
public class BookAppService : ApplicationService |
|||
{ |
|||
private readonly BookMapper _bookMapper; |
|||
|
|||
public BookAppService(BookMapper bookMapper) |
|||
{ |
|||
_bookMapper = bookMapper; |
|||
} |
|||
|
|||
public BookDto GetBook(Book book) |
|||
{ |
|||
return _bookMapper.MapToDto(book); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
> **Note**: Mapperly generates mapping code at compile-time, providing better performance than runtime mappers. |
|||
|
|||
### AutoMapper (runtime) |
|||
If the solution uses AutoMapper, mappings are typically defined in `Profile` classes and registered via ABP's AutoMapper integration. |
|||
@ -0,0 +1,186 @@ |
|||
--- |
|||
description: "ABP permission system and authorization patterns" |
|||
globs: |
|||
- "**/*Permission*.cs" |
|||
- "**/*AppService*.cs" |
|||
- "**/*Controller*.cs" |
|||
alwaysApply: false |
|||
--- |
|||
|
|||
# ABP Authorization |
|||
|
|||
> **Docs**: https://abp.io/docs/latest/framework/fundamentals/authorization |
|||
|
|||
## Permission Definition |
|||
Define permissions in `*.Application.Contracts` project: |
|||
|
|||
```csharp |
|||
public static class BookStorePermissions |
|||
{ |
|||
public const string GroupName = "BookStore"; |
|||
|
|||
public static class Books |
|||
{ |
|||
public const string Default = GroupName + ".Books"; |
|||
public const string Create = Default + ".Create"; |
|||
public const string Edit = Default + ".Edit"; |
|||
public const string Delete = Default + ".Delete"; |
|||
} |
|||
} |
|||
``` |
|||
|
|||
Register in provider: |
|||
```csharp |
|||
public class BookStorePermissionDefinitionProvider : PermissionDefinitionProvider |
|||
{ |
|||
public override void Define(IPermissionDefinitionContext context) |
|||
{ |
|||
var bookStoreGroup = context.AddGroup(BookStorePermissions.GroupName, L("Permission:BookStore")); |
|||
|
|||
var booksPermission = bookStoreGroup.AddPermission( |
|||
BookStorePermissions.Books.Default, |
|||
L("Permission:Books")); |
|||
|
|||
booksPermission.AddChild( |
|||
BookStorePermissions.Books.Create, |
|||
L("Permission:Books.Create")); |
|||
|
|||
booksPermission.AddChild( |
|||
BookStorePermissions.Books.Edit, |
|||
L("Permission:Books.Edit")); |
|||
|
|||
booksPermission.AddChild( |
|||
BookStorePermissions.Books.Delete, |
|||
L("Permission:Books.Delete")); |
|||
} |
|||
|
|||
private static LocalizableString L(string name) |
|||
{ |
|||
return LocalizableString.Create<BookStoreResource>(name); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Using Permissions |
|||
|
|||
### Declarative (Attribute) |
|||
```csharp |
|||
[Authorize(BookStorePermissions.Books.Create)] |
|||
public virtual async Task<BookDto> CreateAsync(CreateBookDto input) |
|||
{ |
|||
// Only users with Books.Create permission can execute |
|||
} |
|||
``` |
|||
|
|||
### Programmatic Check |
|||
```csharp |
|||
public class BookAppService : ApplicationService |
|||
{ |
|||
public async Task DoSomethingAsync() |
|||
{ |
|||
// Check and throw if not granted |
|||
await CheckPolicyAsync(BookStorePermissions.Books.Edit); |
|||
|
|||
// Or check without throwing |
|||
if (await IsGrantedAsync(BookStorePermissions.Books.Delete)) |
|||
{ |
|||
// Has permission |
|||
} |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### Allow Anonymous Access |
|||
```csharp |
|||
[AllowAnonymous] |
|||
public virtual async Task<BookDto> GetPublicBookAsync(Guid id) |
|||
{ |
|||
// No authentication required |
|||
} |
|||
``` |
|||
|
|||
## Current User |
|||
Access authenticated user info via `CurrentUser` property (available in base classes like `ApplicationService`, `DomainService`, `AbpController`): |
|||
|
|||
```csharp |
|||
public class BookAppService : ApplicationService |
|||
{ |
|||
public async Task DoSomethingAsync() |
|||
{ |
|||
// CurrentUser is available from base class - no injection needed |
|||
var userId = CurrentUser.Id; |
|||
var userName = CurrentUser.UserName; |
|||
var email = CurrentUser.Email; |
|||
var isAuthenticated = CurrentUser.IsAuthenticated; |
|||
var roles = CurrentUser.Roles; |
|||
var tenantId = CurrentUser.TenantId; |
|||
} |
|||
} |
|||
|
|||
// In other services, inject ICurrentUser |
|||
public class MyService : ITransientDependency |
|||
{ |
|||
private readonly ICurrentUser _currentUser; |
|||
public MyService(ICurrentUser currentUser) => _currentUser = currentUser; |
|||
} |
|||
``` |
|||
|
|||
### Ownership Validation |
|||
```csharp |
|||
public async Task UpdateMyBookAsync(Guid bookId, UpdateBookDto input) |
|||
{ |
|||
var book = await _bookRepository.GetAsync(bookId); |
|||
|
|||
if (book.CreatorId != CurrentUser.Id) |
|||
{ |
|||
throw new AbpAuthorizationException(); |
|||
} |
|||
|
|||
// Update book... |
|||
} |
|||
``` |
|||
|
|||
## Multi-Tenancy Permissions |
|||
Control permission availability per tenant side: |
|||
|
|||
```csharp |
|||
bookStoreGroup.AddPermission( |
|||
BookStorePermissions.Books.Default, |
|||
L("Permission:Books"), |
|||
multiTenancySide: MultiTenancySides.Tenant // Only for tenants |
|||
); |
|||
``` |
|||
|
|||
Options: `MultiTenancySides.Host`, `Tenant`, or `Both` |
|||
|
|||
## Feature-Dependent Permissions |
|||
```csharp |
|||
booksPermission.RequireFeatures("BookStore.PremiumFeature"); |
|||
``` |
|||
|
|||
## Permission Management |
|||
Grant/revoke permissions programmatically: |
|||
|
|||
```csharp |
|||
public class MyService : ITransientDependency |
|||
{ |
|||
private readonly IPermissionManager _permissionManager; |
|||
|
|||
public async Task GrantPermissionToUserAsync(Guid userId, string permissionName) |
|||
{ |
|||
await _permissionManager.SetForUserAsync(userId, permissionName, true); |
|||
} |
|||
|
|||
public async Task GrantPermissionToRoleAsync(string roleName, string permissionName) |
|||
{ |
|||
await _permissionManager.SetForRoleAsync(roleName, permissionName, true); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Security Best Practices |
|||
- Never trust client input for user identity |
|||
- Use `CurrentUser` property (from base class) or inject `ICurrentUser` |
|||
- Validate ownership in application service methods |
|||
- Filter queries by current user when appropriate |
|||
- Don't expose sensitive fields in DTOs |
|||
@ -0,0 +1,92 @@ |
|||
--- |
|||
description: "ABP CLI commands: generate-proxy, install-libs, add-package-ref, new-module, install-module, update, clean, suite generate (CRUD pages)" |
|||
globs: |
|||
- "**/*.csproj" |
|||
- "**/appsettings*.json" |
|||
alwaysApply: false |
|||
--- |
|||
|
|||
# ABP CLI Commands |
|||
|
|||
> **Full documentation**: https://abp.io/docs/latest/cli |
|||
> Use `abp help [command]` for detailed options. |
|||
|
|||
## Generate Client Proxies |
|||
|
|||
```bash |
|||
# URL flag: `-u` (short) or `--url` (long). Use whichever your team prefers, but keep it consistent. |
|||
# |
|||
# Angular (host must be running) |
|||
abp generate-proxy -t ng |
|||
|
|||
# C# client proxies |
|||
abp generate-proxy -t csharp -u https://localhost:44300 |
|||
|
|||
# Integration services only (microservices) |
|||
abp generate-proxy -t csharp -u https://localhost:44300 -st integration |
|||
|
|||
# JavaScript |
|||
abp generate-proxy -t js -u https://localhost:44300 |
|||
``` |
|||
|
|||
## Install Client-Side Libraries |
|||
|
|||
```bash |
|||
# Install NPM packages for MVC/Blazor Server |
|||
abp install-libs |
|||
``` |
|||
|
|||
## Add Package Reference |
|||
|
|||
```bash |
|||
# Add project reference with module dependency |
|||
abp add-package-ref Acme.BookStore.Domain |
|||
abp add-package-ref Acme.BookStore.Domain -t Acme.BookStore.Application |
|||
``` |
|||
|
|||
## Module Operations |
|||
|
|||
```bash |
|||
# Create new module in solution |
|||
abp new-module Acme.OrderManagement -t module:ddd |
|||
|
|||
# Install published module |
|||
abp install-module Volo.Blogging |
|||
|
|||
# Add ABP NuGet package |
|||
abp add-package Volo.Abp.Caching.StackExchangeRedis |
|||
``` |
|||
|
|||
## Update & Clean |
|||
|
|||
```bash |
|||
abp update # Update all ABP packages |
|||
abp update --version 8.0.0 # Specific version |
|||
abp clean # Delete bin/obj folders |
|||
``` |
|||
|
|||
## ABP Suite (CRUD Generation) |
|||
|
|||
Generate CRUD pages from entity JSON (created via Suite UI): |
|||
|
|||
```bash |
|||
abp suite generate --entity .suite/entities/Book.json --solution ./Acme.BookStore.sln |
|||
``` |
|||
|
|||
> **Note**: Entity JSON files are created when you generate an entity via ABP Suite UI. They are stored in `.suite/entities/` folder. |
|||
> **Suite docs**: https://abp.io/docs/latest/suite |
|||
|
|||
## Quick Reference |
|||
|
|||
| Task | Command | |
|||
|------|---------| |
|||
| Angular proxies | `abp generate-proxy -t ng` | |
|||
| C# proxies | `abp generate-proxy -t csharp -u URL` | |
|||
| Install JS libs | `abp install-libs` | |
|||
| Add reference | `abp add-package-ref PackageName` | |
|||
| Create module | `abp new-module ModuleName` | |
|||
| Install module | `abp install-module ModuleName` | |
|||
| Update packages | `abp update` | |
|||
| Clean solution | `abp clean` | |
|||
| Suite CRUD | `abp suite generate -e entity.json -s solution.sln` | |
|||
| Get help | `abp help [command]` | |
|||
@ -0,0 +1,244 @@ |
|||
--- |
|||
description: "ABP DDD patterns - Entities, Aggregate Roots, Repositories, Domain Services" |
|||
globs: |
|||
- "**/*.Domain/**/*.cs" |
|||
- "**/Domain/**/*.cs" |
|||
- "**/Entities/**/*.cs" |
|||
alwaysApply: false |
|||
--- |
|||
|
|||
# ABP DDD Patterns |
|||
|
|||
> **Docs**: https://abp.io/docs/latest/framework/architecture/domain-driven-design |
|||
|
|||
## Rich Domain Model vs Anemic Domain Model |
|||
|
|||
ABP promotes **Rich Domain Model** pattern where entities contain both data AND behavior: |
|||
|
|||
| Anemic (Anti-pattern) | Rich (Recommended) | |
|||
|----------------------|-------------------| |
|||
| Entity = data only | Entity = data + behavior | |
|||
| Logic in services | Logic in entity methods | |
|||
| Public setters | Private setters with methods | |
|||
| No validation in entity | Entity enforces invariants | |
|||
|
|||
**Encapsulation is key**: Protect entity state by using private setters and exposing behavior through methods. |
|||
|
|||
## Entities |
|||
|
|||
### Entity Example (Rich Model) |
|||
```csharp |
|||
public class OrderLine : Entity<Guid> |
|||
{ |
|||
public Guid ProductId { get; private set; } |
|||
public int Count { get; private set; } |
|||
public decimal Price { get; private set; } |
|||
|
|||
protected OrderLine() { } // For ORM |
|||
|
|||
internal OrderLine(Guid id, Guid productId, int count, decimal price) : base(id) |
|||
{ |
|||
ProductId = productId; |
|||
SetCount(count); // Validates through method |
|||
Price = price; |
|||
} |
|||
|
|||
public void SetCount(int count) |
|||
{ |
|||
if (count <= 0) |
|||
throw new BusinessException("Orders:InvalidCount"); |
|||
Count = count; |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Aggregate Roots |
|||
|
|||
Aggregate roots are consistency boundaries that: |
|||
- Own their child entities |
|||
- Enforce business rules |
|||
- Publish domain events |
|||
|
|||
```csharp |
|||
public class Order : AggregateRoot<Guid> |
|||
{ |
|||
public string OrderNumber { get; private set; } |
|||
public Guid CustomerId { get; private set; } |
|||
public OrderStatus Status { get; private set; } |
|||
public ICollection<OrderLine> Lines { get; private set; } |
|||
|
|||
protected Order() { } // For ORM |
|||
|
|||
public Order(Guid id, string orderNumber, Guid customerId) : base(id) |
|||
{ |
|||
OrderNumber = Check.NotNullOrWhiteSpace(orderNumber, nameof(orderNumber)); |
|||
CustomerId = customerId; |
|||
Status = OrderStatus.Created; |
|||
Lines = new List<OrderLine>(); |
|||
} |
|||
|
|||
public void AddLine(Guid lineId, Guid productId, int count, decimal price) |
|||
{ |
|||
// Business rule: Can only add lines to created orders |
|||
if (Status != OrderStatus.Created) |
|||
throw new BusinessException("Orders:CannotModifyOrder"); |
|||
|
|||
Lines.Add(new OrderLine(lineId, productId, count, price)); |
|||
} |
|||
|
|||
public void Complete() |
|||
{ |
|||
if (Status != OrderStatus.Created) |
|||
throw new BusinessException("Orders:CannotCompleteOrder"); |
|||
|
|||
Status = OrderStatus.Completed; |
|||
|
|||
// Publish events for side effects |
|||
AddLocalEvent(new OrderCompletedEvent(Id)); // Same transaction |
|||
AddDistributedEvent(new OrderCompletedEto { OrderId = Id }); // Cross-service |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### Domain Events |
|||
- `AddLocalEvent()` - Handled within same transaction, can access full entity |
|||
- `AddDistributedEvent()` - Handled asynchronously, use ETOs (Event Transfer Objects) |
|||
|
|||
### Entity Best Practices |
|||
- **Encapsulation**: Private setters, public methods that enforce rules |
|||
- **Primary constructor**: Enforce invariants, accept `id` parameter |
|||
- **Protected parameterless constructor**: Required for ORM |
|||
- **Initialize collections**: In primary constructor |
|||
- **Virtual members**: For ORM proxy compatibility |
|||
- **Reference by Id**: Don't add navigation properties to other aggregates |
|||
- **Don't generate GUID in constructor**: Use `IGuidGenerator` externally |
|||
|
|||
## Repository Pattern |
|||
|
|||
### When to Use Custom Repository |
|||
- **Generic repository** (`IRepository<T, TKey>`): Sufficient for simple CRUD operations |
|||
- **Custom repository**: Only when you need custom query methods |
|||
|
|||
### Interface (Domain Layer) |
|||
```csharp |
|||
// Define custom interface only when custom queries are needed |
|||
public interface IOrderRepository : IRepository<Order, Guid> |
|||
{ |
|||
Task<Order> FindByOrderNumberAsync(string orderNumber, bool includeDetails = false); |
|||
Task<List<Order>> GetListByCustomerAsync(Guid customerId, bool includeDetails = false); |
|||
} |
|||
``` |
|||
|
|||
### Repository Best Practices |
|||
- **One repository per aggregate root only** - Never create repositories for child entities |
|||
- Child entities must be accessed/modified only through their aggregate root |
|||
- Creating repositories for child entities breaks data consistency (bypasses aggregate root's business rules) |
|||
- In ABP, use `AddDefaultRepositories()` without `includeAllEntities: true` to enforce this |
|||
- Define custom repository only when custom queries are needed |
|||
- ABP handles `CancellationToken` automatically; add parameter only for explicit cancellation control |
|||
- Single entity methods: `includeDetails = true` by default |
|||
- List methods: `includeDetails = false` by default |
|||
- Don't return projection classes |
|||
- Interface in Domain, implementation in data layer |
|||
|
|||
```csharp |
|||
// ✅ Correct: Repository for aggregate root (Order) |
|||
public interface IOrderRepository : IRepository<Order, Guid> { } |
|||
|
|||
// ❌ Wrong: Repository for child entity (OrderLine) |
|||
// OrderLine should only be accessed through Order aggregate |
|||
public interface IOrderLineRepository : IRepository<OrderLine, Guid> { } // Don't do this! |
|||
``` |
|||
|
|||
## Domain Services |
|||
|
|||
Use domain services for business logic that: |
|||
- Spans multiple aggregates |
|||
- Requires repository queries to enforce rules |
|||
|
|||
```csharp |
|||
public class OrderManager : DomainService |
|||
{ |
|||
private readonly IOrderRepository _orderRepository; |
|||
private readonly IProductRepository _productRepository; |
|||
|
|||
public OrderManager( |
|||
IOrderRepository orderRepository, |
|||
IProductRepository productRepository) |
|||
{ |
|||
_orderRepository = orderRepository; |
|||
_productRepository = productRepository; |
|||
} |
|||
|
|||
public async Task<Order> CreateAsync(string orderNumber, Guid customerId) |
|||
{ |
|||
// Business rule: Order number must be unique |
|||
var existing = await _orderRepository.FindByOrderNumberAsync(orderNumber); |
|||
if (existing != null) |
|||
{ |
|||
throw new BusinessException("Orders:OrderNumberAlreadyExists") |
|||
.WithData("OrderNumber", orderNumber); |
|||
} |
|||
|
|||
return new Order(GuidGenerator.Create(), orderNumber, customerId); |
|||
} |
|||
|
|||
public async Task AddProductAsync(Order order, Guid productId, int count) |
|||
{ |
|||
var product = await _productRepository.GetAsync(productId); |
|||
order.AddLine(productId, count, product.Price); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### Domain Service Best Practices |
|||
- Use `*Manager` suffix naming |
|||
- No interface by default (create only if needed) |
|||
- Accept/return domain objects, not DTOs |
|||
- Don't depend on authenticated user - pass values from application layer |
|||
- Use base class properties (`GuidGenerator`, `Clock`) instead of injecting these services |
|||
|
|||
## Domain Events |
|||
|
|||
### Local Events |
|||
```csharp |
|||
// In aggregate |
|||
AddLocalEvent(new OrderCompletedEvent(Id)); |
|||
|
|||
// Handler |
|||
public class OrderCompletedEventHandler : ILocalEventHandler<OrderCompletedEvent>, ITransientDependency |
|||
{ |
|||
public async Task HandleEventAsync(OrderCompletedEvent eventData) |
|||
{ |
|||
// Handle within same transaction |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### Distributed Events (ETO) |
|||
For inter-module/microservice communication: |
|||
```csharp |
|||
// In Domain.Shared |
|||
[EventName("Orders.OrderCompleted")] |
|||
public class OrderCompletedEto |
|||
{ |
|||
public Guid OrderId { get; set; } |
|||
public string OrderNumber { get; set; } |
|||
} |
|||
``` |
|||
|
|||
## Specifications |
|||
|
|||
Reusable query conditions: |
|||
```csharp |
|||
public class CompletedOrdersSpec : Specification<Order> |
|||
{ |
|||
public override Expression<Func<Order, bool>> ToExpression() |
|||
{ |
|||
return o => o.Status == OrderStatus.Completed; |
|||
} |
|||
} |
|||
|
|||
// Usage |
|||
var orders = await _orderRepository.GetListAsync(new CompletedOrdersSpec()); |
|||
``` |
|||
@ -0,0 +1,153 @@ |
|||
--- |
|||
description: "ABP layer dependency rules and project structure guardrails" |
|||
globs: |
|||
- "**/*.csproj" |
|||
- "**/*Module*.cs" |
|||
alwaysApply: false |
|||
--- |
|||
|
|||
# ABP Dependency Rules |
|||
|
|||
## Core Principles (All Templates) |
|||
|
|||
These principles apply regardless of solution structure: |
|||
|
|||
1. **Domain logic never depends on infrastructure** (no DbContext in domain/application) |
|||
2. **Use abstractions** (interfaces) for dependencies |
|||
3. **Higher layers depend on lower layers**, never the reverse |
|||
4. **Data access through repositories**, not direct DbContext |
|||
|
|||
## Layered Template Structure |
|||
|
|||
> **Note**: This section applies to layered templates (app, module). Single-layer and microservice templates have different structures. |
|||
|
|||
``` |
|||
Domain.Shared → Constants, enums, localization keys |
|||
↑ |
|||
Domain → Entities, repository interfaces, domain services |
|||
↑ |
|||
Application.Contracts → App service interfaces, DTOs |
|||
↑ |
|||
Application → App service implementations |
|||
↑ |
|||
HttpApi → REST controllers (optional) |
|||
↑ |
|||
Host → Final application with DI and middleware |
|||
``` |
|||
|
|||
### Layered Dependency Direction |
|||
|
|||
| Project | Can Reference | Referenced By | |
|||
|---------|---------------|---------------| |
|||
| Domain.Shared | Nothing | All | |
|||
| Domain | Domain.Shared | Application, Data layer | |
|||
| Application.Contracts | Domain.Shared | Application, HttpApi, Clients | |
|||
| Application | Domain, Contracts | Host | |
|||
| EntityFrameworkCore/MongoDB | Domain | Host only | |
|||
| HttpApi | Contracts only | Host | |
|||
|
|||
## Critical Rules |
|||
|
|||
### ❌ Never Do |
|||
```csharp |
|||
// Application layer accessing DbContext directly |
|||
public class BookAppService : ApplicationService |
|||
{ |
|||
private readonly MyDbContext _dbContext; // ❌ WRONG |
|||
} |
|||
|
|||
// Domain depending on application layer |
|||
public class BookManager : DomainService |
|||
{ |
|||
private readonly IBookAppService _appService; // ❌ WRONG |
|||
} |
|||
|
|||
// HttpApi depending on Application implementation |
|||
public class BookController : AbpController |
|||
{ |
|||
private readonly BookAppService _bookAppService; // ❌ WRONG - Use interface |
|||
} |
|||
``` |
|||
|
|||
### ✅ Always Do |
|||
```csharp |
|||
// Application layer using repository abstraction |
|||
public class BookAppService : ApplicationService |
|||
{ |
|||
private readonly IBookRepository _bookRepository; // ✅ CORRECT |
|||
} |
|||
|
|||
// Domain service using domain abstractions |
|||
public class BookManager : DomainService |
|||
{ |
|||
private readonly IBookRepository _bookRepository; // ✅ CORRECT |
|||
} |
|||
|
|||
// HttpApi depending on contracts only |
|||
public class BookController : AbpController |
|||
{ |
|||
private readonly IBookAppService _bookAppService; // ✅ CORRECT |
|||
} |
|||
``` |
|||
|
|||
## Repository Pattern Enforcement |
|||
|
|||
### Interface Location |
|||
```csharp |
|||
// In Domain project |
|||
public interface IBookRepository : IRepository<Book, Guid> |
|||
{ |
|||
Task<Book> FindByNameAsync(string name); |
|||
} |
|||
``` |
|||
|
|||
### Implementation Location |
|||
```csharp |
|||
// In EntityFrameworkCore project |
|||
public class BookRepository : EfCoreRepository<MyDbContext, Book, Guid>, IBookRepository |
|||
{ |
|||
// Implementation |
|||
} |
|||
|
|||
// In MongoDB project |
|||
public class BookRepository : MongoDbRepository<MyDbContext, Book, Guid>, IBookRepository |
|||
{ |
|||
// Implementation |
|||
} |
|||
``` |
|||
|
|||
## Multi-Application Scenarios |
|||
|
|||
When you have multiple applications (e.g., Admin + Public API): |
|||
|
|||
### Vertical Separation |
|||
``` |
|||
MyProject.Admin.Application - Admin-specific services |
|||
MyProject.Public.Application - Public-specific services |
|||
MyProject.Domain - Shared domain (both reference this) |
|||
``` |
|||
|
|||
### Rules |
|||
- Admin and Public application layers **MUST NOT** reference each other |
|||
- Share domain logic, not application logic |
|||
- Each vertical can have its own DTOs even if similar |
|||
|
|||
## Enforcement Checklist (Layered Templates) |
|||
|
|||
When adding a new feature: |
|||
1. **Entity changes?** → Domain project |
|||
2. **Constants/enums?** → Domain.Shared project |
|||
3. **Repository interface?** → Domain project (only if custom queries needed) |
|||
4. **Repository implementation?** → EntityFrameworkCore/MongoDB project |
|||
5. **DTOs and service interface?** → Application.Contracts project |
|||
6. **Service implementation?** → Application project |
|||
7. **API endpoint?** → HttpApi project (if not using auto API controllers) |
|||
|
|||
## Common Violations to Watch |
|||
|
|||
| Violation | Impact | Fix | |
|||
|-----------|--------|-----| |
|||
| DbContext in Application | Breaks DB independence | Use repository | |
|||
| Entity in DTO | Exposes internals | Map to DTO | |
|||
| IQueryable in interface | Breaks abstraction | Return concrete types | |
|||
| Cross-module app service call | Tight coupling | Use events or domain | |
|||
@ -0,0 +1,299 @@ |
|||
--- |
|||
description: "ABP development workflow - adding features, entities, and migrations" |
|||
globs: |
|||
- "**/*AppService*.cs" |
|||
- "**/*Application*/**/*.cs" |
|||
- "**/*Application.Contracts*/**/*.cs" |
|||
- "**/*Dto*.cs" |
|||
- "**/*DbContext*.cs" |
|||
- "**/*.EntityFrameworkCore/**/*.cs" |
|||
- "**/*.MongoDB/**/*.cs" |
|||
- "**/*Permission*.cs" |
|||
alwaysApply: false |
|||
--- |
|||
|
|||
# ABP Development Workflow |
|||
|
|||
> **Tutorials**: https://abp.io/docs/latest/tutorials |
|||
|
|||
## Adding a New Entity (Full Flow) |
|||
|
|||
### 1. Domain Layer |
|||
Create entity (location varies by template: `*.Domain/Entities/` for layered, `Entities/` for single-layer/microservice): |
|||
|
|||
```csharp |
|||
public class Book : AggregateRoot<Guid> |
|||
{ |
|||
public string Name { get; private set; } |
|||
public decimal Price { get; private set; } |
|||
public Guid AuthorId { get; private set; } |
|||
|
|||
protected Book() { } |
|||
|
|||
public Book(Guid id, string name, decimal price, Guid authorId) : base(id) |
|||
{ |
|||
Name = Check.NotNullOrWhiteSpace(name, nameof(name)); |
|||
SetPrice(price); |
|||
AuthorId = authorId; |
|||
} |
|||
|
|||
public void SetPrice(decimal price) |
|||
{ |
|||
Price = Check.Range(price, nameof(price), 0, 9999); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### 2. Domain.Shared |
|||
Add constants and enums in `*.Domain.Shared/`: |
|||
|
|||
```csharp |
|||
public static class BookConsts |
|||
{ |
|||
public const int MaxNameLength = 128; |
|||
} |
|||
|
|||
public enum BookType |
|||
{ |
|||
Novel, |
|||
Science, |
|||
Biography |
|||
} |
|||
``` |
|||
|
|||
### 3. Repository Interface (Optional) |
|||
Define custom repository in `*.Domain/` only if you need custom query methods. For simple CRUD, use generic `IRepository<Book, Guid>` directly: |
|||
|
|||
```csharp |
|||
// Only if custom queries are needed |
|||
public interface IBookRepository : IRepository<Book, Guid> |
|||
{ |
|||
Task<Book> FindByNameAsync(string name); |
|||
} |
|||
``` |
|||
|
|||
### 4. EF Core Configuration |
|||
In `*.EntityFrameworkCore/`: |
|||
|
|||
**DbContext:** |
|||
```csharp |
|||
public DbSet<Book> Books { get; set; } |
|||
``` |
|||
|
|||
**OnModelCreating:** |
|||
```csharp |
|||
builder.Entity<Book>(b => |
|||
{ |
|||
b.ToTable(MyProjectConsts.DbTablePrefix + "Books", MyProjectConsts.DbSchema); |
|||
b.ConfigureByConvention(); |
|||
b.Property(x => x.Name).IsRequired().HasMaxLength(BookConsts.MaxNameLength); |
|||
b.HasIndex(x => x.Name); |
|||
}); |
|||
``` |
|||
|
|||
**Repository Implementation (only if custom interface defined):** |
|||
```csharp |
|||
public class BookRepository : EfCoreRepository<MyDbContext, Book, Guid>, IBookRepository |
|||
{ |
|||
public BookRepository(IDbContextProvider<MyDbContext> dbContextProvider) |
|||
: base(dbContextProvider) |
|||
{ |
|||
} |
|||
|
|||
public async Task<Book> FindByNameAsync(string name) |
|||
{ |
|||
return await (await GetDbSetAsync()) |
|||
.FirstOrDefaultAsync(b => b.Name == name); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### 5. Run Migration |
|||
```bash |
|||
cd src/MyProject.EntityFrameworkCore |
|||
|
|||
# Add migration |
|||
dotnet ef migrations add Added_Book |
|||
|
|||
# Apply migration (choose one): |
|||
dotnet run --project ../MyProject.DbMigrator # Recommended - also seeds data |
|||
# OR |
|||
dotnet ef database update # EF Core command only |
|||
``` |
|||
|
|||
### 6. Application.Contracts |
|||
Create DTOs and service interface: |
|||
|
|||
```csharp |
|||
// DTOs |
|||
public class BookDto : EntityDto<Guid> |
|||
{ |
|||
public string Name { get; set; } |
|||
public decimal Price { get; set; } |
|||
public Guid AuthorId { get; set; } |
|||
} |
|||
|
|||
public class CreateBookDto |
|||
{ |
|||
[Required] |
|||
[StringLength(BookConsts.MaxNameLength)] |
|||
public string Name { get; set; } |
|||
|
|||
[Range(0, 9999)] |
|||
public decimal Price { get; set; } |
|||
|
|||
[Required] |
|||
public Guid AuthorId { get; set; } |
|||
} |
|||
|
|||
// Service Interface |
|||
public interface IBookAppService : IApplicationService |
|||
{ |
|||
Task<BookDto> GetAsync(Guid id); |
|||
Task<PagedResultDto<BookDto>> GetListAsync(PagedAndSortedResultRequestDto input); |
|||
Task<BookDto> CreateAsync(CreateBookDto input); |
|||
} |
|||
``` |
|||
|
|||
### 7. Object Mapping (Mapperly / AutoMapper) |
|||
ABP supports both Mapperly and AutoMapper. Prefer the provider already used in the solution. |
|||
|
|||
If the solution uses **Mapperly**, create a mapper in the Application project: |
|||
|
|||
```csharp |
|||
[Mapper] |
|||
public partial class BookMapper |
|||
{ |
|||
public partial BookDto MapToDto(Book book); |
|||
public partial List<BookDto> MapToDtoList(List<Book> books); |
|||
} |
|||
``` |
|||
|
|||
Register in module: |
|||
```csharp |
|||
context.Services.AddSingleton<BookMapper>(); |
|||
``` |
|||
|
|||
### 8. Application Service |
|||
Implement service (using generic repository - use `IBookRepository` if you defined custom interface in step 3): |
|||
|
|||
```csharp |
|||
public class BookAppService : ApplicationService, IBookAppService |
|||
{ |
|||
private readonly IRepository<Book, Guid> _bookRepository; // Or IBookRepository |
|||
private readonly BookMapper _bookMapper; |
|||
|
|||
public BookAppService( |
|||
IRepository<Book, Guid> bookRepository, |
|||
BookMapper bookMapper) |
|||
{ |
|||
_bookRepository = bookRepository; |
|||
_bookMapper = bookMapper; |
|||
} |
|||
|
|||
public async Task<BookDto> GetAsync(Guid id) |
|||
{ |
|||
var book = await _bookRepository.GetAsync(id); |
|||
return _bookMapper.MapToDto(book); |
|||
} |
|||
|
|||
[Authorize(MyProjectPermissions.Books.Create)] |
|||
public async Task<BookDto> CreateAsync(CreateBookDto input) |
|||
{ |
|||
var book = new Book( |
|||
GuidGenerator.Create(), |
|||
input.Name, |
|||
input.Price, |
|||
input.AuthorId |
|||
); |
|||
|
|||
await _bookRepository.InsertAsync(book); |
|||
return _bookMapper.MapToDto(book); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### 9. Add Localization |
|||
In `*.Domain.Shared/Localization/*/en.json`: |
|||
|
|||
```json |
|||
{ |
|||
"Book": "Book", |
|||
"Books": "Books", |
|||
"BookName": "Name", |
|||
"BookPrice": "Price" |
|||
} |
|||
``` |
|||
|
|||
### 10. Add Permissions (if needed) |
|||
```csharp |
|||
public static class MyProjectPermissions |
|||
{ |
|||
public static class Books |
|||
{ |
|||
public const string Default = "MyProject.Books"; |
|||
public const string Create = Default + ".Create"; |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### 11. Add Tests |
|||
```csharp |
|||
public class BookAppService_Tests : MyProjectApplicationTestBase |
|||
{ |
|||
private readonly IBookAppService _bookAppService; |
|||
|
|||
public BookAppService_Tests() |
|||
{ |
|||
_bookAppService = GetRequiredService<IBookAppService>(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Create_Book() |
|||
{ |
|||
var result = await _bookAppService.CreateAsync(new CreateBookDto |
|||
{ |
|||
Name = "Test Book", |
|||
Price = 19.99m |
|||
}); |
|||
|
|||
result.Id.ShouldNotBe(Guid.Empty); |
|||
result.Name.ShouldBe("Test Book"); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Quick Reference Commands |
|||
|
|||
### Build Solution |
|||
```bash |
|||
dotnet build |
|||
``` |
|||
|
|||
### Run Migrations |
|||
```bash |
|||
cd src/MyProject.EntityFrameworkCore |
|||
dotnet ef migrations add MigrationName |
|||
dotnet run --project ../MyProject.DbMigrator # Apply migration + seed data |
|||
``` |
|||
|
|||
### Generate Angular Proxies |
|||
```bash |
|||
abp generate-proxy -t ng |
|||
``` |
|||
|
|||
## Checklist for New Features |
|||
|
|||
- [ ] Entity created with proper constructors |
|||
- [ ] Constants in Domain.Shared |
|||
- [ ] Custom repository interface in Domain (only if custom queries needed) |
|||
- [ ] EF Core configuration added |
|||
- [ ] Custom repository implementation (only if interface defined) |
|||
- [ ] Migration generated and applied (use DbMigrator) |
|||
- [ ] Mapperly mapper created and registered |
|||
- [ ] DTOs created in Application.Contracts |
|||
- [ ] Service interface defined |
|||
- [ ] Service implementation with authorization |
|||
- [ ] Localization keys added |
|||
- [ ] Permissions defined (if applicable) |
|||
- [ ] Tests written |
|||
@ -0,0 +1,249 @@ |
|||
--- |
|||
description: "ABP infrastructure services - Settings, Features, Caching, Events, Background Jobs" |
|||
globs: |
|||
- "**/*Setting*.cs" |
|||
- "**/*Feature*.cs" |
|||
- "**/*Cache*.cs" |
|||
- "**/*Event*.cs" |
|||
- "**/*Job*.cs" |
|||
alwaysApply: false |
|||
--- |
|||
|
|||
# ABP Infrastructure Services |
|||
|
|||
> **Docs**: https://abp.io/docs/latest/framework/infrastructure |
|||
|
|||
## Settings |
|||
|
|||
### Define Settings |
|||
```csharp |
|||
public class MySettingDefinitionProvider : SettingDefinitionProvider |
|||
{ |
|||
public override void Define(ISettingDefinitionContext context) |
|||
{ |
|||
context.Add( |
|||
new SettingDefinition("MyApp.MaxItemCount", "10"), |
|||
new SettingDefinition("MyApp.EnableFeature", "false"), |
|||
new SettingDefinition("MyApp.SecretKey", isEncrypted: true) |
|||
); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### Read Settings |
|||
```csharp |
|||
public class MyService : ITransientDependency |
|||
{ |
|||
private readonly ISettingProvider _settingProvider; |
|||
|
|||
public async Task DoSomethingAsync() |
|||
{ |
|||
var maxCount = await _settingProvider.GetAsync<int>("MyApp.MaxItemCount"); |
|||
var isEnabled = await _settingProvider.IsTrueAsync("MyApp.EnableFeature"); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### Setting Value Providers (Priority Order) |
|||
1. User settings (highest) |
|||
2. Tenant settings |
|||
3. Global settings |
|||
4. Configuration (appsettings.json) |
|||
5. Default value (lowest) |
|||
|
|||
## Features |
|||
|
|||
### Define Features |
|||
```csharp |
|||
public class MyFeatureDefinitionProvider : FeatureDefinitionProvider |
|||
{ |
|||
public override void Define(IFeatureDefinitionContext context) |
|||
{ |
|||
var myGroup = context.AddGroup("MyApp"); |
|||
|
|||
myGroup.AddFeature( |
|||
"MyApp.PdfReporting", |
|||
defaultValue: "false", |
|||
valueType: new ToggleStringValueType() |
|||
); |
|||
|
|||
myGroup.AddFeature( |
|||
"MyApp.MaxProductCount", |
|||
defaultValue: "10", |
|||
valueType: new FreeTextStringValueType(new NumericValueValidator(1, 1000)) |
|||
); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### Check Features |
|||
```csharp |
|||
[RequiresFeature("MyApp.PdfReporting")] |
|||
public async Task<PdfReportDto> GetPdfReportAsync() |
|||
{ |
|||
// Only executes if feature is enabled |
|||
} |
|||
|
|||
// Or programmatically |
|||
if (await _featureChecker.IsEnabledAsync("MyApp.PdfReporting")) |
|||
{ |
|||
// Feature is enabled for current tenant |
|||
} |
|||
|
|||
var maxCount = await _featureChecker.GetAsync<int>("MyApp.MaxProductCount"); |
|||
``` |
|||
|
|||
## Distributed Caching |
|||
|
|||
### Typed Cache |
|||
```csharp |
|||
public class BookService : ITransientDependency |
|||
{ |
|||
private readonly IDistributedCache<BookCacheItem> _cache; |
|||
private readonly IClock _clock; |
|||
|
|||
public BookService(IDistributedCache<BookCacheItem> cache, IClock clock) |
|||
{ |
|||
_cache = cache; |
|||
_clock = clock; |
|||
} |
|||
|
|||
public async Task<BookCacheItem> GetAsync(Guid bookId) |
|||
{ |
|||
return await _cache.GetOrAddAsync( |
|||
bookId.ToString(), |
|||
async () => await GetBookFromDatabaseAsync(bookId), |
|||
() => new DistributedCacheEntryOptions |
|||
{ |
|||
AbsoluteExpiration = _clock.Now.AddHours(1) |
|||
} |
|||
); |
|||
} |
|||
} |
|||
|
|||
[CacheName("Books")] |
|||
public class BookCacheItem |
|||
{ |
|||
public string Name { get; set; } |
|||
public decimal Price { get; set; } |
|||
} |
|||
``` |
|||
|
|||
## Event Bus |
|||
|
|||
### Local Events (Same Process) |
|||
```csharp |
|||
// Event class |
|||
public class OrderCreatedEvent |
|||
{ |
|||
public Order Order { get; set; } |
|||
} |
|||
|
|||
// Handler |
|||
public class OrderCreatedEventHandler : ILocalEventHandler<OrderCreatedEvent>, ITransientDependency |
|||
{ |
|||
public async Task HandleEventAsync(OrderCreatedEvent eventData) |
|||
{ |
|||
// Handle within same transaction |
|||
} |
|||
} |
|||
|
|||
// Publish |
|||
await _localEventBus.PublishAsync(new OrderCreatedEvent { Order = order }); |
|||
``` |
|||
|
|||
### Distributed Events (Cross-Service) |
|||
```csharp |
|||
// Event Transfer Object (in Domain.Shared) |
|||
[EventName("MyApp.Order.Created")] |
|||
public class OrderCreatedEto |
|||
{ |
|||
public Guid OrderId { get; set; } |
|||
public string OrderNumber { get; set; } |
|||
} |
|||
|
|||
// Handler |
|||
public class OrderCreatedEtoHandler : IDistributedEventHandler<OrderCreatedEto>, ITransientDependency |
|||
{ |
|||
public async Task HandleEventAsync(OrderCreatedEto eventData) |
|||
{ |
|||
// Handle distributed event |
|||
} |
|||
} |
|||
|
|||
// Publish |
|||
await _distributedEventBus.PublishAsync(new OrderCreatedEto { ... }); |
|||
``` |
|||
|
|||
### When to Use Which |
|||
- **Local**: Within same module/bounded context |
|||
- **Distributed**: Cross-module or microservice communication |
|||
|
|||
## Background Jobs |
|||
|
|||
### Define Job |
|||
```csharp |
|||
public class EmailSendingArgs |
|||
{ |
|||
public string EmailAddress { get; set; } |
|||
public string Subject { get; set; } |
|||
public string Body { get; set; } |
|||
} |
|||
|
|||
public class EmailSendingJob : AsyncBackgroundJob<EmailSendingArgs>, ITransientDependency |
|||
{ |
|||
private readonly IEmailSender _emailSender; |
|||
|
|||
public EmailSendingJob(IEmailSender emailSender) |
|||
{ |
|||
_emailSender = emailSender; |
|||
} |
|||
|
|||
public override async Task ExecuteAsync(EmailSendingArgs args) |
|||
{ |
|||
await _emailSender.SendAsync(args.EmailAddress, args.Subject, args.Body); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### Enqueue Job |
|||
```csharp |
|||
await _backgroundJobManager.EnqueueAsync( |
|||
new EmailSendingArgs |
|||
{ |
|||
EmailAddress = "user@example.com", |
|||
Subject = "Hello", |
|||
Body = "..." |
|||
}, |
|||
delay: TimeSpan.FromMinutes(5) // Optional delay |
|||
); |
|||
``` |
|||
|
|||
## Localization |
|||
|
|||
### Define Resource |
|||
```csharp |
|||
[LocalizationResourceName("MyModule")] |
|||
public class MyModuleResource { } |
|||
``` |
|||
|
|||
### JSON Structure |
|||
```json |
|||
{ |
|||
"culture": "en", |
|||
"texts": { |
|||
"HelloWorld": "Hello World!", |
|||
"Menu:Books": "Books" |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### Usage |
|||
- In `ApplicationService`: Use `L["Key"]` property (already available from base class) |
|||
- In other services: Inject `IStringLocalizer<MyResource>` |
|||
|
|||
> **Tip**: ABP base classes already provide commonly used services as properties. Check before injecting: |
|||
> - `StringLocalizer` (L), `Clock`, `CurrentUser`, `CurrentTenant`, `GuidGenerator` |
|||
> - `AuthorizationService`, `FeatureChecker`, `DataFilter` |
|||
> - `LoggerFactory`, `Logger` |
|||
> - Methods like `CheckPolicyAsync()` for authorization checks |
|||
@ -0,0 +1,165 @@ |
|||
--- |
|||
description: "ABP Multi-Tenancy patterns - tenant-aware entities, data isolation, and tenant switching" |
|||
globs: |
|||
- "**/*Tenant*.cs" |
|||
- "**/*MultiTenant*.cs" |
|||
- "**/Entities/**/*.cs" |
|||
alwaysApply: false |
|||
--- |
|||
|
|||
# ABP Multi-Tenancy |
|||
|
|||
> **Docs**: https://abp.io/docs/latest/framework/architecture/multi-tenancy |
|||
|
|||
## Making Entities Multi-Tenant |
|||
|
|||
Implement `IMultiTenant` interface to make entities tenant-aware: |
|||
|
|||
```csharp |
|||
public class Product : AggregateRoot<Guid>, IMultiTenant |
|||
{ |
|||
public Guid? TenantId { get; set; } // Required by IMultiTenant |
|||
|
|||
public string Name { get; private set; } |
|||
public decimal Price { get; private set; } |
|||
|
|||
protected Product() { } |
|||
|
|||
public Product(Guid id, string name, decimal price) : base(id) |
|||
{ |
|||
Name = name; |
|||
Price = price; |
|||
// TenantId is automatically set from CurrentTenant.Id |
|||
} |
|||
} |
|||
``` |
|||
|
|||
**Key points:** |
|||
- `TenantId` is **nullable** - `null` means entity belongs to Host |
|||
- ABP **automatically filters** queries by current tenant |
|||
- ABP **automatically sets** `TenantId` when creating entities |
|||
|
|||
## Accessing Current Tenant |
|||
|
|||
Use `CurrentTenant` property (available in base classes) or inject `ICurrentTenant`: |
|||
|
|||
```csharp |
|||
public class ProductAppService : ApplicationService |
|||
{ |
|||
public async Task DoSomethingAsync() |
|||
{ |
|||
// Available from base class |
|||
var tenantId = CurrentTenant.Id; // Guid? - null for host |
|||
var tenantName = CurrentTenant.Name; // string? |
|||
var isAvailable = CurrentTenant.IsAvailable; // true if Id is not null |
|||
} |
|||
} |
|||
|
|||
// In other services |
|||
public class MyService : ITransientDependency |
|||
{ |
|||
private readonly ICurrentTenant _currentTenant; |
|||
public MyService(ICurrentTenant currentTenant) => _currentTenant = currentTenant; |
|||
} |
|||
``` |
|||
|
|||
## Switching Tenant Context |
|||
|
|||
Use `CurrentTenant.Change()` to temporarily switch tenant (useful in host context): |
|||
|
|||
```csharp |
|||
public class ProductManager : DomainService |
|||
{ |
|||
private readonly IRepository<Product, Guid> _productRepository; |
|||
|
|||
public async Task<long> GetProductCountAsync(Guid? tenantId) |
|||
{ |
|||
// Switch to specific tenant |
|||
using (CurrentTenant.Change(tenantId)) |
|||
{ |
|||
return await _productRepository.GetCountAsync(); |
|||
} |
|||
// Automatically restored to previous tenant after using block |
|||
} |
|||
|
|||
public async Task DoHostOperationAsync() |
|||
{ |
|||
// Switch to host context |
|||
using (CurrentTenant.Change(null)) |
|||
{ |
|||
// Operations here are in host context |
|||
} |
|||
} |
|||
} |
|||
``` |
|||
|
|||
> **Important**: Always use `Change()` with a `using` statement. |
|||
|
|||
## Disabling Multi-Tenant Filter |
|||
|
|||
To query all tenants' data (only works with single database): |
|||
|
|||
```csharp |
|||
public class ProductManager : DomainService |
|||
{ |
|||
public async Task<long> GetAllProductCountAsync() |
|||
{ |
|||
// DataFilter is available from base class |
|||
using (DataFilter.Disable<IMultiTenant>()) |
|||
{ |
|||
return await _productRepository.GetCountAsync(); |
|||
// Returns count from ALL tenants |
|||
} |
|||
} |
|||
} |
|||
``` |
|||
|
|||
> **Note**: This doesn't work with separate databases per tenant. |
|||
|
|||
## Database Architecture Options |
|||
|
|||
| Approach | Description | Use Case | |
|||
|----------|-------------|----------| |
|||
| Single Database | All tenants share one database | Simple, cost-effective | |
|||
| Database per Tenant | Each tenant has dedicated database | Data isolation, compliance | |
|||
| Hybrid | Mix of shared and dedicated | Flexible, premium tenants | |
|||
|
|||
Connection strings are configured per tenant in Tenant Management module. |
|||
|
|||
## Best Practices |
|||
|
|||
1. **Always implement `IMultiTenant`** for tenant-specific entities |
|||
2. **Never manually filter by `TenantId`** - ABP does it automatically |
|||
3. **Don't change `TenantId` after creation** - it moves entity between tenants |
|||
4. **Use `Change()` scope carefully** - nested scopes are supported |
|||
5. **Test both host and tenant contexts** - ensure proper data isolation |
|||
6. **Consider nullable `TenantId`** - entity may be host-only or shared |
|||
|
|||
## Enabling Multi-Tenancy |
|||
|
|||
```csharp |
|||
Configure<AbpMultiTenancyOptions>(options => |
|||
{ |
|||
options.IsEnabled = true; // Enabled by default in ABP templates |
|||
}); |
|||
``` |
|||
|
|||
Check `MultiTenancyConsts.IsEnabled` in your solution for centralized control. |
|||
|
|||
## Tenant Resolution |
|||
|
|||
ABP resolves current tenant from (in order): |
|||
1. Current user's claims |
|||
2. Query string (`?__tenant=...`) |
|||
3. Route (`/{__tenant}/...`) |
|||
4. HTTP header (`__tenant`) |
|||
5. Cookie (`__tenant`) |
|||
6. Domain/subdomain (if configured) |
|||
|
|||
For subdomain-based resolution: |
|||
```csharp |
|||
Configure<AbpTenantResolveOptions>(options => |
|||
{ |
|||
options.AddDomainTenantResolver("{0}.mydomain.com"); |
|||
}); |
|||
``` |
|||
@ -0,0 +1,257 @@ |
|||
--- |
|||
description: "ABP Entity Framework Core patterns - DbContext, migrations, repositories" |
|||
globs: |
|||
- "**/*.EntityFrameworkCore/**/*.cs" |
|||
- "**/EntityFrameworkCore/**/*.cs" |
|||
- "**/*DbContext*.cs" |
|||
alwaysApply: false |
|||
--- |
|||
|
|||
# ABP Entity Framework Core |
|||
|
|||
> **Docs**: https://abp.io/docs/latest/framework/data/entity-framework-core |
|||
|
|||
## DbContext Configuration |
|||
|
|||
```csharp |
|||
[ConnectionStringName("Default")] |
|||
public class MyProjectDbContext : AbpDbContext<MyProjectDbContext> |
|||
{ |
|||
public DbSet<Book> Books { get; set; } |
|||
public DbSet<Author> Authors { get; set; } |
|||
|
|||
public MyProjectDbContext(DbContextOptions<MyProjectDbContext> options) |
|||
: base(options) |
|||
{ |
|||
} |
|||
|
|||
protected override void OnModelCreating(ModelBuilder builder) |
|||
{ |
|||
base.OnModelCreating(builder); |
|||
|
|||
// Configure all entities |
|||
builder.ConfigureMyProject(); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Entity Configuration |
|||
|
|||
```csharp |
|||
public static class MyProjectDbContextModelCreatingExtensions |
|||
{ |
|||
public static void ConfigureMyProject(this ModelBuilder builder) |
|||
{ |
|||
Check.NotNull(builder, nameof(builder)); |
|||
|
|||
builder.Entity<Book>(b => |
|||
{ |
|||
b.ToTable(MyProjectConsts.DbTablePrefix + "Books", MyProjectConsts.DbSchema); |
|||
b.ConfigureByConvention(); // ABP conventions (audit, soft-delete, etc.) |
|||
|
|||
// Property configurations |
|||
b.Property(x => x.Name) |
|||
.IsRequired() |
|||
.HasMaxLength(BookConsts.MaxNameLength); |
|||
|
|||
b.Property(x => x.Price) |
|||
.HasColumnType("decimal(18,2)"); |
|||
|
|||
// Indexes |
|||
b.HasIndex(x => x.Name); |
|||
|
|||
// Relationships |
|||
b.HasOne<Author>() |
|||
.WithMany() |
|||
.HasForeignKey(x => x.AuthorId) |
|||
.OnDelete(DeleteBehavior.Restrict); |
|||
}); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Repository Implementation |
|||
|
|||
```csharp |
|||
public class BookRepository : EfCoreRepository<MyProjectDbContext, Book, Guid>, IBookRepository |
|||
{ |
|||
public BookRepository(IDbContextProvider<MyProjectDbContext> dbContextProvider) |
|||
: base(dbContextProvider) |
|||
{ |
|||
} |
|||
|
|||
public async Task<Book> FindByNameAsync( |
|||
string name, |
|||
bool includeDetails = true, |
|||
CancellationToken cancellationToken = default) |
|||
{ |
|||
var dbSet = await GetDbSetAsync(); |
|||
|
|||
return await dbSet |
|||
.IncludeDetails(includeDetails) |
|||
.FirstOrDefaultAsync( |
|||
b => b.Name == name, |
|||
GetCancellationToken(cancellationToken)); |
|||
} |
|||
|
|||
public async Task<List<Book>> GetListByAuthorAsync( |
|||
Guid authorId, |
|||
bool includeDetails = false, |
|||
CancellationToken cancellationToken = default) |
|||
{ |
|||
var dbSet = await GetDbSetAsync(); |
|||
|
|||
return await dbSet |
|||
.IncludeDetails(includeDetails) |
|||
.Where(b => b.AuthorId == authorId) |
|||
.ToListAsync(GetCancellationToken(cancellationToken)); |
|||
} |
|||
|
|||
public override async Task<IQueryable<Book>> WithDetailsAsync() |
|||
{ |
|||
return (await GetQueryableAsync()) |
|||
.Include(b => b.Reviews); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Extension Method for Include |
|||
```csharp |
|||
public static class BookEfCoreQueryableExtensions |
|||
{ |
|||
public static IQueryable<Book> IncludeDetails( |
|||
this IQueryable<Book> queryable, |
|||
bool include = true) |
|||
{ |
|||
if (!include) |
|||
{ |
|||
return queryable; |
|||
} |
|||
|
|||
return queryable |
|||
.Include(b => b.Reviews); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Migration Commands |
|||
|
|||
```bash |
|||
# Navigate to EF Core project |
|||
cd src/MyProject.EntityFrameworkCore |
|||
|
|||
# Add migration |
|||
dotnet ef migrations add MigrationName |
|||
|
|||
# Apply migration (choose one): |
|||
dotnet run --project ../MyProject.DbMigrator # Recommended - also seeds data |
|||
dotnet ef database update # EF Core command only |
|||
|
|||
# Remove last migration (if not applied) |
|||
dotnet ef migrations remove |
|||
|
|||
# Generate SQL script |
|||
dotnet ef migrations script |
|||
``` |
|||
|
|||
> **Note**: ABP templates include `IDesignTimeDbContextFactory` in the EF Core project, so `-s` (startup project) parameter is not needed. |
|||
|
|||
## Module Configuration |
|||
|
|||
```csharp |
|||
[DependsOn(typeof(AbpEntityFrameworkCoreModule))] |
|||
public class MyProjectEntityFrameworkCoreModule : AbpModule |
|||
{ |
|||
public override void ConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
context.Services.AddAbpDbContext<MyProjectDbContext>(options => |
|||
{ |
|||
// Add default repositories for aggregate roots only (DDD best practice) |
|||
options.AddDefaultRepositories(); |
|||
// ⚠️ Avoid includeAllEntities: true - it creates repositories for child entities, |
|||
// allowing them to be modified without going through the aggregate root, |
|||
// which breaks data consistency |
|||
}); |
|||
|
|||
Configure<AbpDbContextOptions>(options => |
|||
{ |
|||
options.UseSqlServer(); // or UseNpgsql(), UseMySql(), etc. |
|||
}); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Best Practices |
|||
|
|||
### Repositories for Aggregate Roots Only |
|||
Don't use `includeAllEntities: true` in `AddDefaultRepositories()`. This creates repositories for child entities, allowing direct modification without going through the aggregate root - breaking DDD data consistency rules. |
|||
|
|||
```csharp |
|||
// ✅ Correct - Only aggregate roots get repositories |
|||
options.AddDefaultRepositories(); |
|||
|
|||
// ❌ Avoid - Creates repositories for ALL entities including child entities |
|||
options.AddDefaultRepositories(includeAllEntities: true); |
|||
``` |
|||
|
|||
### Always Call ConfigureByConvention |
|||
```csharp |
|||
builder.Entity<MyEntity>(b => |
|||
{ |
|||
b.ConfigureByConvention(); // Don't forget this! |
|||
// Other configurations... |
|||
}); |
|||
``` |
|||
|
|||
### Use Table Prefix |
|||
```csharp |
|||
public static class MyProjectConsts |
|||
{ |
|||
public const string DbTablePrefix = "App"; |
|||
public const string DbSchema = null; // Or "myschema" |
|||
} |
|||
``` |
|||
|
|||
### Performance Tips |
|||
- Add explicit indexes for frequently queried fields |
|||
- Use `AsNoTracking()` for read-only queries |
|||
- Avoid N+1 queries with `.Include()` or specifications |
|||
- ABP handles cancellation automatically; use `GetCancellationToken(cancellationToken)` only in custom repository methods |
|||
- Consider query splitting for complex queries with multiple collections |
|||
|
|||
### Accessing Raw DbContext |
|||
```csharp |
|||
public async Task CustomOperationAsync() |
|||
{ |
|||
var dbContext = await GetDbContextAsync(); |
|||
|
|||
// Raw SQL |
|||
await dbContext.Database.ExecuteSqlRawAsync( |
|||
"UPDATE Books SET IsPublished = 1 WHERE AuthorId = {0}", |
|||
authorId |
|||
); |
|||
} |
|||
``` |
|||
|
|||
## Data Seeding |
|||
|
|||
```csharp |
|||
public class MyProjectDataSeedContributor : IDataSeedContributor, ITransientDependency |
|||
{ |
|||
private readonly IRepository<Book, Guid> _bookRepository; |
|||
private readonly IGuidGenerator _guidGenerator; |
|||
|
|||
public async Task SeedAsync(DataSeedContext context) |
|||
{ |
|||
if (await _bookRepository.GetCountAsync() > 0) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
await _bookRepository.InsertAsync( |
|||
new Book(_guidGenerator.Create(), "Sample Book", 19.99m, Guid.Empty), |
|||
autoSave: true |
|||
); |
|||
} |
|||
} |
|||
``` |
|||
@ -0,0 +1,274 @@ |
|||
--- |
|||
description: "ABP testing patterns - unit tests and integration tests" |
|||
globs: |
|||
- "test/**/*.cs" |
|||
- "tests/**/*.cs" |
|||
- "**/*Tests*/**/*.cs" |
|||
- "**/*Test*.cs" |
|||
alwaysApply: false |
|||
--- |
|||
|
|||
# ABP Testing Patterns |
|||
|
|||
> **Docs**: https://abp.io/docs/latest/testing |
|||
|
|||
## Test Project Structure |
|||
|
|||
| Project | Purpose | Base Class | |
|||
|---------|---------|------------| |
|||
| `*.Domain.Tests` | Domain logic, entities, domain services | `*DomainTestBase` | |
|||
| `*.Application.Tests` | Application services | `*ApplicationTestBase` | |
|||
| `*.EntityFrameworkCore.Tests` | Repository implementations | `*EntityFrameworkCoreTestBase` | |
|||
|
|||
## Integration Test Approach |
|||
|
|||
ABP recommends integration tests over unit tests: |
|||
- Tests run with real services and database (SQLite in-memory) |
|||
- No mocking of internal services |
|||
- Each test gets a fresh database instance |
|||
|
|||
## Application Service Test |
|||
|
|||
```csharp |
|||
public class BookAppService_Tests : MyProjectApplicationTestBase |
|||
{ |
|||
private readonly IBookAppService _bookAppService; |
|||
|
|||
public BookAppService_Tests() |
|||
{ |
|||
_bookAppService = GetRequiredService<IBookAppService>(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Get_List_Of_Books() |
|||
{ |
|||
// Act |
|||
var result = await _bookAppService.GetListAsync( |
|||
new PagedAndSortedResultRequestDto() |
|||
); |
|||
|
|||
// Assert |
|||
result.TotalCount.ShouldBeGreaterThan(0); |
|||
result.Items.ShouldContain(b => b.Name == "Test Book"); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Create_Book() |
|||
{ |
|||
// Arrange |
|||
var input = new CreateBookDto |
|||
{ |
|||
Name = "New Book", |
|||
Price = 19.99m |
|||
}; |
|||
|
|||
// Act |
|||
var result = await _bookAppService.CreateAsync(input); |
|||
|
|||
// Assert |
|||
result.Id.ShouldNotBe(Guid.Empty); |
|||
result.Name.ShouldBe("New Book"); |
|||
result.Price.ShouldBe(19.99m); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Create_Book_With_Invalid_Name() |
|||
{ |
|||
// Arrange |
|||
var input = new CreateBookDto |
|||
{ |
|||
Name = "", // Invalid |
|||
Price = 10m |
|||
}; |
|||
|
|||
// Act & Assert |
|||
await Should.ThrowAsync<AbpValidationException>(async () => |
|||
{ |
|||
await _bookAppService.CreateAsync(input); |
|||
}); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Domain Service Test |
|||
|
|||
```csharp |
|||
public class BookManager_Tests : MyProjectDomainTestBase |
|||
{ |
|||
private readonly BookManager _bookManager; |
|||
private readonly IBookRepository _bookRepository; |
|||
|
|||
public BookManager_Tests() |
|||
{ |
|||
_bookManager = GetRequiredService<BookManager>(); |
|||
_bookRepository = GetRequiredService<IBookRepository>(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Create_Book() |
|||
{ |
|||
// Act |
|||
var book = await _bookManager.CreateAsync("Test Book", 29.99m); |
|||
|
|||
// Assert |
|||
book.ShouldNotBeNull(); |
|||
book.Name.ShouldBe("Test Book"); |
|||
book.Price.ShouldBe(29.99m); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Allow_Duplicate_Book_Name() |
|||
{ |
|||
// Arrange |
|||
await _bookManager.CreateAsync("Existing Book", 10m); |
|||
|
|||
// Act & Assert |
|||
var exception = await Should.ThrowAsync<BusinessException>(async () => |
|||
{ |
|||
await _bookManager.CreateAsync("Existing Book", 20m); |
|||
}); |
|||
|
|||
exception.Code.ShouldBe("MyProject:BookNameAlreadyExists"); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Test Naming Convention |
|||
|
|||
Use descriptive names: |
|||
```csharp |
|||
// Pattern: Should_ExpectedBehavior_When_Condition |
|||
public async Task Should_Create_Book_When_Input_Is_Valid() |
|||
public async Task Should_Throw_BusinessException_When_Name_Already_Exists() |
|||
public async Task Should_Return_Empty_List_When_No_Books_Exist() |
|||
``` |
|||
|
|||
## Arrange-Act-Assert (AAA) |
|||
|
|||
```csharp |
|||
[Fact] |
|||
public async Task Should_Update_Book_Price() |
|||
{ |
|||
// Arrange |
|||
var bookId = await CreateTestBookAsync(); |
|||
var newPrice = 39.99m; |
|||
|
|||
// Act |
|||
var result = await _bookAppService.UpdateAsync(bookId, new UpdateBookDto |
|||
{ |
|||
Price = newPrice |
|||
}); |
|||
|
|||
// Assert |
|||
result.Price.ShouldBe(newPrice); |
|||
} |
|||
``` |
|||
|
|||
## Assertions with Shouldly |
|||
|
|||
ABP uses Shouldly library: |
|||
```csharp |
|||
result.ShouldNotBeNull(); |
|||
result.Name.ShouldBe("Expected Name"); |
|||
result.Price.ShouldBeGreaterThan(0); |
|||
result.Items.ShouldContain(x => x.Id == expectedId); |
|||
result.Items.ShouldBeEmpty(); |
|||
result.Items.Count.ShouldBe(5); |
|||
|
|||
// Exception assertions |
|||
await Should.ThrowAsync<BusinessException>(async () => |
|||
{ |
|||
await _service.DoSomethingAsync(); |
|||
}); |
|||
|
|||
var ex = await Should.ThrowAsync<BusinessException>(async () => |
|||
{ |
|||
await _service.DoSomethingAsync(); |
|||
}); |
|||
ex.Code.ShouldBe("MyProject:ErrorCode"); |
|||
``` |
|||
|
|||
## Test Data Seeding |
|||
|
|||
```csharp |
|||
public class MyProjectTestDataSeedContributor : IDataSeedContributor, ITransientDependency |
|||
{ |
|||
public static readonly Guid TestBookId = Guid.Parse("..."); |
|||
|
|||
private readonly IBookRepository _bookRepository; |
|||
private readonly IGuidGenerator _guidGenerator; |
|||
|
|||
public async Task SeedAsync(DataSeedContext context) |
|||
{ |
|||
await _bookRepository.InsertAsync( |
|||
new Book(TestBookId, "Test Book", 19.99m, Guid.Empty), |
|||
autoSave: true |
|||
); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Disabling Authorization in Tests |
|||
|
|||
```csharp |
|||
public override void ConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
context.Services.AddAlwaysAllowAuthorization(); |
|||
} |
|||
``` |
|||
|
|||
## Mocking External Services |
|||
|
|||
Use NSubstitute when needed: |
|||
```csharp |
|||
public override void ConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
var emailSender = Substitute.For<IEmailSender>(); |
|||
emailSender.SendAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()) |
|||
.Returns(Task.CompletedTask); |
|||
|
|||
context.Services.AddSingleton(emailSender); |
|||
} |
|||
``` |
|||
|
|||
## Testing with Specific User |
|||
|
|||
```csharp |
|||
[Fact] |
|||
public async Task Should_Get_Current_User_Books() |
|||
{ |
|||
// Login as specific user |
|||
await WithUnitOfWorkAsync(async () => |
|||
{ |
|||
using (CurrentUser.Change(TestData.UserId)) |
|||
{ |
|||
var result = await _bookAppService.GetMyBooksAsync(); |
|||
result.Items.ShouldAllBe(b => b.CreatorId == TestData.UserId); |
|||
} |
|||
}); |
|||
} |
|||
``` |
|||
|
|||
## Testing Multi-Tenancy |
|||
|
|||
```csharp |
|||
[Fact] |
|||
public async Task Should_Filter_Books_By_Tenant() |
|||
{ |
|||
using (CurrentTenant.Change(TestData.TenantId)) |
|||
{ |
|||
var result = await _bookAppService.GetListAsync(new GetBookListDto()); |
|||
// Results should be filtered by tenant |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Best Practices |
|||
|
|||
- Each test should be independent |
|||
- Don't share state between tests |
|||
- Use meaningful test data |
|||
- Test edge cases and error conditions |
|||
- Keep tests focused on single behavior |
|||
- Use test data seeders for common data |
|||
- Avoid testing framework internals |
|||
@ -0,0 +1,262 @@ |
|||
--- |
|||
description: "ABP MVC and Razor Pages UI patterns" |
|||
globs: |
|||
- "**/*.cshtml" |
|||
- "**/Pages/**/*.cs" |
|||
- "**/Views/**/*.cs" |
|||
- "**/Controllers/**/*.cs" |
|||
alwaysApply: false |
|||
--- |
|||
|
|||
# ABP MVC / Razor Pages UI |
|||
|
|||
> **Docs**: https://abp.io/docs/latest/framework/ui/mvc-razor-pages/overall |
|||
|
|||
## Razor Page Model |
|||
```csharp |
|||
public class IndexModel : AbpPageModel |
|||
{ |
|||
private readonly IBookAppService _bookAppService; |
|||
|
|||
public List<BookDto> Books { get; set; } |
|||
|
|||
public IndexModel(IBookAppService bookAppService) |
|||
{ |
|||
_bookAppService = bookAppService; |
|||
} |
|||
|
|||
public async Task OnGetAsync() |
|||
{ |
|||
var result = await _bookAppService.GetListAsync( |
|||
new PagedAndSortedResultRequestDto() |
|||
); |
|||
Books = result.Items.ToList(); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Razor Page View |
|||
```html |
|||
@page |
|||
@model IndexModel |
|||
|
|||
<abp-card> |
|||
<abp-card-header> |
|||
<abp-row> |
|||
<abp-column size-md="_6"> |
|||
<h2>@L["Books"]</h2> |
|||
</abp-column> |
|||
<abp-column size-md="_6" class="text-end"> |
|||
<abp-button button-type="Primary" |
|||
id="NewBookButton" |
|||
text="@L["NewBook"].Value" /> |
|||
</abp-column> |
|||
</abp-row> |
|||
</abp-card-header> |
|||
<abp-card-body> |
|||
<abp-table striped-rows="true" id="BooksTable"> |
|||
<thead> |
|||
<tr> |
|||
<th>@L["Name"]</th> |
|||
<th>@L["Price"]</th> |
|||
<th>@L["Actions"]</th> |
|||
</tr> |
|||
</thead> |
|||
<tbody> |
|||
@foreach (var book in Model.Books) |
|||
{ |
|||
<tr> |
|||
<td>@book.Name</td> |
|||
<td>@book.Price</td> |
|||
<td> |
|||
<abp-button button-type="Primary" size="Small" |
|||
text="@L["Edit"].Value" /> |
|||
</td> |
|||
</tr> |
|||
} |
|||
</tbody> |
|||
</abp-table> |
|||
</abp-card-body> |
|||
</abp-card> |
|||
``` |
|||
|
|||
## ABP Tag Helpers |
|||
|
|||
### Cards |
|||
```html |
|||
<abp-card> |
|||
<abp-card-header>Header</abp-card-header> |
|||
<abp-card-body>Content</abp-card-body> |
|||
<abp-card-footer>Footer</abp-card-footer> |
|||
</abp-card> |
|||
``` |
|||
|
|||
### Buttons |
|||
```html |
|||
<abp-button button-type="Primary" text="@L["Save"].Value" /> |
|||
<abp-button button-type="Danger" icon="fa fa-trash" /> |
|||
``` |
|||
|
|||
### Forms |
|||
```html |
|||
<abp-dynamic-form abp-model="Book" asp-page="/Books/CreateModal"> |
|||
<abp-modal> |
|||
<abp-modal-header title="@L["NewBook"].Value" /> |
|||
<abp-modal-body> |
|||
<abp-form-content /> |
|||
</abp-modal-body> |
|||
<abp-modal-footer buttons="@(AbpModalButtons.Save | AbpModalButtons.Cancel)" /> |
|||
</abp-modal> |
|||
</abp-dynamic-form> |
|||
``` |
|||
|
|||
### Tables |
|||
```html |
|||
<abp-table striped-rows="true" hoverable-rows="true"> |
|||
<!-- content --> |
|||
</abp-table> |
|||
``` |
|||
|
|||
## Localization |
|||
```html |
|||
@* In Razor views/pages *@ |
|||
<h1>@L["Books"]</h1> |
|||
|
|||
@* With parameters *@ |
|||
<p>@L["WelcomeMessage", Model.UserName]</p> |
|||
``` |
|||
|
|||
## JavaScript API |
|||
```javascript |
|||
// Localization |
|||
var text = abp.localization.getResource('BookStore')('Books'); |
|||
|
|||
// Authorization |
|||
if (abp.auth.isGranted('BookStore.Books.Create')) { |
|||
// Show create button |
|||
} |
|||
|
|||
// Settings |
|||
var maxCount = abp.setting.get('BookStore.MaxItemCount'); |
|||
|
|||
// Ajax with automatic error handling |
|||
abp.ajax({ |
|||
url: '/api/app/book', |
|||
type: 'POST', |
|||
data: JSON.stringify(bookData) |
|||
}).then(function(result) { |
|||
// Success |
|||
}); |
|||
|
|||
// Notifications |
|||
abp.notify.success('Book created successfully!'); |
|||
abp.notify.error('An error occurred!'); |
|||
|
|||
// Confirmation |
|||
abp.message.confirm('Are you sure?').then(function(confirmed) { |
|||
if (confirmed) { |
|||
// User confirmed |
|||
} |
|||
}); |
|||
``` |
|||
|
|||
## DataTables Integration |
|||
```javascript |
|||
var dataTable = $('#BooksTable').DataTable( |
|||
abp.libs.datatables.normalizeConfiguration({ |
|||
serverSide: true, |
|||
paging: true, |
|||
ajax: abp.libs.datatables.createAjax(bookService.getList), |
|||
columnDefs: [ |
|||
{ |
|||
title: l('Name'), |
|||
data: 'name' |
|||
}, |
|||
{ |
|||
title: l('Price'), |
|||
data: 'price', |
|||
render: function(data) { |
|||
return data.toFixed(2); |
|||
} |
|||
}, |
|||
{ |
|||
title: l('Actions'), |
|||
rowAction: { |
|||
items: [ |
|||
{ |
|||
text: l('Edit'), |
|||
visible: abp.auth.isGranted('BookStore.Books.Edit'), |
|||
action: function(data) { |
|||
editModal.open({ id: data.record.id }); |
|||
} |
|||
}, |
|||
{ |
|||
text: l('Delete'), |
|||
visible: abp.auth.isGranted('BookStore.Books.Delete'), |
|||
confirmMessage: function(data) { |
|||
return l('BookDeletionConfirmationMessage', data.record.name); |
|||
}, |
|||
action: function(data) { |
|||
bookService.delete(data.record.id).then(function() { |
|||
abp.notify.success(l('SuccessfullyDeleted')); |
|||
dataTable.ajax.reload(); |
|||
}); |
|||
} |
|||
} |
|||
] |
|||
} |
|||
} |
|||
] |
|||
}) |
|||
); |
|||
``` |
|||
|
|||
## Modal Pages |
|||
**CreateModal.cshtml:** |
|||
```html |
|||
@page |
|||
@model CreateModalModel |
|||
|
|||
<abp-dynamic-form abp-model="Book" asp-page="/Books/CreateModal"> |
|||
<abp-modal> |
|||
<abp-modal-header title="@L["NewBook"].Value" /> |
|||
<abp-modal-body> |
|||
<abp-form-content /> |
|||
</abp-modal-body> |
|||
<abp-modal-footer buttons="@(AbpModalButtons.Save | AbpModalButtons.Cancel)" /> |
|||
</abp-modal> |
|||
</abp-dynamic-form> |
|||
``` |
|||
|
|||
**CreateModal.cshtml.cs:** |
|||
```csharp |
|||
public class CreateModalModel : AbpPageModel |
|||
{ |
|||
[BindProperty] |
|||
public CreateBookDto Book { get; set; } |
|||
|
|||
private readonly IBookAppService _bookAppService; |
|||
|
|||
public CreateModalModel(IBookAppService bookAppService) |
|||
{ |
|||
_bookAppService = bookAppService; |
|||
} |
|||
|
|||
public async Task<IActionResult> OnPostAsync() |
|||
{ |
|||
await _bookAppService.CreateAsync(Book); |
|||
return NoContent(); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
## Bundle & Minification |
|||
```csharp |
|||
Configure<AbpBundlingOptions>(options => |
|||
{ |
|||
options.StyleBundles.Configure( |
|||
StandardBundles.Styles.Global, |
|||
bundle => bundle.AddFiles("/styles/my-styles.css") |
|||
); |
|||
}); |
|||
``` |
|||
@ -0,0 +1,119 @@ |
|||
--- |
|||
description: Guide for AI to effectively use ABP Studio MCP tools - workflows, best practices, and tool reference |
|||
alwaysApply: true |
|||
--- |
|||
|
|||
# ABP Studio MCP Tools - AI Usage Guide |
|||
|
|||
ABP Studio exposes 14 MCP tools through the `abp mcp-studio` bridge. They let you monitor the running applications, drive the Solution Runner and explore the solution structure. |
|||
|
|||
ABP Studio must be running. The monitoring tools work on their own, the build and solution tools need an open solution, and the application, container and task tools also need a selected run profile. |
|||
|
|||
## Tool Categories at a Glance |
|||
|
|||
| Category | Purpose | Tools | |
|||
|---|---|---| |
|||
| Monitoring | Observe running apps (logs, errors, requests, events) | `get_logs`, `get_exceptions`, `get_requests`, `get_events` | |
|||
| Applications | Start and stop applications | `start_applications`, `stop_applications` | |
|||
| Containers | Start and stop Docker containers | `start_containers`, `stop_containers` | |
|||
| Build | Compile and prepare the solution | `dotnet_build`, `install_libs` | |
|||
| Tasks | Run a configured task | `run_task` | |
|||
| Solution Structure | Explore the solution, modules and packages | `get_solution_info`, `list_modules`, `list_packages` | |
|||
|
|||
--- |
|||
|
|||
## Workflows |
|||
|
|||
### 1. Understanding a Solution (Start Here) |
|||
|
|||
Always begin with discovery before taking action: |
|||
|
|||
``` |
|||
get_solution_info -- solution name, path, template, module count, selected run profile |
|||
-> list_modules -- see all modules |
|||
-> list_packages -- see packages/projects, optionally filtered by module |
|||
``` |
|||
|
|||
### 2. Running Applications |
|||
|
|||
``` |
|||
start_applications -- apps: ["<application-name>"], or folder: "Backend/API", or root: true |
|||
stop_applications -- same targeting options |
|||
``` |
|||
|
|||
`start_applications` also restarts: an application that is already running is stopped and started again, so use it after a code change too. |
|||
|
|||
Do not call the monitoring tools right after starting an application. Use them when the user reports a problem or asks what is happening. |
|||
|
|||
### 3. Infrastructure (Docker Containers) |
|||
|
|||
``` |
|||
start_containers -- containers: ["<container-name>"], or omit to start all |
|||
stop_containers -- containers: [...], or omit to stop all |
|||
``` |
|||
|
|||
Containers are typically infrastructure dependencies (databases, Redis, RabbitMQ). Start them before starting applications. |
|||
|
|||
### 4. Building |
|||
|
|||
``` |
|||
dotnet_build -- root: true, or modules: [...], or packages: [...] |
|||
install_libs -- when wwwroot/libs is missing client-side packages |
|||
``` |
|||
|
|||
### 5. Running Tasks |
|||
|
|||
Tasks are one-shot operations (database migrations, seed data, npm install, etc.): |
|||
|
|||
``` |
|||
run_task -- task: "Migrate Database", timeout_seconds: 300 |
|||
``` |
|||
|
|||
Task names come from the run profile and can contain spaces. They are matched in full, ignoring case only. |
|||
|
|||
--- |
|||
|
|||
## Best Practices |
|||
|
|||
### Discover Before Acting |
|||
|
|||
Call `get_solution_info` first. It returns the selected run profile, which most Solution Runner operations depend on. It does not list the applications, containers or tasks of that profile, so ask the user for the exact name when you don't have it, or read the run profile in ABP Studio. |
|||
|
|||
### Target Applications Explicitly |
|||
|
|||
`start_applications` and `stop_applications` take `apps` (an array of names), `folder` (everything under a folder) or `root: true` (everything from the root). `root` does not affect containers, use the container tools for those. |
|||
|
|||
### Respect Timeouts |
|||
|
|||
`run_task` accepts `timeout_seconds` (default: 300). Increase it for long operations. On timeout the call returns, but the task keeps running in the background. |
|||
|
|||
### Filter Monitor Data |
|||
|
|||
All monitor tools accept `app` to filter by application and `last` to limit the number of entries. `get_logs` also accepts `level`, and `get_requests` accepts `status` and `urlContains`. When debugging a specific service, always filter by app name to reduce noise. |
|||
|
|||
--- |
|||
|
|||
## Quick Reference: Common Scenarios |
|||
|
|||
| User Says | Tool Sequence | |
|||
|---|---| |
|||
| "What does this solution look like?" | `get_solution_info` -> `list_modules` -> `list_packages` | |
|||
| "Start the application" | `get_solution_info` -> `start_applications` | |
|||
| "Start infrastructure" | `start_containers` | |
|||
| "What errors are happening?" | `get_exceptions` | |
|||
| "Check application logs" | `get_logs` with `app` and optionally `level: "Error"` | |
|||
| "Show me the API calls" | `get_requests` | |
|||
| "Build and restart" | `dotnet_build` -> `start_applications` | |
|||
| "Run database migration" | `run_task` | |
|||
|
|||
--- |
|||
|
|||
## Error Handling |
|||
|
|||
A response is flagged with `isError: true` only when its text starts with `Error:`. A failed build or a failed task comes back as a normal response, so always read the text instead of relying on the flag. Common error patterns: |
|||
|
|||
- **"No solution is open"** -- The user needs to open a solution in ABP Studio first |
|||
- **"No run profile selected"** -- The user needs to select a run profile in ABP Studio |
|||
- **"Applications not found"** / **"Containers not found"** -- The name is wrong, ask the user for the exact one |
|||
- **"Build FAILED."** -- Read the build output in the response, it is not flagged as an error |
|||
- **"Timed out"** -- Increase `timeout_seconds` or check if the operation is stuck |
|||
@ -0,0 +1,200 @@ |
|||
--- |
|||
description: "ABP Layered (DDD) application template specific patterns" |
|||
globs: |
|||
- "**/*.Domain/**/*.cs" |
|||
- "**/*.Application/**/*.cs" |
|||
- "**/*.EntityFrameworkCore/**/*.cs" |
|||
- "**/*.HttpApi/**/*.cs" |
|||
alwaysApply: true |
|||
--- |
|||
|
|||
# ABP Layered Application Template |
|||
|
|||
> **Docs**: https://abp.io/docs/latest/solution-templates/layered-web-application |
|||
|
|||
This template follows **Domain-Driven Design (DDD)** principles with strict layer separation. |
|||
|
|||
## Solution Structure |
|||
|
|||
``` |
|||
MyProject/ |
|||
├── src/ |
|||
│ ├── Bench.Domain.Shared/ # Constants, enums, localization, ETOs |
|||
│ ├── Bench.Domain/ # Entities, repository interfaces, domain services |
|||
│ ├── Bench.Application.Contracts/ # DTOs, service interfaces |
|||
│ ├── Bench.Application/ # Application service implementations |
|||
│ ├── Bench.EntityFrameworkCore/ # EF Core DbContext, repository implementations |
|||
│ ├── Bench.HttpApi/ # REST API controllers (optional) |
|||
│ ├── Bench.HttpApi.Client/ # Client proxies for remote calls |
|||
│ ├── Bench.Web/ # MVC/Razor Pages UI |
|||
│ └── Bench.DbMigrator/ # Database migration console app |
|||
``` |
|||
|
|||
## Layer Responsibilities |
|||
|
|||
| Layer | Responsibility | References | |
|||
|-------|---------------|------------| |
|||
| **Domain.Shared** | Constants, enums, localization keys, ETOs | Nothing | |
|||
| **Domain** | Entities, aggregate roots, domain services, repository interfaces | Domain.Shared | |
|||
| **Application.Contracts** | DTOs, service interfaces | Domain.Shared | |
|||
| **Application** | Use case orchestration, mapping | Domain, Application.Contracts | |
|||
| **EntityFrameworkCore** | DbContext, repository implementations, migrations | Domain | |
|||
| **HttpApi** | REST controllers (if not using Auto API) | Application.Contracts | |
|||
| **Web** | MVC/Razor Pages UI components | Application.Contracts | |
|||
| **DbMigrator** | Database migration + seeding console app | EntityFrameworkCore | |
|||
|
|||
## Key Differences from Other Templates |
|||
|
|||
| Layered (This) | Single-Layer | Microservice | |
|||
|---------------|--------------|--------------| |
|||
| Strict DDD layers | Single project | Single project per service | |
|||
| DTOs in Application.Contracts | DTOs in Services folder | DTOs in Contracts project | |
|||
| Custom repository interfaces in Domain | Generic repositories only | Generic repositories only | |
|||
| Multiple module classes | Single module class | Single module class per service | |
|||
| DbMigrator project | Migration in host | Migration per service | |
|||
|
|||
## Adding a New Feature |
|||
|
|||
### 1. Entity in Domain |
|||
```csharp |
|||
public class Book : AuditedAggregateRoot<Guid> |
|||
{ |
|||
public string Name { get; private set; } |
|||
public decimal Price { get; private set; } |
|||
|
|||
protected Book() { } // For ORM |
|||
|
|||
public Book(Guid id, string name, decimal price) : base(id) |
|||
{ |
|||
SetName(name); |
|||
SetPrice(price); |
|||
} |
|||
|
|||
public void SetName(string name) |
|||
{ |
|||
Name = Check.NotNullOrWhiteSpace(name, nameof(name), maxLength: BookConsts.MaxNameLength); |
|||
} |
|||
|
|||
public void SetPrice(decimal price) |
|||
{ |
|||
Price = Check.Range(price, nameof(price), 0, 9999); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### 2. Constants in Domain.Shared |
|||
```csharp |
|||
public static class BookConsts |
|||
{ |
|||
public const int MaxNameLength = 128; |
|||
} |
|||
``` |
|||
|
|||
### 3. Repository Interface in Domain (if custom queries needed) |
|||
```csharp |
|||
public interface IBookRepository : IRepository<Book, Guid> |
|||
{ |
|||
Task<Book> FindByNameAsync(string name); |
|||
} |
|||
``` |
|||
|
|||
### 4. DTOs in Application.Contracts |
|||
```csharp |
|||
public class BookDto : EntityDto<Guid> |
|||
{ |
|||
public string Name { get; set; } |
|||
public decimal Price { get; set; } |
|||
} |
|||
|
|||
public class CreateBookDto |
|||
{ |
|||
[Required] |
|||
[StringLength(BookConsts.MaxNameLength)] |
|||
public string Name { get; set; } |
|||
|
|||
[Range(0, 9999)] |
|||
public decimal Price { get; set; } |
|||
} |
|||
``` |
|||
|
|||
### 5. Service Interface in Application.Contracts |
|||
```csharp |
|||
public interface IBookAppService : IApplicationService |
|||
{ |
|||
Task<BookDto> GetAsync(Guid id); |
|||
Task<PagedResultDto<BookDto>> GetListAsync(PagedAndSortedResultRequestDto input); |
|||
Task<BookDto> CreateAsync(CreateBookDto input); |
|||
} |
|||
``` |
|||
|
|||
### 6. Service Implementation in Application |
|||
```csharp |
|||
public class BookAppService : ApplicationService, IBookAppService |
|||
{ |
|||
private readonly IRepository<Book, Guid> _bookRepository; |
|||
private readonly BookMapper _bookMapper; |
|||
|
|||
public BookAppService(IRepository<Book, Guid> bookRepository, BookMapper bookMapper) |
|||
{ |
|||
_bookRepository = bookRepository; |
|||
_bookMapper = bookMapper; |
|||
} |
|||
|
|||
public async Task<BookDto> GetAsync(Guid id) |
|||
{ |
|||
var book = await _bookRepository.GetAsync(id); |
|||
return _bookMapper.MapToDto(book); |
|||
} |
|||
|
|||
[Authorize(MyProjectPermissions.Books.Create)] |
|||
public async Task<BookDto> CreateAsync(CreateBookDto input) |
|||
{ |
|||
var book = new Book(GuidGenerator.Create(), input.Name, input.Price); |
|||
await _bookRepository.InsertAsync(book); |
|||
return _bookMapper.MapToDto(book); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### 7. DbContext Configuration in EntityFrameworkCore |
|||
```csharp |
|||
public DbSet<Book> Books { get; set; } |
|||
|
|||
// In OnModelCreating |
|||
builder.Entity<Book>(b => |
|||
{ |
|||
b.ToTable(MyProjectConsts.DbTablePrefix + "Books", MyProjectConsts.DbSchema); |
|||
b.ConfigureByConvention(); |
|||
b.Property(x => x.Name).IsRequired().HasMaxLength(BookConsts.MaxNameLength); |
|||
}); |
|||
``` |
|||
|
|||
### 8. Run DbMigrator |
|||
```bash |
|||
cd src/Bench.EntityFrameworkCore |
|||
dotnet ef migrations add Added_Book |
|||
|
|||
cd ../Bench.DbMigrator |
|||
dotnet run |
|||
``` |
|||
|
|||
## DbMigrator |
|||
|
|||
Console application for: |
|||
- Applying database migrations |
|||
- Seeding initial data (admin user, permissions, etc.) |
|||
|
|||
Run before first launch: |
|||
```bash |
|||
dotnet run --project src/Bench.DbMigrator |
|||
``` |
|||
|
|||
## Best Practices |
|||
|
|||
1. **Respect layer boundaries** - Never referenceEntityFrameworkCorefrom Application |
|||
2. **Rich domain model** - Encapsulate business logic in entities |
|||
3. **Repository per aggregate** - One repository per aggregate root only |
|||
4. **DTOs at boundaries** - Never expose entities outside Application layer |
|||
5. **Use DbMigrator** - For consistent database setup across environments |
|||
6. **Auto API Controllers** - Let ABP generate controllers from app services |
|||
7. **Mapperly for mapping** - Use compile-time mapper for performance |
|||
@ -0,0 +1,2 @@ |
|||
[*.csproj] |
|||
indent_size = 2 |
|||
@ -0,0 +1 @@ |
|||
**/wwwroot/libs/** linguist-vendored |
|||
@ -0,0 +1,284 @@ |
|||
## Ignore Visual Studio temporary files, build results, and |
|||
## files generated by popular Visual Studio add-ons. |
|||
|
|||
# User-specific files |
|||
*.suo |
|||
*.user |
|||
*.userosscache |
|||
*.sln.docstates |
|||
|
|||
# User-specific files (MonoDevelop/Xamarin Studio) |
|||
*.userprefs |
|||
|
|||
# Build results |
|||
[Dd]ebug/ |
|||
[Dd]ebugPublic/ |
|||
[Rr]elease/ |
|||
[Rr]eleases/ |
|||
x64/ |
|||
x86/ |
|||
bld/ |
|||
[Bb]in/ |
|||
[Oo]bj/ |
|||
[Ll]og/ |
|||
|
|||
# Visual Studio 2015 cache/options directory |
|||
.vs/ |
|||
# Uncomment if you have tasks that create the project's static files in wwwroot |
|||
#wwwroot/ |
|||
|
|||
# MSTest test Results |
|||
[Tt]est[Rr]esult*/ |
|||
[Bb]uild[Ll]og.* |
|||
|
|||
# NUNIT |
|||
*.VisualState.xml |
|||
TestResult.xml |
|||
|
|||
# Build Results of an ATL Project |
|||
[Dd]ebugPS/ |
|||
[Rr]eleasePS/ |
|||
dlldata.c |
|||
|
|||
# DNX |
|||
project.lock.json |
|||
artifacts/ |
|||
|
|||
*_i.c |
|||
*_p.c |
|||
*_i.h |
|||
*.ilk |
|||
*.meta |
|||
*.obj |
|||
*.pch |
|||
*.pdb |
|||
*.pgc |
|||
*.pgd |
|||
*.rsp |
|||
*.sbr |
|||
*.tlb |
|||
*.tli |
|||
*.tlh |
|||
*.tmp |
|||
*.tmp_proj |
|||
*.log |
|||
*.vspscc |
|||
*.vssscc |
|||
.builds |
|||
*.pidb |
|||
*.svclog |
|||
*.scc |
|||
|
|||
# Chutzpah Test files |
|||
_Chutzpah* |
|||
|
|||
# Visual C++ cache files |
|||
ipch/ |
|||
*.aps |
|||
*.ncb |
|||
*.opendb |
|||
*.opensdf |
|||
*.sdf |
|||
*.cachefile |
|||
*.VC.db |
|||
*.VC.VC.opendb |
|||
|
|||
# Visual Studio profiler |
|||
*.psess |
|||
*.vsp |
|||
*.vspx |
|||
*.sap |
|||
|
|||
# TFS 2012 Local Workspace |
|||
$tf/ |
|||
|
|||
# Guidance Automation Toolkit |
|||
*.gpState |
|||
|
|||
# ReSharper is a .NET coding add-in |
|||
_ReSharper*/ |
|||
*.[Rr]e[Ss]harper |
|||
*.DotSettings.user |
|||
|
|||
# JustCode is a .NET coding add-in |
|||
.JustCode |
|||
|
|||
# TeamCity is a build add-in |
|||
_TeamCity* |
|||
|
|||
# DotCover is a Code Coverage Tool |
|||
*.dotCover |
|||
|
|||
# NCrunch |
|||
_NCrunch_* |
|||
.*crunch*.local.xml |
|||
nCrunchTemp_* |
|||
|
|||
# MightyMoose |
|||
*.mm.* |
|||
AutoTest.Net/ |
|||
|
|||
# Web workbench (sass) |
|||
.sass-cache/ |
|||
|
|||
# Installshield output folder |
|||
[Ee]xpress/ |
|||
|
|||
# DocProject is a documentation generator add-in |
|||
DocProject/buildhelp/ |
|||
DocProject/Help/*.HxT |
|||
DocProject/Help/*.HxC |
|||
DocProject/Help/*.hhc |
|||
DocProject/Help/*.hhk |
|||
DocProject/Help/*.hhp |
|||
DocProject/Help/Html2 |
|||
DocProject/Help/html |
|||
|
|||
# Click-Once directory |
|||
publish/ |
|||
|
|||
# Publish Web Output |
|||
*.[Pp]ublish.xml |
|||
*.azurePubxml |
|||
# TODO: Comment the next line if you want to checkin your web deploy settings |
|||
# but database connection strings (with potential passwords) will be unencrypted |
|||
*.pubxml |
|||
*.publishproj |
|||
|
|||
# Microsoft Azure Web App publish settings. Comment the next line if you want to |
|||
# checkin your Azure Web App publish settings, but sensitive information contained |
|||
# in these scripts will be unencrypted |
|||
PublishScripts/ |
|||
|
|||
# NuGet Packages |
|||
*.nupkg |
|||
# The packages folder can be ignored because of Package Restore |
|||
**/packages/* |
|||
# except build/, which is used as an MSBuild target. |
|||
!**/packages/build/ |
|||
# Uncomment if necessary however generally it will be regenerated when needed |
|||
#!**/packages/repositories.config |
|||
# NuGet v3's project.json files produces more ignoreable files |
|||
*.nuget.props |
|||
*.nuget.targets |
|||
|
|||
# Microsoft Azure Build Output |
|||
csx/ |
|||
*.build.csdef |
|||
|
|||
# Microsoft Azure Emulator |
|||
ecf/ |
|||
rcf/ |
|||
|
|||
# Windows Store app package directories and files |
|||
AppPackages/ |
|||
BundleArtifacts/ |
|||
Package.StoreAssociation.xml |
|||
_pkginfo.txt |
|||
|
|||
# Visual Studio cache files |
|||
# files ending in .cache can be ignored |
|||
*.[Cc]ache |
|||
# but keep track of directories ending in .cache |
|||
!*.[Cc]ache/ |
|||
|
|||
# Others |
|||
ClientBin/ |
|||
~$* |
|||
*~ |
|||
*.dbmdl |
|||
*.dbproj.schemaview |
|||
*.pfx |
|||
*.publishsettings |
|||
node_modules/ |
|||
orleans.codegen.cs |
|||
|
|||
# Since there are multiple workflows, uncomment next line to ignore bower_components |
|||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) |
|||
#bower_components/ |
|||
|
|||
# RIA/Silverlight projects |
|||
Generated_Code/ |
|||
|
|||
# Backup & report files from converting an old project file |
|||
# to a newer Visual Studio version. Backup files are not needed, |
|||
# because we have git ;-) |
|||
_UpgradeReport_Files/ |
|||
Backup*/ |
|||
UpgradeLog*.XML |
|||
UpgradeLog*.htm |
|||
|
|||
# SQL Server files |
|||
*.mdf |
|||
*.ldf |
|||
|
|||
# Business Intelligence projects |
|||
*.rdl.data |
|||
*.bim.layout |
|||
*.bim_*.settings |
|||
|
|||
# Microsoft Fakes |
|||
FakesAssemblies/ |
|||
|
|||
# GhostDoc plugin setting file |
|||
*.GhostDoc.xml |
|||
|
|||
# Node.js Tools for Visual Studio |
|||
.ntvs_analysis.dat |
|||
|
|||
# Visual Studio 6 build log |
|||
*.plg |
|||
|
|||
# Visual Studio 6 workspace options file |
|||
*.opt |
|||
|
|||
# Visual Studio LightSwitch build output |
|||
**/*.HTMLClient/GeneratedArtifacts |
|||
**/*.DesktopClient/GeneratedArtifacts |
|||
**/*.DesktopClient/ModelManifest.xml |
|||
**/*.Server/GeneratedArtifacts |
|||
**/*.Server/ModelManifest.xml |
|||
_Pvt_Extensions |
|||
|
|||
# Paket dependency manager |
|||
.paket/paket.exe |
|||
paket-files/ |
|||
|
|||
# FAKE - F# Make |
|||
.fake/ |
|||
|
|||
# JetBrains Rider |
|||
**/.idea/ |
|||
*.sln.iml |
|||
|
|||
# ABP Studio |
|||
**/.abpstudio/ |
|||
**/.abpstudio/test-catalog.json |
|||
**/*.abppkg.analyze.json |
|||
|
|||
# VS Code files for those working on multiple tools |
|||
.vscode/* |
|||
!.vscode/settings.json |
|||
!.vscode/tasks.json |
|||
!.vscode/launch.json |
|||
!.vscode/extensions.json |
|||
*.code-workspace |
|||
|
|||
# Bench |
|||
src/Bench.Web/Logs/* |
|||
src/Bench.Web.Host/Logs/* |
|||
src/Bench.Web.Public/Logs/* |
|||
src/Bench.Web.Public.Host/Logs/* |
|||
src/Bench.AuthServer/Logs/* |
|||
src/Bench.HttpApi.Host/Logs/* |
|||
src/Bench.HttpApi.HostWithIds/Logs/* |
|||
src/Bench.DbMigrator/Logs/* |
|||
src/Bench.Blazor.Server/Logs/* |
|||
src/Bench.Blazor.Server.Tiered/Logs/* |
|||
|
|||
# Use abp install-libs to restore. |
|||
**/wwwroot/libs/* |
|||
|
|||
# IdentityServer temp files |
|||
tempkey.rsa |
|||
tempkey.jwk |
|||
@ -0,0 +1,93 @@ |
|||
{ |
|||
"template": "app", |
|||
"imports": { |
|||
"Volo.Abp.LeptonXLiteTheme": { |
|||
"version": "5.7.0", |
|||
"isInstalled": true, |
|||
"creationTime": "11/05/2026 08:11:40 +00:00" |
|||
}, |
|||
"Volo.Abp.Account": { |
|||
"version": "10.7.1", |
|||
"isInstalled": true, |
|||
"creationTime": "11/05/2026 08:11:40 +00:00" |
|||
}, |
|||
"Volo.Abp.OpenIddict": { |
|||
"version": "10.7.1", |
|||
"isInstalled": true, |
|||
"creationTime": "11/05/2026 08:11:40 +00:00" |
|||
}, |
|||
"Volo.Abp.Identity": { |
|||
"version": "10.7.1", |
|||
"isInstalled": true, |
|||
"creationTime": "11/05/2026 08:11:40 +00:00" |
|||
}, |
|||
"Volo.Abp.TenantManagement": { |
|||
"version": "10.7.1", |
|||
"isInstalled": true, |
|||
"creationTime": "11/05/2026 08:11:40 +00:00" |
|||
}, |
|||
"Volo.Abp.SettingManagement": { |
|||
"version": "10.7.1", |
|||
"isInstalled": true, |
|||
"creationTime": "11/05/2026 08:11:40 +00:00" |
|||
}, |
|||
"Volo.Abp.PermissionManagement": { |
|||
"version": "10.7.1", |
|||
"isInstalled": true, |
|||
"creationTime": "11/05/2026 08:11:40 +00:00" |
|||
}, |
|||
"Volo.Abp.FeatureManagement": { |
|||
"version": "10.7.1", |
|||
"isInstalled": true, |
|||
"creationTime": "11/05/2026 08:11:40 +00:00" |
|||
}, |
|||
"Volo.Abp.BlobStoring.Database": { |
|||
"version": "10.7.1", |
|||
"isInstalled": true, |
|||
"creationTime": "11/05/2026 08:11:40 +00:00" |
|||
} |
|||
}, |
|||
"folders": { |
|||
"items": { |
|||
"src": {} |
|||
} |
|||
}, |
|||
"packages": { |
|||
"Bench.Application": { |
|||
"path": "src/Bench.Application/Bench.Application.abppkg", |
|||
"folder": "src" |
|||
}, |
|||
"Bench.Domain.Shared": { |
|||
"path": "src/Bench.Domain.Shared/Bench.Domain.Shared.abppkg", |
|||
"folder": "src" |
|||
}, |
|||
"Bench.Application.Contracts": { |
|||
"path": "src/Bench.Application.Contracts/Bench.Application.Contracts.abppkg", |
|||
"folder": "src" |
|||
}, |
|||
"Bench.HttpApi": { |
|||
"path": "src/Bench.HttpApi/Bench.HttpApi.abppkg", |
|||
"folder": "src" |
|||
}, |
|||
"Bench.HttpApi.Client": { |
|||
"path": "src/Bench.HttpApi.Client/Bench.HttpApi.Client.abppkg", |
|||
"folder": "src" |
|||
}, |
|||
"Bench.Web": { |
|||
"path": "src/Bench.Web/Bench.Web.abppkg", |
|||
"folder": "src" |
|||
}, |
|||
"Bench.EntityFrameworkCore": { |
|||
"path": "src/Bench.EntityFrameworkCore/Bench.EntityFrameworkCore.abppkg", |
|||
"folder": "src" |
|||
}, |
|||
"Bench.DbMigrator": { |
|||
"path": "src/Bench.DbMigrator/Bench.DbMigrator.abppkg", |
|||
"folder": "src" |
|||
}, |
|||
"Bench.Domain": { |
|||
"path": "src/Bench.Domain/Bench.Domain.abppkg", |
|||
"folder": "src" |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,77 @@ |
|||
{ |
|||
"id": "5a4903e8-f92d-415f-8b00-92c05972c9fe", |
|||
"creationTime": "11/05/2026 08:11:40 +00:00", |
|||
"template": "app", |
|||
"versions": { |
|||
"AbpFramework": "10.7.1", |
|||
"AbpStudio": "3.1.6", |
|||
"TargetDotnetFramework": "net10.0", |
|||
"AbpCommercial": "10.7.1", |
|||
"LeptonX": "5.7.0" |
|||
}, |
|||
"modules": { |
|||
"Bench": { |
|||
"path": "Bench.abpmdl" |
|||
} |
|||
}, |
|||
"runProfiles": { |
|||
"Default": { |
|||
"path": "etc/abp-studio/run-profiles/Default.abprun.json" |
|||
} |
|||
}, |
|||
"options": { |
|||
"httpRequests": { |
|||
"ignoredUrls": [] |
|||
} |
|||
}, |
|||
"creatingStudioConfiguration": { |
|||
"template": "app", |
|||
"createdAbpStudioVersion": "3.1.6", |
|||
"creationTool": "ABP Studio CLI", |
|||
"tiered": "false", |
|||
"runInstallLibs": "", |
|||
"useLocalReferences": "false", |
|||
"multiTenancy": "true", |
|||
"includeTests": "false", |
|||
"kubernetesConfiguration": "false", |
|||
"uiFramework": "mvc", |
|||
"mobileFramework": "none", |
|||
"distributedEventBus": "none", |
|||
"databaseProvider": "ef", |
|||
"runDbMigrator": "", |
|||
"databaseManagementSystem": "postgresql", |
|||
"separateTenantSchema": "false", |
|||
"createInitialMigration": "", |
|||
"theme": "leptonx-lite", |
|||
"themeStyle": "", |
|||
"themeMenuPlacement": "", |
|||
"publicWebsite": "false", |
|||
"socialLogin": "true", |
|||
"sampleCrudPage": "false", |
|||
"selectedLanguages": [ |
|||
"English", |
|||
"Arabic", |
|||
"Chinese (Simplified)", |
|||
"Chinese (Traditional)", |
|||
"Czech", |
|||
"English (UK)", |
|||
"Finnish", |
|||
"French", |
|||
"German (Germany)", |
|||
"Hindi ", |
|||
"Hungarian", |
|||
"Icelandic", |
|||
"Italian", |
|||
"Korean", |
|||
"Portuguese (Brazil)", |
|||
"Romanian (Romania)", |
|||
"Russian", |
|||
"Slovak", |
|||
"Spanish", |
|||
"Swedish", |
|||
"Turkish" |
|||
], |
|||
"defaultLanguage": "English", |
|||
"createCommand": "abp new Bench -t app --ui-framework mvc --database-provider ef --database-management-system postgresql --theme leptonx-lite --skip-migration --skip-migrator --no-tests --without-cms-kit --dont-run-install-libs --dont-run-bundling --use-open-source-template" |
|||
} |
|||
} |
|||
@ -0,0 +1,16 @@ |
|||
<Solution> |
|||
<Configurations> |
|||
<Platform Name="Any CPU" /> |
|||
</Configurations> |
|||
<Folder Name="/src/"> |
|||
<Project Path="src/Bench.Domain/Bench.Domain.csproj" /> |
|||
<Project Path="src/Bench.Application/Bench.Application.csproj" /> |
|||
<Project Path="src/Bench.EntityFrameworkCore/Bench.EntityFrameworkCore.csproj" /> |
|||
<Project Path="src/Bench.Web/Bench.Web.csproj" /> |
|||
<Project Path="src/Bench.Domain.Shared/Bench.Domain.Shared.csproj" /> |
|||
<Project Path="src/Bench.Application.Contracts/Bench.Application.Contracts.csproj" /> |
|||
<Project Path="src/Bench.HttpApi/Bench.HttpApi.csproj" /> |
|||
<Project Path="src/Bench.HttpApi.Client/Bench.HttpApi.Client.csproj" /> |
|||
<Project Path="src/Bench.DbMigrator/Bench.DbMigrator.csproj" /> |
|||
</Folder> |
|||
</Solution> |
|||
@ -0,0 +1,23 @@ |
|||
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> |
|||
<s:Boolean x:Key="/Default/CodeEditing/Intellisense/CodeCompletion/IntelliSenseCompletingCharacters/CSharpCompletingCharacters/UpgradedFromVSSettings/@EntryValue">True</s:Boolean> |
|||
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=EnforceDoWhileStatementBraces/@EntryIndexedValue">WARNING</s:String> |
|||
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=EnforceFixedStatementBraces/@EntryIndexedValue">WARNING</s:String> |
|||
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=EnforceForeachStatementBraces/@EntryIndexedValue">WARNING</s:String> |
|||
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=EnforceForStatementBraces/@EntryIndexedValue">WARNING</s:String> |
|||
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=EnforceIfStatementBraces/@EntryIndexedValue">WARNING</s:String> |
|||
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=EnforceLockStatementBraces/@EntryIndexedValue">WARNING</s:String> |
|||
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=EnforceUsingStatementBraces/@EntryIndexedValue">WARNING</s:String> |
|||
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=EnforceWhileStatementBraces/@EntryIndexedValue">WARNING</s:String> |
|||
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_FOR/@EntryValue">Required</s:String> |
|||
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_FOREACH/@EntryValue">Required</s:String> |
|||
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_IFELSE/@EntryValue">Required</s:String> |
|||
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_WHILE/@EntryValue">Required</s:String> |
|||
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_REDUNDANT/@EntryValue">False</s:Boolean> |
|||
<s:Boolean x:Key="/Default/CodeStyle/Generate/=Implementations/@KeyIndexDefined">True</s:Boolean> |
|||
<s:String x:Key="/Default/CodeStyle/Generate/=Implementations/Options/=Async/@EntryIndexedValue">False</s:String> |
|||
<s:String x:Key="/Default/CodeStyle/Generate/=Implementations/Options/=Mutable/@EntryIndexedValue">False</s:String> |
|||
<s:Boolean x:Key="/Default/CodeStyle/Generate/=Overrides/@KeyIndexDefined">True</s:Boolean> |
|||
<s:String x:Key="/Default/CodeStyle/Generate/=Overrides/Options/=Async/@EntryIndexedValue">False</s:String> |
|||
<s:String x:Key="/Default/CodeStyle/Generate/=Overrides/Options/=Mutable/@EntryIndexedValue">False</s:String> |
|||
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SQL/@EntryIndexedValue">SQL</s:String> |
|||
</wpf:ResourceDictionary> |
|||
@ -0,0 +1,13 @@ |
|||
<?xml version="1.0" encoding="utf-8"?> |
|||
<configuration> |
|||
<packageSources> |
|||
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" /> |
|||
</packageSources> |
|||
<packageSourceMapping> |
|||
<packageSource key="nuget.org"> |
|||
<package pattern="*" /> |
|||
<package pattern="Microsoft.*" /> |
|||
<package pattern="Volo.*" /> |
|||
</packageSource> |
|||
</packageSourceMapping> |
|||
</configuration> |
|||
@ -0,0 +1,60 @@ |
|||
# Bench |
|||
|
|||
## About this solution |
|||
|
|||
This is a layered startup solution based on [Domain Driven Design (DDD)](https://abp.io/docs/latest/framework/architecture/domain-driven-design) practises. All the fundamental ABP modules are already installed. Check the [Application Startup Template](https://abp.io/docs/latest/solution-templates/layered-web-application) documentation for more info. |
|||
|
|||
### Pre-requirements |
|||
|
|||
* [.NET10.0+ SDK](https://dotnet.microsoft.com/download/dotnet) |
|||
* [Node v18 or 20](https://nodejs.org/en) |
|||
|
|||
### Configurations |
|||
|
|||
The solution comes with a default configuration that works out of the box. However, you may consider to change the following configuration before running your solution: |
|||
|
|||
* Check the `ConnectionStrings` in `appsettings.json` files under the `Bench.Web` and `Bench.DbMigrator` projects and change it if you need. |
|||
|
|||
### Before running the application |
|||
|
|||
* Run `abp install-libs` command on your solution folder to install client-side package dependencies. This step is automatically done when you create a new solution, if you didn't especially disabled it. However, you should run it yourself if you have first cloned this solution from your source control, or added a new client-side package dependency to your solution. |
|||
* Run `Bench.DbMigrator` to create the initial database. This step is also automatically done when you create a new solution, if you didn't especially disabled it. This should be done in the first run. It is also needed if a new database migration is added to the solution later. |
|||
|
|||
#### Generating a Signing Certificate |
|||
|
|||
In the production environment, you need to use a production signing certificate. ABP Framework sets up signing and encryption certificates in your application and expects an `openiddict.pfx` file in your application. |
|||
|
|||
To generate a signing certificate, you can use the following command: |
|||
|
|||
```bash |
|||
dotnet dev-certs https -v -ep openiddict.pfx -p 9b3fcdc9-9e29-4862-96c7-18239226ee42 |
|||
``` |
|||
|
|||
> `9b3fcdc9-9e29-4862-96c7-18239226ee42` is the password of the certificate, you can change it to any password you want. |
|||
|
|||
It is recommended to use **two** RSA certificates, distinct from the certificate(s) used for HTTPS: one for encryption, one for signing. |
|||
|
|||
For more information, please refer to: [OpenIddict Certificate Configuration](https://documentation.openiddict.com/configuration/encryption-and-signing-credentials.html#registering-a-certificate-recommended-for-production-ready-scenarios) |
|||
|
|||
> Also, see the [Configuring OpenIddict](https://abp.io/docs/latest/Deployment/Configuring-OpenIddict#production-environment) documentation for more information. |
|||
|
|||
### Solution structure |
|||
|
|||
This is a layered monolith application that consists of the following applications: |
|||
|
|||
* `Bench.DbMigrator`: A console application which applies the migrations and also seeds the initial data. It is useful on development as well as on production environment. |
|||
* `Bench.Web`: ASP.NET Core MVC / Razor Pages application that is the essential web application of the solution. |
|||
|
|||
|
|||
|
|||
|
|||
## Deploying the application |
|||
|
|||
Deploying an ABP application follows the same process as deploying any .NET or ASP.NET Core application. However, there are important considerations to keep in mind. For detailed guidance, refer to ABP's [deployment documentation](https://abp.io/docs/latest/Deployment/Index). |
|||
|
|||
### Additional resources |
|||
|
|||
You can see the following resources to learn more about your solution and the ABP Framework: |
|||
|
|||
* [Web Application Development Tutorial](https://abp.io/docs/latest/tutorials/book-store/part-1) |
|||
* [Application Startup Template](https://abp.io/docs/latest/startup-templates/application/index) |
|||
@ -0,0 +1,22 @@ |
|||
<Project> |
|||
<PropertyGroup> |
|||
<LangVersion>latest</LangVersion> |
|||
<Version>1.0.0</Version> |
|||
<NoWarn>$(NoWarn);CS1591</NoWarn> |
|||
<NuGetAudit>false</NuGetAudit> |
|||
<AbpProjectType>app</AbpProjectType> |
|||
</PropertyGroup> |
|||
|
|||
<Target Name="NoWarnOnRazorViewImportedTypeConflicts" BeforeTargets="RazorCoreCompile"> |
|||
<PropertyGroup> |
|||
<NoWarn>$(NoWarn);0436</NoWarn> |
|||
</PropertyGroup> |
|||
</Target> |
|||
|
|||
<ItemGroup> |
|||
<None Remove="**\*.abppkg" /> |
|||
<None Remove="**\*.abppkg.analyze.json" /> |
|||
<Content Remove="$(UserProfile)\.nuget\packages\*\*\contentFiles\any\*\*.abppkg*" /> |
|||
</ItemGroup> |
|||
|
|||
</Project> |
|||
@ -0,0 +1,85 @@ |
|||
{ |
|||
"applications": { |
|||
"Bench.Web": { |
|||
"type": "dotnet-project", |
|||
"launchUrl": "https://localhost:44377", |
|||
"path": "../../../src/Bench.Web/Bench.Web.csproj", |
|||
"kubernetesService": ".*-web$", |
|||
"healthCheckEndpoint": "/health-status", |
|||
"healthUiEndpoint": "/health-ui", |
|||
"execution": { |
|||
"order": 2 |
|||
} |
|||
} |
|||
}, |
|||
"containers": { |
|||
"serviceName": "Bench-Containers", |
|||
}, |
|||
"tasks":{ |
|||
"Initialize Solution":{ |
|||
"behaviour": 2, |
|||
"startCommand": "./initialize-solution.ps1", |
|||
"workingDirectory": "../../scripts", |
|||
"shortDescription": "Prepares the solution for development." |
|||
}, |
|||
"Migrate Database":{ |
|||
"behaviour": 0, |
|||
"startCommand": "./migrate-database.ps1", |
|||
"workingDirectory": "../../scripts", |
|||
"shortDescription": "Migrates the database to the latest version." |
|||
} |
|||
}, |
|||
"workflows": { |
|||
"d3b2a1c4-e5f6-4890-abcd-ef1234567890": { |
|||
"Id": "d3b2a1c4-e5f6-4890-abcd-ef1234567890", |
|||
"Name": "Default", |
|||
"Description": "Stops applications, builds, migrates, and starts applications", |
|||
"IsShared": true, |
|||
"BeforeTasks": [], |
|||
"AfterTasks": [ |
|||
{ |
|||
"ActionType": "Build", |
|||
"Targets": [], |
|||
"AllTargets": true, |
|||
"ModuleTargets": [], |
|||
"PackageTargets": [], |
|||
"FolderTargets": [], |
|||
"ApplicationTargets": [], |
|||
"ContainerTargets": [] |
|||
}, |
|||
{ |
|||
"ActionType": "AddMigration", |
|||
"Targets": [], |
|||
"AllTargets": false, |
|||
"ModuleTargets": [], |
|||
"PackageTargets": [], |
|||
"FolderTargets": [], |
|||
"ApplicationTargets": [], |
|||
"ContainerTargets": [] |
|||
}, |
|||
{ |
|||
"ActionType": "RunTask", |
|||
"Targets": [ |
|||
"Migrate Database" |
|||
], |
|||
"AllTargets": false, |
|||
"ModuleTargets": [], |
|||
"PackageTargets": [], |
|||
"FolderTargets": [], |
|||
"ApplicationTargets": [], |
|||
"ContainerTargets": [] |
|||
}, |
|||
{ |
|||
"ActionType": "StartApplication", |
|||
"Targets": [], |
|||
"AllTargets": true, |
|||
"ModuleTargets": [], |
|||
"PackageTargets": [], |
|||
"FolderTargets": [], |
|||
"ApplicationTargets": [], |
|||
"ContainerTargets": [] |
|||
} |
|||
] |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,89 @@ |
|||
$ErrorActionPreference = "Stop" |
|||
$scriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path |
|||
$solutionRoot = Join-Path $scriptRoot "../../" |
|||
|
|||
function Write-StudioStep([string]$Message) { |
|||
[Console]::Out.WriteLine("[STUDIO:STEP] $Message") |
|||
[Console]::Out.Flush() |
|||
} |
|||
|
|||
Write-StudioStep "Building solution" |
|||
Set-Location $solutionRoot |
|||
dotnet build |
|||
|
|||
if ($LASTEXITCODE -ne 0) { |
|||
[Console]::Error.WriteLine("dotnet build FAILED with exit code $LASTEXITCODE") |
|||
exit -1 |
|||
} |
|||
|
|||
$jobs = @() |
|||
|
|||
Write-StudioStep "Installing client-side libraries" |
|||
$jobs += Start-Job -Name "InstallLibs" -ScriptBlock { |
|||
$ErrorActionPreference = "Stop" |
|||
Set-Location (Join-Path $using:scriptRoot "../../") |
|||
abp install-libs |
|||
|
|||
if ($LASTEXITCODE -ne 0) { |
|||
throw "abp install-libs exited with code $LASTEXITCODE" |
|||
} |
|||
} |
|||
|
|||
$jobs += Start-Job -Name "DbMigrator" -ScriptBlock { |
|||
$ErrorActionPreference = "Stop" |
|||
$migratorDir = Join-Path $using:scriptRoot "../../src/Bench.DbMigrator" |
|||
$efProjectDir = Join-Path $using:scriptRoot "../../src/Bench.EntityFrameworkCore" |
|||
# The CLI creates the migration and then runs the migrator. Do not start another |
|||
# dotnet run until that process exits; a parallel run can seed before AbpSettings exists. |
|||
if (-not (Test-Path (Join-Path $efProjectDir "Migrations"))) { |
|||
& abp create-migration-and-run-migrator $efProjectDir |
|||
} |
|||
else { |
|||
Set-Location $migratorDir |
|||
dotnet run |
|||
} |
|||
|
|||
if ($LASTEXITCODE -ne 0) { |
|||
throw "DbMigrator exited with code $LASTEXITCODE" |
|||
} |
|||
} |
|||
|
|||
Write-StudioStep "Creating development certificate" |
|||
$jobs += Start-Job -Name "DevCert" -ScriptBlock { |
|||
$ErrorActionPreference = "Stop" |
|||
Set-Location (Join-Path $using:scriptRoot "../../src/Bench.Web") |
|||
dotnet dev-certs https -v -ep openiddict.pfx -p 9b3fcdc9-9e29-4862-96c7-18239226ee42 |
|||
|
|||
if ($LASTEXITCODE -ne 0) { |
|||
throw "dotnet dev-certs exited with code $LASTEXITCODE" |
|||
} |
|||
} |
|||
|
|||
|
|||
Write-StudioStep "Waiting for initialization jobs" |
|||
while (($jobs | Where-Object { $_.State -eq 'Running' }).Count -gt 0) { |
|||
$running = ($jobs | Where-Object { $_.State -eq 'Running' } | ForEach-Object { $_.Name }) -join ', ' |
|||
if (-not [string]::IsNullOrWhiteSpace($running)) { |
|||
Write-StudioStep "Running: $running" |
|||
} |
|||
Start-Sleep -Seconds 2 |
|||
} |
|||
|
|||
Wait-Job $jobs | Out-Null |
|||
# Native tools can write warnings to stderr; keep them visible without failing completed jobs. |
|||
$jobs | Receive-Job -ErrorAction Continue |
|||
|
|||
$failed = $jobs | Where-Object { $_.State -eq 'Failed' } |
|||
$hasError = $failed.Count -gt 0 |
|||
|
|||
if ($hasError) { |
|||
foreach ($job in $failed) { |
|||
[Console]::Error.WriteLine("Job '$($job.Name)' FAILED") |
|||
} |
|||
|
|||
Remove-Job $jobs | Out-Null |
|||
exit -1 |
|||
} |
|||
|
|||
Remove-Job $jobs | Out-Null |
|||
exit 0 |
|||
@ -0,0 +1,32 @@ |
|||
$scriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path |
|||
|
|||
$jobs = @() |
|||
|
|||
$jobs += Start-Job -Name "DbMigrator" -ScriptBlock { |
|||
$ErrorActionPreference = "Stop" |
|||
Set-Location (Join-Path $using:scriptRoot "../../src/Bench.DbMigrator") |
|||
dotnet run |
|||
|
|||
if ($LASTEXITCODE -ne 0) { |
|||
throw "dotnet run (DbMigrator) exited with code $LASTEXITCODE" |
|||
} |
|||
} |
|||
|
|||
Wait-Job $jobs | Out-Null |
|||
# Native tools can write warnings to stderr; keep them visible without failing completed jobs. |
|||
$jobs | Receive-Job -ErrorAction Continue |
|||
|
|||
$failed = $jobs | Where-Object { $_.State -eq 'Failed' } |
|||
$hasError = $failed.Count -gt 0 |
|||
|
|||
if ($hasError) { |
|||
foreach ($job in $failed) { |
|||
[Console]::Error.WriteLine("Job '$($job.Name)' FAILED") |
|||
} |
|||
|
|||
Remove-Job $jobs | Out-Null |
|||
exit -1 |
|||
} |
|||
|
|||
Remove-Job $jobs | Out-Null |
|||
exit 0 |
|||
@ -0,0 +1,6 @@ |
|||
{ |
|||
"sdk": { |
|||
"version": "10.0.402", |
|||
"rollForward": "disable" |
|||
} |
|||
} |
|||
@ -0,0 +1,4 @@ |
|||
{ |
|||
"role": "lib.application-contracts", |
|||
"projectId": "532547a1-2a72-473f-8299-62aae8d19c47" |
|||
} |
|||
@ -0,0 +1,24 @@ |
|||
<Project Sdk="Microsoft.NET.Sdk"> |
|||
|
|||
<Import Project="..\..\common.props" /> |
|||
|
|||
<PropertyGroup> |
|||
<TargetFramework>net10.0</TargetFramework> |
|||
<Nullable>enable</Nullable> |
|||
<RootNamespace>Bench</RootNamespace> |
|||
</PropertyGroup> |
|||
|
|||
<ItemGroup> |
|||
<ProjectReference Include="..\Bench.Domain.Shared\Bench.Domain.Shared.csproj" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Volo.Abp.PermissionManagement.Application.Contracts" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.FeatureManagement.Application.Contracts" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.SettingManagement.Application.Contracts" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.Identity.Application.Contracts" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.Account.Application.Contracts" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.TenantManagement.Application.Contracts" Version="10.7.1" /> |
|||
</ItemGroup> |
|||
|
|||
</Project> |
|||
@ -0,0 +1,26 @@ |
|||
using Volo.Abp.Account; |
|||
using Volo.Abp.Modularity; |
|||
using Volo.Abp.PermissionManagement; |
|||
using Volo.Abp.SettingManagement; |
|||
using Volo.Abp.FeatureManagement; |
|||
using Volo.Abp.Identity; |
|||
using Volo.Abp.TenantManagement; |
|||
|
|||
namespace Bench; |
|||
|
|||
[DependsOn( |
|||
typeof(BenchDomainSharedModule), |
|||
typeof(AbpFeatureManagementApplicationContractsModule), |
|||
typeof(AbpSettingManagementApplicationContractsModule), |
|||
typeof(AbpIdentityApplicationContractsModule), |
|||
typeof(AbpAccountApplicationContractsModule), |
|||
typeof(AbpTenantManagementApplicationContractsModule), |
|||
typeof(AbpPermissionManagementApplicationContractsModule) |
|||
)] |
|||
public class BenchApplicationContractsModule : AbpModule |
|||
{ |
|||
public override void PreConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
BenchDtoExtensions.Configure(); |
|||
} |
|||
} |
|||
@ -0,0 +1,28 @@ |
|||
using Volo.Abp.Identity; |
|||
using Volo.Abp.ObjectExtending; |
|||
using Volo.Abp.Threading; |
|||
|
|||
namespace Bench; |
|||
|
|||
public static class BenchDtoExtensions |
|||
{ |
|||
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); |
|||
|
|||
public static void Configure() |
|||
{ |
|||
OneTimeRunner.Run(() => |
|||
{ |
|||
/* You can add extension properties to DTOs |
|||
* defined in the depended modules. |
|||
* |
|||
* Example: |
|||
* |
|||
* ObjectExtensionManager.Instance |
|||
* .AddOrUpdateProperty<IdentityRoleDto, string>("Title"); |
|||
* |
|||
* See the documentation for more: |
|||
* https://docs.abp.io/en/abp/latest/Object-Extensions
|
|||
*/ |
|||
}); |
|||
} |
|||
} |
|||
@ -0,0 +1,22 @@ |
|||
using Bench.Localization; |
|||
using Volo.Abp.Authorization.Permissions; |
|||
using Volo.Abp.Localization; |
|||
using Volo.Abp.MultiTenancy; |
|||
|
|||
namespace Bench.Permissions; |
|||
|
|||
public class BenchPermissionDefinitionProvider : PermissionDefinitionProvider |
|||
{ |
|||
public override void Define(IPermissionDefinitionContext context) |
|||
{ |
|||
var myGroup = context.AddGroup(BenchPermissions.GroupName); |
|||
|
|||
//Define your own permissions here. Example:
|
|||
//myGroup.AddPermission(BenchPermissions.MyPermission1, L("Permission:MyPermission1"));
|
|||
} |
|||
|
|||
private static LocalizableString L(string name) |
|||
{ |
|||
return LocalizableString.Create<BenchResource>(name); |
|||
} |
|||
} |
|||
@ -0,0 +1,11 @@ |
|||
namespace Bench.Permissions; |
|||
|
|||
public static class BenchPermissions |
|||
{ |
|||
public const string GroupName = "Bench"; |
|||
|
|||
|
|||
|
|||
//Add your own permission names. Example:
|
|||
//public const string MyPermission1 = GroupName + ".MyPermission1";
|
|||
} |
|||
@ -0,0 +1,4 @@ |
|||
{ |
|||
"role": "lib.application", |
|||
"projectId": "f74c51c2-cb98-4773-8059-f3c83e26db9b" |
|||
} |
|||
@ -0,0 +1,25 @@ |
|||
<Project Sdk="Microsoft.NET.Sdk"> |
|||
|
|||
<Import Project="..\..\common.props" /> |
|||
|
|||
<PropertyGroup> |
|||
<TargetFramework>net10.0</TargetFramework> |
|||
<Nullable>enable</Nullable> |
|||
<RootNamespace>Bench</RootNamespace> |
|||
</PropertyGroup> |
|||
|
|||
<ItemGroup> |
|||
<ProjectReference Include="..\Bench.Domain\Bench.Domain.csproj" /> |
|||
<ProjectReference Include="..\Bench.Application.Contracts\Bench.Application.Contracts.csproj" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Volo.Abp.PermissionManagement.Application" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.FeatureManagement.Application" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.SettingManagement.Application" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.Account.Application" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.Identity.Application" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.TenantManagement.Application" Version="10.7.1" /> |
|||
</ItemGroup> |
|||
|
|||
</Project> |
|||
@ -0,0 +1,14 @@ |
|||
using Bench.Localization; |
|||
using Volo.Abp.Application.Services; |
|||
|
|||
namespace Bench; |
|||
|
|||
/* Inherit your application services from this class. |
|||
*/ |
|||
public abstract class BenchAppService : ApplicationService |
|||
{ |
|||
protected BenchAppService() |
|||
{ |
|||
LocalizationResource = typeof(BenchResource); |
|||
} |
|||
} |
|||
@ -0,0 +1,15 @@ |
|||
using Riok.Mapperly.Abstractions; |
|||
using Volo.Abp.Mapperly; |
|||
|
|||
namespace Bench; |
|||
|
|||
/* |
|||
* You can add your own mappings here. |
|||
* [Mapper(RequiredMappingStrategy = RequiredMappingStrategy.Target)] |
|||
* public partial class BenchApplicationMappers : MapperBase<BookDto, CreateUpdateBookDto> |
|||
* { |
|||
* public override partial CreateUpdateBookDto Map(BookDto source); |
|||
* |
|||
* public override partial void Map(BookDto source, CreateUpdateBookDto destination); |
|||
* } |
|||
*/ |
|||
@ -0,0 +1,26 @@ |
|||
using Volo.Abp.PermissionManagement; |
|||
using Volo.Abp.SettingManagement; |
|||
using Volo.Abp.Account; |
|||
using Volo.Abp.Identity; |
|||
using Volo.Abp.Mapperly; |
|||
using Volo.Abp.FeatureManagement; |
|||
using Volo.Abp.Modularity; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Volo.Abp.TenantManagement; |
|||
|
|||
namespace Bench; |
|||
|
|||
[DependsOn( |
|||
typeof(BenchDomainModule), |
|||
typeof(BenchApplicationContractsModule), |
|||
typeof(AbpPermissionManagementApplicationModule), |
|||
typeof(AbpFeatureManagementApplicationModule), |
|||
typeof(AbpIdentityApplicationModule), |
|||
typeof(AbpAccountApplicationModule), |
|||
typeof(AbpTenantManagementApplicationModule), |
|||
typeof(AbpSettingManagementApplicationModule) |
|||
)] |
|||
public class BenchApplicationModule : AbpModule |
|||
{ |
|||
|
|||
} |
|||
@ -0,0 +1,2 @@ |
|||
using System.Runtime.CompilerServices; |
|||
[assembly:InternalsVisibleToAttribute("Bench.Application.Tests")] |
|||
@ -0,0 +1,3 @@ |
|||
{ |
|||
"projectId": "b21bc1d0-00b0-4845-83b9-3ef2f240ec63" |
|||
} |
|||
@ -0,0 +1,44 @@ |
|||
<Project Sdk="Microsoft.NET.Sdk"> |
|||
|
|||
<Import Project="..\..\common.props" /> |
|||
|
|||
<PropertyGroup> |
|||
<OutputType>Exe</OutputType> |
|||
<TargetFramework>net10.0</TargetFramework> |
|||
<Nullable>enable</Nullable> |
|||
</PropertyGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" /> |
|||
<PackageReference Include="Serilog.Sinks.Async" Version="2.1.0" /> |
|||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.11" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Volo.Abp.Autofac" Version="10.7.1" /> |
|||
<ProjectReference Include="..\Bench.EntityFrameworkCore\Bench.EntityFrameworkCore.csproj" /> |
|||
<ProjectReference Include="..\Bench.Application.Contracts\Bench.Application.Contracts.csproj" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<Compile Remove="Logs\**" /> |
|||
<Content Remove="Logs\**" /> |
|||
|
|||
<EmbeddedResource Remove="Logs\**" /> |
|||
<None Remove="Logs\**" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<None Remove="appsettings.json" /> |
|||
<Content Include="appsettings.json"> |
|||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> |
|||
<CopyToOutputDirectory>Always</CopyToOutputDirectory> |
|||
</Content> |
|||
<None Remove="appsettings.secrets.json" /> |
|||
<Content Include="appsettings.secrets.json"> |
|||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> |
|||
<CopyToOutputDirectory>Always</CopyToOutputDirectory> |
|||
</Content> |
|||
</ItemGroup> |
|||
|
|||
</Project> |
|||
@ -0,0 +1,14 @@ |
|||
using Bench.EntityFrameworkCore; |
|||
using Volo.Abp.Autofac; |
|||
using Volo.Abp.Modularity; |
|||
|
|||
namespace Bench.DbMigrator; |
|||
|
|||
[DependsOn( |
|||
typeof(AbpAutofacModule), |
|||
typeof(BenchEntityFrameworkCoreModule), |
|||
typeof(BenchApplicationContractsModule) |
|||
)] |
|||
public class BenchDbMigratorModule : AbpModule |
|||
{ |
|||
} |
|||
@ -0,0 +1,51 @@ |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.Configuration; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Hosting; |
|||
using Bench.Data; |
|||
using Serilog; |
|||
using Volo.Abp; |
|||
using Volo.Abp.Data; |
|||
|
|||
namespace Bench.DbMigrator; |
|||
|
|||
public class DbMigratorHostedService : IHostedService |
|||
{ |
|||
private readonly IHostApplicationLifetime _hostApplicationLifetime; |
|||
private readonly IConfiguration _configuration; |
|||
|
|||
public DbMigratorHostedService(IHostApplicationLifetime hostApplicationLifetime, IConfiguration configuration) |
|||
{ |
|||
_hostApplicationLifetime = hostApplicationLifetime; |
|||
_configuration = configuration; |
|||
} |
|||
|
|||
public async Task StartAsync(CancellationToken cancellationToken) |
|||
{ |
|||
using (var application = await AbpApplicationFactory.CreateAsync<BenchDbMigratorModule>(options => |
|||
{ |
|||
options.Services.ReplaceConfiguration(_configuration); |
|||
options.UseAutofac(); |
|||
options.Services.AddLogging(c => c.AddSerilog()); |
|||
options.AddDataMigrationEnvironment(); |
|||
})) |
|||
{ |
|||
await application.InitializeAsync(); |
|||
|
|||
await application |
|||
.ServiceProvider |
|||
.GetRequiredService<BenchDbMigrationService>() |
|||
.MigrateAsync(); |
|||
|
|||
await application.ShutdownAsync(); |
|||
|
|||
_hostApplicationLifetime.StopApplication(); |
|||
} |
|||
} |
|||
|
|||
public Task StopAsync(CancellationToken cancellationToken) |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
@ -0,0 +1,5 @@ |
|||
FROM mcr.microsoft.com/dotnet/sdk:10.0 |
|||
COPY bin/Release/net10.0/publish/ app/ |
|||
WORKDIR /app |
|||
ENV ASPNETCORE_URLS=http://+:80 |
|||
ENTRYPOINT ["dotnet", "Bench.DbMigrator.dll"] |
|||
@ -0,0 +1,6 @@ |
|||
FROM mcr.microsoft.com/dotnet/sdk:10.0 |
|||
USER $APP_UID |
|||
|
|||
COPY bin/Release/net10.0/publish/ app/ |
|||
WORKDIR /app |
|||
ENTRYPOINT ["dotnet", "Bench.DbMigrator.dll"] |
|||
@ -0,0 +1,39 @@ |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Hosting; |
|||
using Microsoft.Extensions.Logging; |
|||
using Serilog; |
|||
using Serilog.Events; |
|||
|
|||
namespace Bench.DbMigrator; |
|||
|
|||
class Program |
|||
{ |
|||
static async Task Main(string[] args) |
|||
{ |
|||
Log.Logger = new LoggerConfiguration() |
|||
.MinimumLevel.Information() |
|||
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning) |
|||
.MinimumLevel.Override("Volo.Abp", LogEventLevel.Warning) |
|||
#if DEBUG
|
|||
.MinimumLevel.Override("Bench", LogEventLevel.Debug) |
|||
#else
|
|||
.MinimumLevel.Override("Bench", LogEventLevel.Information) |
|||
#endif
|
|||
.Enrich.FromLogContext() |
|||
.WriteTo.Async(c => c.File("Logs/logs.txt")) |
|||
.WriteTo.Async(c => c.Console()) |
|||
.CreateLogger(); |
|||
|
|||
await CreateHostBuilder(args).RunConsoleAsync(); |
|||
} |
|||
|
|||
public static IHostBuilder CreateHostBuilder(string[] args) => |
|||
Host.CreateDefaultBuilder(args) |
|||
.AddAppSettingsSecretsJson() |
|||
.ConfigureLogging((context, logging) => logging.ClearProviders()) |
|||
.ConfigureServices((hostContext, services) => |
|||
{ |
|||
services.AddHostedService<DbMigratorHostedService>(); |
|||
}); |
|||
} |
|||
@ -0,0 +1,15 @@ |
|||
{ |
|||
"ConnectionStrings": { |
|||
"Default": "Host=localhost;Port=5432;Database=Bench;User ID=root;Password=myPassword;" |
|||
}, |
|||
"OpenIddict": { |
|||
"Applications": { |
|||
"Bench_App": { |
|||
"ClientId": "Bench_App" }, |
|||
"Bench_Swagger": { |
|||
"ClientId": "Bench_Swagger", |
|||
"RootUrl": "https://localhost:44377/" |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,4 @@ |
|||
{ |
|||
"role": "lib.domain-shared", |
|||
"projectId": "688d875d-cbb0-4807-a5d6-64f9a75e7f4d" |
|||
} |
|||
@ -0,0 +1,37 @@ |
|||
<Project Sdk="Microsoft.NET.Sdk"> |
|||
|
|||
<Import Project="..\..\common.props" /> |
|||
|
|||
<PropertyGroup> |
|||
<TargetFramework>net10.0</TargetFramework> |
|||
<Nullable>enable</Nullable> |
|||
<RootNamespace>Bench</RootNamespace> |
|||
<GenerateEmbeddedFilesManifest>true</GenerateEmbeddedFilesManifest> |
|||
</PropertyGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Volo.Abp.BackgroundJobs.Domain.Shared" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.AuditLogging.Domain.Shared" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.FeatureManagement.Domain.Shared" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.PermissionManagement.Domain.Shared" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.SettingManagement.Domain.Shared" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.BlobStoring.Database.Domain.Shared" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.GlobalFeatures" Version="10.7.1" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Volo.Abp.OpenIddict.Domain.Shared" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.Identity.Domain.Shared" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.TenantManagement.Domain.Shared" Version="10.7.1" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="10.0.11" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<EmbeddedResource Include="Localization\Bench\*.json" /> |
|||
<Content Remove="Localization\Bench\*.json" /> |
|||
</ItemGroup> |
|||
|
|||
</Project> |
|||
@ -0,0 +1,6 @@ |
|||
namespace Bench; |
|||
|
|||
public static class BenchDomainErrorCodes |
|||
{ |
|||
/* You can add your business exception error codes here, as constants */ |
|||
} |
|||
@ -0,0 +1,83 @@ |
|||
using Bench.Localization; |
|||
using Volo.Abp.AuditLogging; |
|||
using Volo.Abp.BackgroundJobs; |
|||
using Volo.Abp.FeatureManagement; |
|||
using Volo.Abp.Identity; |
|||
using Volo.Abp.Localization; |
|||
using Volo.Abp.Localization.ExceptionHandling; |
|||
using Volo.Abp.Validation.Localization; |
|||
using Volo.Abp.Modularity; |
|||
using Volo.Abp.PermissionManagement; |
|||
using Volo.Abp.SettingManagement; |
|||
using Volo.Abp.VirtualFileSystem; |
|||
using Volo.Abp.OpenIddict; |
|||
using Volo.Abp.BlobStoring.Database; |
|||
using Volo.Abp.TenantManagement; |
|||
|
|||
namespace Bench; |
|||
|
|||
[DependsOn( |
|||
typeof(AbpAuditLoggingDomainSharedModule), |
|||
typeof(AbpBackgroundJobsDomainSharedModule), |
|||
typeof(AbpFeatureManagementDomainSharedModule), |
|||
typeof(AbpPermissionManagementDomainSharedModule), |
|||
typeof(AbpSettingManagementDomainSharedModule), |
|||
typeof(AbpIdentityDomainSharedModule), |
|||
typeof(AbpOpenIddictDomainSharedModule), |
|||
typeof(AbpTenantManagementDomainSharedModule), |
|||
typeof(BlobStoringDatabaseDomainSharedModule) |
|||
)] |
|||
public class BenchDomainSharedModule : AbpModule |
|||
{ |
|||
public override void PreConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
BenchGlobalFeatureConfigurator.Configure(); |
|||
BenchModuleExtensionConfigurator.Configure(); |
|||
} |
|||
|
|||
public override void ConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
Configure<AbpVirtualFileSystemOptions>(options => |
|||
{ |
|||
options.FileSets.AddEmbedded<BenchDomainSharedModule>(); |
|||
}); |
|||
|
|||
Configure<AbpLocalizationOptions>(options => |
|||
{ |
|||
options.Resources |
|||
.Add<BenchResource>("en") |
|||
.AddBaseTypes(typeof(AbpValidationResource)) |
|||
.AddVirtualJson("/Localization/Bench"); |
|||
|
|||
options.DefaultResourceType = typeof(BenchResource); |
|||
|
|||
options.Languages.Add(new LanguageInfo("en", "en", "English")); |
|||
options.Languages.Add(new LanguageInfo("ar", "ar", "Arabic")); |
|||
options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "Chinese (Simplified)")); |
|||
options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "Chinese (Traditional)")); |
|||
options.Languages.Add(new LanguageInfo("cs", "cs", "Czech")); |
|||
options.Languages.Add(new LanguageInfo("en-GB", "en-GB", "English (UK)")); |
|||
options.Languages.Add(new LanguageInfo("fi", "fi", "Finnish")); |
|||
options.Languages.Add(new LanguageInfo("fr", "fr", "French")); |
|||
options.Languages.Add(new LanguageInfo("de-DE", "de-DE", "German (Germany)")); |
|||
options.Languages.Add(new LanguageInfo("hi", "hi", "Hindi ")); |
|||
options.Languages.Add(new LanguageInfo("hu", "hu", "Hungarian")); |
|||
options.Languages.Add(new LanguageInfo("is", "is", "Icelandic")); |
|||
options.Languages.Add(new LanguageInfo("it", "it", "Italian")); |
|||
options.Languages.Add(new LanguageInfo("ko", "ko", "Korean")); |
|||
options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Portuguese (Brazil)")); |
|||
options.Languages.Add(new LanguageInfo("ro-RO", "ro-RO", "Romanian (Romania)")); |
|||
options.Languages.Add(new LanguageInfo("ru", "ru", "Russian")); |
|||
options.Languages.Add(new LanguageInfo("sk", "sk", "Slovak")); |
|||
options.Languages.Add(new LanguageInfo("es", "es", "Spanish")); |
|||
options.Languages.Add(new LanguageInfo("sv", "sv", "Swedish")); |
|||
options.Languages.Add(new LanguageInfo("tr", "tr", "Turkish")); |
|||
|
|||
}); |
|||
|
|||
Configure<AbpExceptionLocalizationOptions>(options => |
|||
{ |
|||
options.MapCodeNamespace("Bench", typeof(BenchResource)); |
|||
}); |
|||
} |
|||
} |
|||
@ -0,0 +1,20 @@ |
|||
using Volo.Abp.GlobalFeatures; |
|||
using Volo.Abp.Threading; |
|||
|
|||
namespace Bench; |
|||
|
|||
public static class BenchGlobalFeatureConfigurator |
|||
{ |
|||
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); |
|||
|
|||
public static void Configure() |
|||
{ |
|||
OneTimeRunner.Run(() => |
|||
{ |
|||
/* You can configure (enable/disable) global features of the used modules here. |
|||
* Please refer to the documentation to learn more about the Global Features System: |
|||
* https://docs.abp.io/en/abp/latest/Global-Features
|
|||
*/ |
|||
}); |
|||
} |
|||
} |
|||
@ -0,0 +1,71 @@ |
|||
using System.ComponentModel.DataAnnotations; |
|||
using Volo.Abp.Identity; |
|||
using Volo.Abp.ObjectExtending; |
|||
using Volo.Abp.Threading; |
|||
|
|||
namespace Bench; |
|||
|
|||
public static class BenchModuleExtensionConfigurator |
|||
{ |
|||
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); |
|||
|
|||
public static void Configure() |
|||
{ |
|||
OneTimeRunner.Run(() => |
|||
{ |
|||
ConfigureExistingProperties(); |
|||
ConfigureExtraProperties(); |
|||
}); |
|||
} |
|||
|
|||
private static void ConfigureExistingProperties() |
|||
{ |
|||
/* You can change max lengths for properties of the |
|||
* entities defined in the modules used by your application. |
|||
* |
|||
* Example: Change user and role name max lengths |
|||
|
|||
AbpUserConsts.MaxNameLength = 99; |
|||
IdentityRoleConsts.MaxNameLength = 99; |
|||
|
|||
* Notice: It is not suggested to change property lengths |
|||
* unless you really need it. Go with the standard values wherever possible. |
|||
* |
|||
* If you are using EF Core, you will need to run the add-migration command after your changes. |
|||
*/ |
|||
} |
|||
|
|||
private static void ConfigureExtraProperties() |
|||
{ |
|||
/* You can configure extra properties for the |
|||
* entities defined in the modules used by your application. |
|||
* |
|||
* This class can be used to define these extra properties |
|||
* with a high level, easy to use API. |
|||
* |
|||
* Example: Add a new property to the user entity of the identity module |
|||
|
|||
ObjectExtensionManager.Instance.Modules() |
|||
.ConfigureIdentity(identity => |
|||
{ |
|||
identity.ConfigureUser(user => |
|||
{ |
|||
user.AddOrUpdateProperty<string>( //property type: string
|
|||
"SocialSecurityNumber", //property name
|
|||
property => |
|||
{ |
|||
//validation rules
|
|||
property.Attributes.Add(new RequiredAttribute()); |
|||
property.Attributes.Add(new StringLengthAttribute(64) {MinimumLength = 4}); |
|||
|
|||
//...other configurations for this property
|
|||
} |
|||
); |
|||
}); |
|||
}); |
|||
|
|||
* See the documentation for more: |
|||
* https://abp.io/docs/latest/framework/architecture/modularity/extending/module-entity-extensions
|
|||
*/ |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"culture": "ar", |
|||
"texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "منزل، بيت", |
|||
"Menu:ContactUs": "اتصل بنا", |
|||
"Menu:ArticleSample": "عينة المادة", |
|||
"Home": "منزل، بيت", |
|||
"Welcome": "مرحبا", |
|||
"LongWelcomeMessage": "مرحبا بكم في التطبيق. هذا مشروع بدء التشغيل يعتمد على إطار عمل برنامج ABP. لمزيد من المعلومات قم بزيارة", |
|||
"Date": "تاريخ", |
|||
"Permission:Dashboard": "لوحة القيادة", |
|||
"Menu:Dashboard": "لوحة القيادة", |
|||
"Menu:HomePage": "الصفحة الرئيسية", |
|||
"Dashboard": "لوحة القيادة", |
|||
"ExternalProvider:Google": "جوجل", |
|||
"ExternalProvider:Google:ClientId": "معرف العميل", |
|||
"ExternalProvider:Google:ClientSecret": "سر العميل", |
|||
"ExternalProvider:Microsoft": "مايكروسوفت", |
|||
"ExternalProvider:Microsoft:ClientId": "معرف العميل", |
|||
"ExternalProvider:Microsoft:ClientSecret": "سر العميل", |
|||
"ExternalProvider:Twitter": "تويتر", |
|||
"ExternalProvider:Twitter:ConsumerKey": "مفتاح المستهلك", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "سر المستهلك", |
|||
"NewsletterHeader": "اشترك في النشرة الإخبارية!", |
|||
"NewsletterInfo": "احصل على معلومات حول آخر الأحداث.", |
|||
"NewsletterPreference_Default": "النشرة الإخبارية الافتراضية", |
|||
"NewsletterPrivacyAcceptMessage": "أوافق على <a href='/privacy-policy'> سياسة الخصوصية </a>.", |
|||
"Language": "لغة", |
|||
"Search": "يبحث", |
|||
"LoadMore": "تحميل المزيد", |
|||
"Settings": "إعدادات", |
|||
"Theme": "سمة", |
|||
"DeviceTheme": "موضوع الجهاز", |
|||
"Dark": "مظلم", |
|||
"Light": "ضوء", |
|||
"Unspecified": "نظام", |
|||
"SeeAllUsers": "رؤية كافة المستخدمين", |
|||
"TakePhoto": "تصوير", |
|||
"ChoosePhoto": "اختر صورة" |
|||
} |
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
{ |
|||
"Culture": "cs", |
|||
"Texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Home", |
|||
"LongWelcomeMessage": "Welcome to the application. This is a startup project based on the ABP framework. For more information visit", |
|||
"Welcome": "Welcome" |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"culture": "de-DE", |
|||
"texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Home", |
|||
"Menu:ContactUs": "Kontaktiere uns", |
|||
"Menu:ArticleSample": "Artikelmuster", |
|||
"Home": "Home", |
|||
"Welcome": "Willkommen", |
|||
"LongWelcomeMessage": "Willkommen in der Anwendung. Dies ist ein Startup-Projekt basierend auf dem ABP-Framework. Weitere Informationen finden Sie unter", |
|||
"Date": "Datum", |
|||
"Permission:Dashboard": "Dashboard", |
|||
"Menu:Dashboard": "Dashboard", |
|||
"Menu:HomePage": "Startseite", |
|||
"Dashboard": "Dashboard", |
|||
"ExternalProvider:Google": "Google", |
|||
"ExternalProvider:Google:ClientId": "Kunden ID", |
|||
"ExternalProvider:Google:ClientSecret": "Client-Geheimnis", |
|||
"ExternalProvider:Microsoft": "Microsoft", |
|||
"ExternalProvider:Microsoft:ClientId": "Kunden ID", |
|||
"ExternalProvider:Microsoft:ClientSecret": "Client-Geheimnis", |
|||
"ExternalProvider:Twitter": "Twitter", |
|||
"ExternalProvider:Twitter:ConsumerKey": "Verbraucherschlüssel", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "Verbrauchergeheimnis", |
|||
"NewsletterHeader": "Abonnieren Sie den Newsletter!", |
|||
"NewsletterInfo": "Informieren Sie sich über aktuelle Ereignisse.", |
|||
"NewsletterPreference_Default": "Standard-Newsletter", |
|||
"NewsletterPrivacyAcceptMessage": "Ich akzeptiere die <a href='/privacy-policy'>Datenschutzerklärung</a>.", |
|||
"Language": "Sprache", |
|||
"Search": "Suchen", |
|||
"LoadMore": "Mehr laden", |
|||
"Settings": "Einstellungen", |
|||
"Theme": "Thema", |
|||
"DeviceTheme": "Gerätethema", |
|||
"Dark": "Dunkel", |
|||
"Light": "Licht", |
|||
"Unspecified": "System", |
|||
"SeeAllUsers": "Alle Benutzer anzeigen", |
|||
"TakePhoto": "Foto machen", |
|||
"ChoosePhoto": "Wähle ein Foto aus" |
|||
} |
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
{ |
|||
"Culture": "en-GB", |
|||
"Texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Home", |
|||
"LongWelcomeMessage": "Welcome to the application. This is a startup project based on the ABP framework. For more information visit", |
|||
"Welcome": "Welcome" |
|||
} |
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
{ |
|||
"Culture": "en", |
|||
"Texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Home", |
|||
"LongWelcomeMessage": "Welcome to the application. This is a startup project based on the ABP framework. For more information visit", |
|||
"Welcome": "Welcome" |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"culture": "es", |
|||
"texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Hogar", |
|||
"Menu:ContactUs": "Contáctenos", |
|||
"Menu:ArticleSample": "Muestra de artículo", |
|||
"Home": "Hogar", |
|||
"Welcome": "Bienvenido", |
|||
"LongWelcomeMessage": "Bienvenido a la aplicacion. Este es un proyecto de inicio basado en el marco ABP. Para obtener mas informacion, visite", |
|||
"Date": "Fecha", |
|||
"Permission:Dashboard": "Panel de control", |
|||
"Menu:Dashboard": "Panel de control", |
|||
"Menu:HomePage": "Página de inicio", |
|||
"Dashboard": "Panel de control", |
|||
"ExternalProvider:Google": "Google", |
|||
"ExternalProvider:Google:ClientId": "ID de cliente", |
|||
"ExternalProvider:Google:ClientSecret": "Client Secret", |
|||
"ExternalProvider:Microsoft": "Microsoft", |
|||
"ExternalProvider:Microsoft:ClientId": "ID de cliente", |
|||
"ExternalProvider:Microsoft:ClientSecret": "Client Secret", |
|||
"ExternalProvider:Twitter": "Twitter", |
|||
"ExternalProvider:Twitter:ConsumerKey": "Clave de consumidor", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "Consumer Secret", |
|||
"NewsletterHeader": "Suscríbete a la newsletter!", |
|||
"NewsletterInfo": "Obtenga información sobre los últimos acontecimientos.", |
|||
"NewsletterPreference_Default": "Boletín de noticias predeterminado", |
|||
"NewsletterPrivacyAcceptMessage": "Acepto la <a href='/privacy-policy'> Política de privacidad </a>.", |
|||
"Language": "Idioma", |
|||
"Search": "Buscar", |
|||
"LoadMore": "Carga más", |
|||
"Settings": "Ajustes", |
|||
"Theme": "Tema", |
|||
"DeviceTheme": "Tema del dispositivo", |
|||
"Dark": "Oscuro", |
|||
"Light": "Luz", |
|||
"Unspecified": "Sistema", |
|||
"SeeAllUsers": "Ver todos los usuarios", |
|||
"TakePhoto": "Tomar foto", |
|||
"ChoosePhoto": "Escoge una foto" |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"culture": "fi", |
|||
"texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Koti", |
|||
"Menu:ContactUs": "Ota meihin yhteyttä", |
|||
"Menu:ArticleSample": "Artikkelinäyte", |
|||
"Home": "Koti", |
|||
"Welcome": "Tervetuloa", |
|||
"LongWelcomeMessage": "Tervetuloa sovellukseen. Tämä on ABP-kehykseen perustuva käynnistysprojekti. Lisätietoja on osoitteessa", |
|||
"Date": "Päivämäärä", |
|||
"Permission:Dashboard": "Kojelauta", |
|||
"Menu:Dashboard": "Kojelauta", |
|||
"Menu:HomePage": "Kotisivu", |
|||
"Dashboard": "Kojelauta", |
|||
"ExternalProvider:Google": "Google", |
|||
"ExternalProvider:Google:ClientId": "Asiakastunnus", |
|||
"ExternalProvider:Google:ClientSecret": "Asiakkaan salaisuus", |
|||
"ExternalProvider:Microsoft": "Microsoft", |
|||
"ExternalProvider:Microsoft:ClientId": "Asiakastunnus", |
|||
"ExternalProvider:Microsoft:ClientSecret": "Asiakkaan salaisuus", |
|||
"ExternalProvider:Twitter": "Viserrys", |
|||
"ExternalProvider:Twitter:ConsumerKey": "Kuluttaja-avain", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "Kuluttajan salaisuus", |
|||
"NewsletterHeader": "Tilaa uutiskirje!", |
|||
"NewsletterInfo": "Hanki tietoa viimeisimmistä tapahtumista.", |
|||
"NewsletterPreference_Default": "Oletusuutiskirje", |
|||
"NewsletterPrivacyAcceptMessage": "Hyväksyn <a href='/privacy-policy'> tietosuojakäytännön </a>.", |
|||
"Language": "Kieli", |
|||
"Search": "Hae", |
|||
"LoadMore": "Lataa lisää", |
|||
"Settings": "asetukset", |
|||
"Theme": "Teema", |
|||
"DeviceTheme": "Laitteen teema", |
|||
"Dark": "Tumma", |
|||
"Light": "Kevyt", |
|||
"Unspecified": "Järjestelmä", |
|||
"SeeAllUsers": "Katso Kaikki käyttäjät", |
|||
"TakePhoto": "Ota valokuva", |
|||
"ChoosePhoto": "Valitse Valokuva" |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"culture": "fr", |
|||
"texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Acceuil", |
|||
"Menu:ContactUs": "Nous contacter", |
|||
"Menu:ArticleSample": "Échantillon d'article", |
|||
"Home": "Acceuil", |
|||
"Welcome": "Bienvenue", |
|||
"LongWelcomeMessage": "Bienvenue dans l'application. Il s'agit d'un projet de démarrage basé sur le framework ABP. Pour plus d'informations, visitez", |
|||
"Date": "Date", |
|||
"Permission:Dashboard": "Tableau de bord", |
|||
"Menu:Dashboard": "Tableau de bord", |
|||
"Menu:HomePage": "Page d'accueil", |
|||
"Dashboard": "Tableau de bord", |
|||
"ExternalProvider:Google": "Google", |
|||
"ExternalProvider:Google:ClientId": "identité du client", |
|||
"ExternalProvider:Google:ClientSecret": "Secret du client", |
|||
"ExternalProvider:Microsoft": "Microsoft", |
|||
"ExternalProvider:Microsoft:ClientId": "identité du client", |
|||
"ExternalProvider:Microsoft:ClientSecret": "Secret du client", |
|||
"ExternalProvider:Twitter": "Twitter", |
|||
"ExternalProvider:Twitter:ConsumerKey": "La clé du consommateur", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "Secret du consommateur", |
|||
"NewsletterHeader": "Abonnez-vous à la newsletter!", |
|||
"NewsletterInfo": "Obtenez des informations sur les derniers événements.", |
|||
"NewsletterPreference_Default": "Newsletter par défaut", |
|||
"NewsletterPrivacyAcceptMessage": "J'accepte la <a href='/privacy-policy'> Politique de confidentialité </a>.", |
|||
"Language": "Langue", |
|||
"Search": "Recherche", |
|||
"LoadMore": "Charger plus", |
|||
"Settings": "Paramètres", |
|||
"Theme": "Thème", |
|||
"DeviceTheme": "Thème de l'appareil", |
|||
"Dark": "Sombre", |
|||
"Light": "Lumière", |
|||
"Unspecified": "Système", |
|||
"SeeAllUsers": "Voir tous les utilisateurs", |
|||
"TakePhoto": "Prendre une photo", |
|||
"ChoosePhoto": "Choisissez une photo" |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"culture": "hi", |
|||
"texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "घर", |
|||
"Menu:ContactUs": "संपर्क करें", |
|||
"Menu:ArticleSample": "आलेख नमूना", |
|||
"Home": "घर", |
|||
"Welcome": "स्वागत हे", |
|||
"LongWelcomeMessage": "आवेदन करने के लिए आपका स्वागत है। यह एबीपी ढांचे पर आधारित एक स्टार्टअप परियोजना है। अधिक जानकारी के लिए पर जाएँ।", |
|||
"Date": "दिनांक", |
|||
"Permission:Dashboard": "डैशबोर्ड", |
|||
"Menu:Dashboard": "डैशबोर्ड", |
|||
"Menu:HomePage": "मुख पृष्ठ", |
|||
"Dashboard": "डैशबोर्ड", |
|||
"ExternalProvider:Google": "गूगल", |
|||
"ExternalProvider:Google:ClientId": "ग्राहक ID", |
|||
"ExternalProvider:Google:ClientSecret": "ग्राहक गुप्त", |
|||
"ExternalProvider:Microsoft": "माइक्रोसॉफ्ट", |
|||
"ExternalProvider:Microsoft:ClientId": "ग्राहक ID", |
|||
"ExternalProvider:Microsoft:ClientSecret": "ग्राहक गुप्त", |
|||
"ExternalProvider:Twitter": "ट्विटर", |
|||
"ExternalProvider:Twitter:ConsumerKey": "उपभोक्ता कुंजी", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "उपभोक्ता रहस्य", |
|||
"NewsletterHeader": "न्यूज़लेटर की सदस्यता लें!", |
|||
"NewsletterInfo": "नवीनतम घटनाओं के बारे में जानकारी प्राप्त करें।", |
|||
"NewsletterPreference_Default": "डिफ़ॉल्ट न्यूज़लैटर", |
|||
"NewsletterPrivacyAcceptMessage": "मैं <a href='/privacy-policy'> गोपनीयता नीति </a> स्वीकार करता हूं।", |
|||
"Language": "भाषा", |
|||
"Search": "खोज", |
|||
"LoadMore": "और लोड करें", |
|||
"Settings": "समायोजन", |
|||
"Theme": "विषय", |
|||
"DeviceTheme": "डिवाइस थीम", |
|||
"Dark": "अँधेरा", |
|||
"Light": "रोशनी", |
|||
"Unspecified": "प्रणाली", |
|||
"SeeAllUsers": "सभी उपयोगकर्ता देखें", |
|||
"TakePhoto": "फोटो लो", |
|||
"ChoosePhoto": "तस्विर का चयन करो" |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"culture": "hu", |
|||
"texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Kezdőlap", |
|||
"Menu:ContactUs": "Lépjen kapcsolatba velünk", |
|||
"Menu:ArticleSample": "Cikkminta", |
|||
"Home": "Kezdőlap", |
|||
"Welcome": "Üdvözöljük", |
|||
"LongWelcomeMessage": "Üdvözöljük az alkalmazásban. Ez egy ABP keretrendszeren alapuló startup projekt. További információért látogasson el az oldalra", |
|||
"Date": "dátum", |
|||
"Permission:Dashboard": "Irányítópult", |
|||
"Menu:Dashboard": "Irányítópult", |
|||
"Menu:HomePage": "Kezdőlap", |
|||
"Dashboard": "Irányítópult", |
|||
"ExternalProvider:Google": "Google", |
|||
"ExternalProvider:Google:ClientId": "Ügyfélazonosító", |
|||
"ExternalProvider:Google:ClientSecret": "Ügyfél titkos kulcs", |
|||
"ExternalProvider:Microsoft": "Microsoft", |
|||
"ExternalProvider:Microsoft:ClientId": "Ügyfélazonosító", |
|||
"ExternalProvider:Microsoft:ClientSecret": "Ügyfél titkos kulcs", |
|||
"ExternalProvider:Twitter": "Twitter", |
|||
"ExternalProvider:Twitter:ConsumerKey": "Fogyasztói kulcs", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "Fogyasztói titkos kulcs", |
|||
"NewsletterHeader": "Iratkozz fel a hírlevélre!", |
|||
"NewsletterInfo": "Tájékozódjon a legfrissebb eseményekről.", |
|||
"NewsletterPreference_Default": "Alapértelmezett hírlevél", |
|||
"NewsletterPrivacyAcceptMessage": "Elfogadom az <a href='/privacy-policy'>Adatvédelmi szabályzatot</a> .", |
|||
"Language": "Nyelv", |
|||
"Search": "Keresés", |
|||
"LoadMore": "Load More", |
|||
"Settings": "Beállítások", |
|||
"Theme": "Téma", |
|||
"DeviceTheme": "Eszköz téma", |
|||
"Dark": "Sötét", |
|||
"Light": "Fény", |
|||
"Unspecified": "Rendszer", |
|||
"SeeAllUsers": "Lásd: Összes felhasználó", |
|||
"TakePhoto": "Fotót készíteni", |
|||
"ChoosePhoto": "Válassz képet" |
|||
} |
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
{ |
|||
"Culture": "is", |
|||
"Texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Home", |
|||
"LongWelcomeMessage": "Welcome to the application. This is a startup project based on the ABP framework. For more information visit", |
|||
"Welcome": "Welcome" |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"culture": "it", |
|||
"texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Home", |
|||
"Menu:ContactUs": "Contattaci", |
|||
"Menu:ArticleSample": "Esempio di articolo", |
|||
"Home": "Home", |
|||
"Welcome": "Benvenuto", |
|||
"LongWelcomeMessage": "Benvenuto nell'applicazione. Questo è un progetto di avvio basato sul framework ABP. Per maggiori informazioni visita", |
|||
"Date": "Data", |
|||
"Permission:Dashboard": "Cruscotto", |
|||
"Menu:Dashboard": "Cruscotto", |
|||
"Menu:HomePage": "Pagina iniziale", |
|||
"Dashboard": "Cruscotto", |
|||
"ExternalProvider:Google": "Google", |
|||
"ExternalProvider:Google:ClientId": "Client ID", |
|||
"ExternalProvider:Google:ClientSecret": "Client Secret", |
|||
"ExternalProvider:Microsoft": "Microsoft", |
|||
"ExternalProvider:Microsoft:ClientId": "Client ID", |
|||
"ExternalProvider:Microsoft:ClientSecret": "Client Secret", |
|||
"ExternalProvider:Twitter": "Twitter", |
|||
"ExternalProvider:Twitter:ConsumerKey": "Consumer Key", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "Consumer Secret", |
|||
"NewsletterHeader": "Iscriviti alla newsletter!", |
|||
"NewsletterInfo": "Ottieni informazioni sugli ultimi avvenimenti.", |
|||
"NewsletterPreference_Default": "Newsletter predefinita", |
|||
"NewsletterPrivacyAcceptMessage": "Accetto la <a href='/privacy-policy'>Informativa sulla privacy</a>.", |
|||
"Language": "Lingua", |
|||
"Search": "Ricerca", |
|||
"LoadMore": "Carica altro", |
|||
"Settings": "Impostazioni", |
|||
"Theme": "Tema", |
|||
"DeviceTheme": "Tema del dispositivo", |
|||
"Dark": "Buio", |
|||
"Light": "Leggero", |
|||
"Unspecified": "Sistema", |
|||
"SeeAllUsers": "Visualizza tutti gli utenti", |
|||
"TakePhoto": "Fare foto", |
|||
"ChoosePhoto": "Scegli la foto" |
|||
} |
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
{ |
|||
"Culture": "ko", |
|||
"Texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Home", |
|||
"LongWelcomeMessage": "Welcome to the application. This is a startup project based on the ABP framework. For more information visit", |
|||
"Welcome": "Welcome" |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"culture": "pt-BR", |
|||
"texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Principal", |
|||
"Menu:ContactUs": "Entre em contato conosco", |
|||
"Menu:ArticleSample": "Amostra de Artigo", |
|||
"Home": "Casa", |
|||
"Welcome": "Seja bem-vindo!", |
|||
"LongWelcomeMessage": "Bem-vindo a esta aplicação. Este é um projeto inicial baseado no ABP framework. Para mais informações, visite", |
|||
"Date": "Data", |
|||
"Permission:Dashboard": "Painel", |
|||
"Menu:Dashboard": "Painel", |
|||
"Menu:HomePage": "Pagina inicial", |
|||
"Dashboard": "Painel", |
|||
"ExternalProvider:Google": "Google", |
|||
"ExternalProvider:Google:ClientId": "ID do Cliente", |
|||
"ExternalProvider:Google:ClientSecret": "Segredo do cliente", |
|||
"ExternalProvider:Microsoft": "Microsoft", |
|||
"ExternalProvider:Microsoft:ClientId": "ID do Cliente", |
|||
"ExternalProvider:Microsoft:ClientSecret": "Segredo do cliente", |
|||
"ExternalProvider:Twitter": "Twitter", |
|||
"ExternalProvider:Twitter:ConsumerKey": "Chave do consumidor", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "consumidor secreto", |
|||
"NewsletterHeader": "Assine a newsletter!", |
|||
"NewsletterInfo": "Obtenha informações sobre os últimos acontecimentos.", |
|||
"NewsletterPreference_Default": "Boletim informativo padrão", |
|||
"NewsletterPrivacyAcceptMessage": "Eu aceito a <a href='/privacy-policy'> Política de Privacidade </a>.", |
|||
"Language": "Linguagem", |
|||
"Search": "Procurar", |
|||
"LoadMore": "Carregue mais", |
|||
"Settings": "Configurações", |
|||
"Theme": "Tema", |
|||
"DeviceTheme": "Tema do dispositivo", |
|||
"Dark": "Escuro", |
|||
"Light": "Luz", |
|||
"Unspecified": "Sistema", |
|||
"SeeAllUsers": "Ver todos os usuários", |
|||
"TakePhoto": "Tirar fotos", |
|||
"ChoosePhoto": "Escolher Foto" |
|||
} |
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
{ |
|||
"Culture": "ro-RO", |
|||
"Texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Home", |
|||
"LongWelcomeMessage": "Welcome to the application. This is a startup project based on the ABP framework. For more information visit", |
|||
"Welcome": "Welcome" |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"culture": "ru", |
|||
"texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Дома", |
|||
"Menu:ContactUs": "Связаться с нами", |
|||
"Menu:ArticleSample": "Образец статьи", |
|||
"Home": "Дома", |
|||
"Welcome": "Добро пожаловать", |
|||
"LongWelcomeMessage": "Добро пожаловать в приложение. Это стартап-проект, основанный на структуре ABP. Для получения дополнительной информации посетите сайт", |
|||
"Date": "датировать", |
|||
"Permission:Dashboard": "Панель приборов", |
|||
"Menu:Dashboard": "Панель приборов", |
|||
"Menu:HomePage": "Домашняя страница", |
|||
"Dashboard": "Панель приборов", |
|||
"ExternalProvider:Google": "Google", |
|||
"ExternalProvider:Google:ClientId": "ID клиента", |
|||
"ExternalProvider:Google:ClientSecret": "Секрет клиента", |
|||
"ExternalProvider:Microsoft": "Майкрософт", |
|||
"ExternalProvider:Microsoft:ClientId": "ID клиента", |
|||
"ExternalProvider:Microsoft:ClientSecret": "Секрет клиента", |
|||
"ExternalProvider:Twitter": "Твиттер", |
|||
"ExternalProvider:Twitter:ConsumerKey": "Потребительский ключ", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "Потребительский секрет", |
|||
"NewsletterHeader": "Подпишитесь на рассылку!", |
|||
"NewsletterInfo": "Получайте информацию о последних событиях.", |
|||
"NewsletterPreference_Default": "Информационный бюллетень по умолчанию", |
|||
"NewsletterPrivacyAcceptMessage": "Я принимаю <a href='/privacy-policy'>Политику конфиденциальности</a>.", |
|||
"Language": "Язык", |
|||
"Search": "Поиск", |
|||
"LoadMore": "Загрузи больше", |
|||
"Settings": "Настройки", |
|||
"Theme": "Тема", |
|||
"DeviceTheme": "Тема устройства", |
|||
"Dark": "Темный", |
|||
"Light": "Свет", |
|||
"Unspecified": "Система", |
|||
"SeeAllUsers": "Просмотреть всех пользователей", |
|||
"TakePhoto": "Сделать фотографию", |
|||
"ChoosePhoto": "Выбрать фото" |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"culture": "sk", |
|||
"texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Domov", |
|||
"Menu:ContactUs": "Kontaktujte nás", |
|||
"Menu:ArticleSample": "Ukážka článku", |
|||
"Home": "Domov", |
|||
"Welcome": "Vitajte", |
|||
"LongWelcomeMessage": "Vitajte v aplikácii. Toto je štartovací projekt založený na ABP frameworku. Viac informácií nájdete na stránke", |
|||
"Date": "Dátum", |
|||
"Permission:Dashboard": "Dashboard", |
|||
"Menu:Dashboard": "Dashboard", |
|||
"Menu:HomePage": "Domovská stránka", |
|||
"Dashboard": "Dashboard", |
|||
"ExternalProvider:Google": "Google", |
|||
"ExternalProvider:Google:ClientId": "Client ID", |
|||
"ExternalProvider:Google:ClientSecret": "Client Secret", |
|||
"ExternalProvider:Microsoft": "Microsoft", |
|||
"ExternalProvider:Microsoft:ClientId": "Client ID", |
|||
"ExternalProvider:Microsoft:ClientSecret": "Client Secret", |
|||
"ExternalProvider:Twitter": "Twitter", |
|||
"ExternalProvider:Twitter:ConsumerKey": "Consumer Key", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "Consumer Secret", |
|||
"NewsletterHeader": "Prihláste sa na odber noviniek!", |
|||
"NewsletterInfo": "Získajte informácie o najnovšiom dianí.", |
|||
"NewsletterPreference_Default": "Predvolený odber noviniek", |
|||
"NewsletterPrivacyAcceptMessage": "Súhlasím so <a href='/privacy-policy'>Zásadami ochrany osobných údajov</a>.", |
|||
"Language": "Jazyk", |
|||
"Search": "Vyhľadávanie", |
|||
"LoadMore": "Načítať viac", |
|||
"Settings": "nastavenie", |
|||
"Theme": "Téma", |
|||
"DeviceTheme": "Téma zariadenia", |
|||
"Dark": "Tmavý", |
|||
"Light": "Svetlo", |
|||
"Unspecified": "Systém", |
|||
"SeeAllUsers": "Pozrite si Všetci používatelia", |
|||
"TakePhoto": "Odfoť", |
|||
"ChoosePhoto": "Vyberte fotografiu" |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"Culture": "sv", |
|||
"Texts": { |
|||
"AppName": "Bench", |
|||
"Menu:ContactUs": "Kontakta oss", |
|||
"Menu:ArticleSample": "Artikelexempel", |
|||
"Home": "Hem", |
|||
"Date": "Datum", |
|||
"Permission:Dashboard": "Dashboard", |
|||
"Menu:Dashboard": "Dashboard", |
|||
"Menu:HomePage": "Hemsida", |
|||
"Dashboard": "Dashboard", |
|||
"ExternalProvider:Google": "Google", |
|||
"ExternalProvider:Google:ClientId": "Klient-ID", |
|||
"ExternalProvider:Google:ClientSecret": "Klienthemlighet", |
|||
"ExternalProvider:Microsoft": "Microsoft", |
|||
"ExternalProvider:Microsoft:ClientId": "Klient-ID", |
|||
"ExternalProvider:Microsoft:ClientSecret": "Klienthemlighet", |
|||
"ExternalProvider:Twitter": "Twitter (X)", |
|||
"ExternalProvider:Twitter:ConsumerKey": "Konsumentnyckel", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "Konsumenthemlighet", |
|||
"NewsletterHeader": "Prenumerera på nyhetsbrevet!", |
|||
"NewsletterInfo": "Få information om de senaste händelserna.", |
|||
"NewsletterPreference_Default": "Standardnyhetsbrev", |
|||
"NewsletterPrivacyAcceptMessage": "Jag accepterar <a href='/privacy-policy'>Sekretesspolicy</a>.", |
|||
"Language": "Språk", |
|||
"Search": "Söka", |
|||
"LoadMore": "Ladda mer", |
|||
"Settings": "Inställningar", |
|||
"Theme": "Tema", |
|||
"DeviceTheme": "Enhetstema", |
|||
"Dark": "Mörk", |
|||
"Light": "Ljus", |
|||
"Unspecified": "System", |
|||
"SeeAllUsers": "Se Alla användare", |
|||
"TakePhoto": "Ta foto", |
|||
"ChoosePhoto": "Välj Foto", |
|||
"Menu:Home": "Hem", |
|||
"LongWelcomeMessage": "Välkommen till ansökan. ", |
|||
"Welcome": "Välkomna" |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"culture": "tr", |
|||
"texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Ana sayfa", |
|||
"Menu:ContactUs": "Bize Ulaşın", |
|||
"Menu:ArticleSample": "Yazı Örneği", |
|||
"Home": "Ana sayfa", |
|||
"Welcome": "Hoşgeldiniz", |
|||
"LongWelcomeMessage": "Uygulamaya hoşgeldiniz. Bu, ABP framework'ü üzerine bina edilmiş bir başlangıç projesidir. Daha fazla bilgi için ziyaret edebilirsiniz", |
|||
"Date": "Tarih", |
|||
"Permission:Dashboard": "Genel görünüm", |
|||
"Menu:Dashboard": "Genel görünüm", |
|||
"Menu:HomePage": "ana sayfa", |
|||
"Dashboard": "Genel görünüm", |
|||
"ExternalProvider:Google": "Google", |
|||
"ExternalProvider:Google:ClientId": "Client ID", |
|||
"ExternalProvider:Google:ClientSecret": "Client Secret", |
|||
"ExternalProvider:Microsoft": "Microsoft", |
|||
"ExternalProvider:Microsoft:ClientId": "Client ID", |
|||
"ExternalProvider:Microsoft:ClientSecret": "Client Secret", |
|||
"ExternalProvider:Twitter": "Twitter", |
|||
"ExternalProvider:Twitter:ConsumerKey": "Consumer Key", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "Consumer Secret", |
|||
"NewsletterHeader": "Bültene abone olun!", |
|||
"NewsletterInfo": "Son gelişmeler hakkında bilgi alın.", |
|||
"NewsletterPreference_Default": "Varsayılan Bülten", |
|||
"NewsletterPrivacyAcceptMessage": "<a href='/privacy-policy'>Gizlilik Politikası</a>'nı kabul ediyorum.", |
|||
"Language": "Dil", |
|||
"Search": "Ara", |
|||
"LoadMore": "Daha fazla yükle", |
|||
"Settings": "Ayarlar", |
|||
"Theme": "Tema", |
|||
"DeviceTheme": "Cihaz Teması", |
|||
"Dark": "Koyu", |
|||
"Light": "Açık", |
|||
"Unspecified": "Sistem", |
|||
"SeeAllUsers": "Tüm Kullanıcıları Gör", |
|||
"TakePhoto": "Fotoğraf Çek", |
|||
"ChoosePhoto": "Fotoğraf Seç" |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
{ |
|||
"culture": "zh-Hans", |
|||
"texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "首页", |
|||
"Menu:ContactUs": "联系我们", |
|||
"Menu:ArticleSample": "文章示例", |
|||
"Home": "首页", |
|||
"Welcome": "欢迎", |
|||
"LongWelcomeMessage": "欢迎使用本应用程序。这是一个基于 ABP 框架的启动项目。欲了解更多信息,请访问", |
|||
"Date": "日期", |
|||
"Permission:Dashboard": "仪表板", |
|||
"Menu:Dashboard": "仪表板", |
|||
"Menu:HomePage": "主页", |
|||
"Dashboard": "仪表板", |
|||
"ExternalProvider:Google": "Google", |
|||
"ExternalProvider:Google:ClientId": "Client Id", |
|||
"ExternalProvider:Google:ClientSecret": "Client Secret", |
|||
"ExternalProvider:Microsoft": "Microsoft", |
|||
"ExternalProvider:Microsoft:ClientId": "Client Id", |
|||
"ExternalProvider:Microsoft:ClientSecret": "Client Secret", |
|||
"ExternalProvider:Twitter": "Twitter", |
|||
"ExternalProvider:Twitter:ConsumerKey": "Consumer Key", |
|||
"ExternalProvider:Twitter:ConsumerSecret": "Consumer Secret", |
|||
"NewsletterHeader": "订阅时事通讯!", |
|||
"NewsletterInfo": "了解最新动态。", |
|||
"NewsletterPreference_Default": "默认通讯", |
|||
"NewsletterPrivacyAcceptMessage": "我接受<a href='/privacy-policy'>隐私政策</a>。", |
|||
"Language": "语言", |
|||
"Search": "搜索", |
|||
"LoadMore": "加载更多", |
|||
"Settings": "设置", |
|||
"Theme": "主题", |
|||
"DeviceTheme": "设备主题", |
|||
"Dark": "Dark", |
|||
"Light": "Light", |
|||
"Unspecified": "System", |
|||
"SeeAllUsers": "查看所有用户", |
|||
"TakePhoto": "拍摄照片", |
|||
"ChoosePhoto": "选择照片" |
|||
} |
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
{ |
|||
"Culture": "zh-Hant", |
|||
"Texts": { |
|||
"AppName": "Bench", |
|||
"Menu:Home": "Home", |
|||
"LongWelcomeMessage": "Welcome to the application. This is a startup project based on the ABP framework. For more information visit", |
|||
"Welcome": "Welcome" |
|||
} |
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
using Volo.Abp.Localization; |
|||
|
|||
namespace Bench.Localization; |
|||
|
|||
[LocalizationResourceName("Bench")] |
|||
public class BenchResource |
|||
{ |
|||
|
|||
} |
|||
@ -0,0 +1,10 @@ |
|||
namespace Bench.MultiTenancy; |
|||
|
|||
public static class MultiTenancyConsts |
|||
{ |
|||
/* Enable/disable multi-tenancy easily in a single point. |
|||
* If you will never need to multi-tenancy, you can remove |
|||
* related modules and code parts, including this file. |
|||
*/ |
|||
public const bool IsEnabled = true; |
|||
} |
|||
@ -0,0 +1,4 @@ |
|||
{ |
|||
"role": "lib.domain", |
|||
"projectId": "50c7be3b-5f75-4c21-bb3f-2355b7bcab01" |
|||
} |
|||
@ -0,0 +1,33 @@ |
|||
<Project Sdk="Microsoft.NET.Sdk"> |
|||
|
|||
<Import Project="..\..\common.props" /> |
|||
|
|||
<PropertyGroup> |
|||
<TargetFramework>net10.0</TargetFramework> |
|||
<Nullable>enable</Nullable> |
|||
<RootNamespace>Bench</RootNamespace> |
|||
</PropertyGroup> |
|||
|
|||
<ItemGroup> |
|||
<ProjectReference Include="..\Bench.Domain.Shared\Bench.Domain.Shared.csproj" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Volo.Abp.Emailing" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.Caching" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.PermissionManagement.Domain.Identity" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.PermissionManagement.Domain.OpenIddict" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.BackgroundJobs.Domain" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.AuditLogging.Domain" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.FeatureManagement.Domain" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.SettingManagement.Domain" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.BlobStoring.Database.Domain" Version="10.7.1" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Volo.Abp.OpenIddict.Domain" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.Identity.Domain" Version="10.7.1" /> |
|||
<PackageReference Include="Volo.Abp.TenantManagement.Domain" Version="10.7.1" /> |
|||
</ItemGroup> |
|||
|
|||
</Project> |
|||
@ -0,0 +1,11 @@ |
|||
using Volo.Abp.Identity; |
|||
|
|||
namespace Bench; |
|||
|
|||
public static class BenchConsts |
|||
{ |
|||
public const string DbTablePrefix = "App"; |
|||
public const string? DbSchema = null; |
|||
public const string AdminEmailDefaultValue = IdentityDataSeedContributor.AdminEmailDefaultValue; |
|||
public const string AdminPasswordDefaultValue = "1q2w3E*"; |
|||
} |
|||
@ -0,0 +1,53 @@ |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.DependencyInjection.Extensions; |
|||
using Bench.Localization; |
|||
using Bench.MultiTenancy; |
|||
using System; |
|||
using Volo.Abp.Localization; |
|||
using Volo.Abp.Modularity; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Volo.Abp.PermissionManagement.Identity; |
|||
using Volo.Abp.SettingManagement; |
|||
using Volo.Abp.BlobStoring.Database; |
|||
using Volo.Abp.Caching; |
|||
using Volo.Abp.OpenIddict; |
|||
using Volo.Abp.PermissionManagement.OpenIddict; |
|||
using Volo.Abp.AuditLogging; |
|||
using Volo.Abp.BackgroundJobs; |
|||
using Volo.Abp.Emailing; |
|||
using Volo.Abp.FeatureManagement; |
|||
using Volo.Abp.Identity; |
|||
using Volo.Abp.TenantManagement; |
|||
|
|||
namespace Bench; |
|||
|
|||
[DependsOn( |
|||
typeof(BenchDomainSharedModule), |
|||
typeof(AbpAuditLoggingDomainModule), |
|||
typeof(AbpCachingModule), |
|||
typeof(AbpBackgroundJobsDomainModule), |
|||
typeof(AbpFeatureManagementDomainModule), |
|||
typeof(AbpPermissionManagementDomainIdentityModule), |
|||
typeof(AbpPermissionManagementDomainOpenIddictModule), |
|||
typeof(AbpSettingManagementDomainModule), |
|||
typeof(AbpEmailingModule), |
|||
typeof(AbpIdentityDomainModule), |
|||
typeof(AbpOpenIddictDomainModule), |
|||
typeof(AbpTenantManagementDomainModule), |
|||
typeof(BlobStoringDatabaseDomainModule) )] |
|||
public class BenchDomainModule : AbpModule |
|||
{ |
|||
public override void ConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
Configure<AbpMultiTenancyOptions>(options => |
|||
{ |
|||
options.IsEnabled = MultiTenancyConsts.IsEnabled; |
|||
}); |
|||
|
|||
|
|||
|
|||
#if DEBUG
|
|||
context.Services.Replace(ServiceDescriptor.Singleton<IEmailSender, NullEmailSender>()); |
|||
#endif
|
|||
} |
|||
} |
|||
@ -0,0 +1,217 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Diagnostics; |
|||
using System.IO; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.Logging; |
|||
using Microsoft.Extensions.Logging.Abstractions; |
|||
using Volo.Abp.Data; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.Identity; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Bench.MultiTenancy; |
|||
using Volo.Abp.TenantManagement; |
|||
|
|||
namespace Bench.Data; |
|||
|
|||
public class BenchDbMigrationService : ITransientDependency |
|||
{ |
|||
public ILogger<BenchDbMigrationService> Logger { get; set; } |
|||
|
|||
private readonly IDataSeeder _dataSeeder; |
|||
private readonly IEnumerable<IBenchDbSchemaMigrator> _dbSchemaMigrators; |
|||
private readonly ITenantRepository _tenantRepository; |
|||
private readonly ICurrentTenant _currentTenant; |
|||
|
|||
public BenchDbMigrationService( |
|||
IDataSeeder dataSeeder, |
|||
ITenantRepository tenantRepository, |
|||
ICurrentTenant currentTenant, |
|||
IEnumerable<IBenchDbSchemaMigrator> dbSchemaMigrators) |
|||
{ |
|||
_dataSeeder = dataSeeder; |
|||
_tenantRepository = tenantRepository; |
|||
_currentTenant = currentTenant; |
|||
_dbSchemaMigrators = dbSchemaMigrators; |
|||
|
|||
Logger = NullLogger<BenchDbMigrationService>.Instance; |
|||
} |
|||
|
|||
public async Task MigrateAsync() |
|||
{ |
|||
var initialMigrationAdded = AddInitialMigrationIfNotExist(); |
|||
|
|||
if (initialMigrationAdded) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
Logger.LogInformation("Started database migrations..."); |
|||
|
|||
await MigrateDatabaseSchemaAsync(); |
|||
await SeedDataAsync(); |
|||
|
|||
Logger.LogInformation($"Successfully completed host database migrations."); |
|||
|
|||
if (MultiTenancyConsts.IsEnabled) |
|||
{ |
|||
|
|||
var tenants = await _tenantRepository.GetListAsync(includeDetails: true); |
|||
|
|||
var migratedDatabaseSchemas = new HashSet<string>(); |
|||
foreach (var tenant in tenants) |
|||
{ |
|||
using (_currentTenant.Change(tenant.Id)) |
|||
{ |
|||
if (tenant.ConnectionStrings.Any()) |
|||
{ |
|||
var tenantConnectionStrings = tenant.ConnectionStrings |
|||
.Select(x => x.Value) |
|||
.ToList(); |
|||
|
|||
if (!migratedDatabaseSchemas.IsSupersetOf(tenantConnectionStrings)) |
|||
{ |
|||
await MigrateDatabaseSchemaAsync(tenant); |
|||
|
|||
migratedDatabaseSchemas.AddIfNotContains(tenantConnectionStrings); |
|||
} |
|||
} |
|||
|
|||
await SeedDataAsync(tenant); |
|||
} |
|||
|
|||
Logger.LogInformation($"Successfully completed {tenant.Name} tenant database migrations."); |
|||
} |
|||
|
|||
Logger.LogInformation("Successfully completed all database migrations."); |
|||
} |
|||
Logger.LogInformation("You can safely end this process..."); |
|||
} |
|||
|
|||
private async Task MigrateDatabaseSchemaAsync(Tenant? tenant = null) |
|||
{ |
|||
Logger.LogInformation( |
|||
$"Migrating schema for {(tenant == null ? "host" : tenant.Name + " tenant")} database..."); |
|||
|
|||
foreach (var migrator in _dbSchemaMigrators) |
|||
{ |
|||
await migrator.MigrateAsync(); |
|||
} |
|||
} |
|||
|
|||
private async Task SeedDataAsync(Tenant? tenant = null) |
|||
{ |
|||
Logger.LogInformation($"Executing {(tenant == null ? "host" : tenant.Name + " tenant")} database seed..."); |
|||
|
|||
await _dataSeeder.SeedAsync(new DataSeedContext(tenant?.Id) |
|||
.WithProperty(IdentityDataSeedContributor.AdminEmailPropertyName, |
|||
BenchConsts.AdminEmailDefaultValue) |
|||
.WithProperty(IdentityDataSeedContributor.AdminPasswordPropertyName, |
|||
BenchConsts.AdminPasswordDefaultValue) |
|||
); |
|||
} |
|||
|
|||
private bool AddInitialMigrationIfNotExist() |
|||
{ |
|||
try |
|||
{ |
|||
if (!DbMigrationsProjectExists()) |
|||
{ |
|||
return false; |
|||
} |
|||
} |
|||
catch (Exception) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
try |
|||
{ |
|||
if (!MigrationsFolderExists()) |
|||
{ |
|||
AddInitialMigration(); |
|||
return true; |
|||
} |
|||
else |
|||
{ |
|||
return false; |
|||
} |
|||
} |
|||
catch (Exception e) |
|||
{ |
|||
Logger.LogWarning("Couldn't determinate if any migrations exist : " + e.Message); |
|||
return false; |
|||
} |
|||
} |
|||
|
|||
private bool DbMigrationsProjectExists() |
|||
{ |
|||
var dbMigrationsProjectFolder = GetEntityFrameworkCoreProjectFolderPath(); |
|||
|
|||
return dbMigrationsProjectFolder != null; |
|||
} |
|||
|
|||
private bool MigrationsFolderExists() |
|||
{ |
|||
var dbMigrationsProjectFolder = GetEntityFrameworkCoreProjectFolderPath(); |
|||
|
|||
return dbMigrationsProjectFolder != null && Directory.Exists(Path.Combine(dbMigrationsProjectFolder, "Migrations")); |
|||
} |
|||
|
|||
private void AddInitialMigration() |
|||
{ |
|||
Logger.LogInformation("Creating initial migration..."); |
|||
|
|||
var procStartInfo = new ProcessStartInfo |
|||
{ |
|||
FileName = "abp", |
|||
ArgumentList = |
|||
{ |
|||
"create-migration-and-run-migrator", |
|||
GetEntityFrameworkCoreProjectFolderPath()! |
|||
} |
|||
}; |
|||
|
|||
try |
|||
{ |
|||
Process.Start(procStartInfo); |
|||
} |
|||
catch (Exception) |
|||
{ |
|||
throw new Exception("Couldn't run ABP CLI..."); |
|||
} |
|||
} |
|||
|
|||
private string? GetEntityFrameworkCoreProjectFolderPath() |
|||
{ |
|||
var slnDirectoryPath = GetSolutionDirectoryPath(); |
|||
|
|||
if (slnDirectoryPath == null) |
|||
{ |
|||
throw new Exception("Solution folder not found!"); |
|||
} |
|||
|
|||
var srcDirectoryPath = Path.Combine(slnDirectoryPath, "src"); |
|||
|
|||
return Directory.GetDirectories(srcDirectoryPath) |
|||
.FirstOrDefault(d => d.EndsWith(".EntityFrameworkCore")); |
|||
} |
|||
|
|||
private string? GetSolutionDirectoryPath() |
|||
{ |
|||
var currentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory()); |
|||
|
|||
while (currentDirectory != null && Directory.GetParent(currentDirectory.FullName) != null) |
|||
{ |
|||
currentDirectory = Directory.GetParent(currentDirectory.FullName); |
|||
|
|||
if (currentDirectory != null && Directory.GetFiles(currentDirectory.FullName).FirstOrDefault(f => f.EndsWith(".sln") || f.EndsWith(".slnx")) != null) |
|||
{ |
|||
return currentDirectory.FullName; |
|||
} |
|||
} |
|||
|
|||
return null; |
|||
} |
|||
} |
|||
@ -0,0 +1,8 @@ |
|||
using System.Threading.Tasks; |
|||
|
|||
namespace Bench.Data; |
|||
|
|||
public interface IBenchDbSchemaMigrator |
|||
{ |
|||
Task MigrateAsync(); |
|||
} |
|||
@ -0,0 +1,15 @@ |
|||
using System.Threading.Tasks; |
|||
using Volo.Abp.DependencyInjection; |
|||
|
|||
namespace Bench.Data; |
|||
|
|||
/* This is used if database provider does't define |
|||
* IBenchDbSchemaMigrator implementation. |
|||
*/ |
|||
public class NullBenchDbSchemaMigrator : IBenchDbSchemaMigrator, ITransientDependency |
|||
{ |
|||
public Task MigrateAsync() |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
} |
|||
@ -0,0 +1,34 @@ |
|||
using Volo.Abp.Identity.Settings; |
|||
using Volo.Abp.Settings; |
|||
|
|||
namespace Bench.Identity; |
|||
|
|||
public class ChangeIdentityPasswordPolicySettingDefinitionProvider : SettingDefinitionProvider |
|||
{ |
|||
public override void Define(ISettingDefinitionContext context) |
|||
{ |
|||
var requireNonAlphanumeric = context.GetOrNull(IdentitySettingNames.Password.RequireNonAlphanumeric); |
|||
if (requireNonAlphanumeric != null) |
|||
{ |
|||
requireNonAlphanumeric.DefaultValue = false.ToString(); |
|||
} |
|||
|
|||
var requireLowercase = context.GetOrNull(IdentitySettingNames.Password.RequireLowercase); |
|||
if (requireLowercase != null) |
|||
{ |
|||
requireLowercase.DefaultValue = false.ToString(); |
|||
} |
|||
|
|||
var requireUppercase = context.GetOrNull(IdentitySettingNames.Password.RequireUppercase); |
|||
if (requireUppercase != null) |
|||
{ |
|||
requireUppercase.DefaultValue = false.ToString(); |
|||
} |
|||
|
|||
var requireDigit = context.GetOrNull(IdentitySettingNames.Password.RequireDigit); |
|||
if (requireDigit != null) |
|||
{ |
|||
requireDigit.DefaultValue = false.ToString(); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,119 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.Configuration; |
|||
using OpenIddict.Abstractions; |
|||
using Volo.Abp.Data; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.OpenIddict; |
|||
using Volo.Abp.OpenIddict.Applications; |
|||
using Volo.Abp.OpenIddict.Scopes; |
|||
using Volo.Abp.Uow; |
|||
|
|||
namespace Bench.OpenIddict; |
|||
|
|||
/* Creates initial data that is needed to property run the application |
|||
* and make client-to-server communication possible. |
|||
*/ |
|||
public class OpenIddictDataSeedContributor : OpenIddictDataSeedContributorBase, IDataSeedContributor, ITransientDependency |
|||
{ |
|||
public OpenIddictDataSeedContributor( |
|||
IConfiguration configuration, |
|||
IOpenIddictApplicationRepository openIddictApplicationRepository, |
|||
IAbpApplicationManager applicationManager, |
|||
IOpenIddictScopeRepository openIddictScopeRepository, |
|||
IOpenIddictScopeManager scopeManager) |
|||
: base(configuration, openIddictApplicationRepository, applicationManager, openIddictScopeRepository, scopeManager) |
|||
{ |
|||
} |
|||
|
|||
[UnitOfWork] |
|||
public virtual async Task SeedAsync(DataSeedContext context) |
|||
{ |
|||
await CreateScopesAsync(); |
|||
await CreateApplicationsAsync(); |
|||
} |
|||
|
|||
private async Task CreateScopesAsync() |
|||
{ |
|||
await CreateScopesAsync(new OpenIddictScopeDescriptor |
|||
{ |
|||
Name = "Bench", |
|||
DisplayName = "Bench API", |
|||
Resources = { "Bench" } |
|||
}); |
|||
} |
|||
|
|||
private async Task CreateApplicationsAsync() |
|||
{ |
|||
var commonScopes = new List<string> { |
|||
OpenIddictConstants.Permissions.Scopes.Address, |
|||
OpenIddictConstants.Permissions.Scopes.Email, |
|||
OpenIddictConstants.Permissions.Scopes.Phone, |
|||
OpenIddictConstants.Permissions.Scopes.Profile, |
|||
OpenIddictConstants.Permissions.Scopes.Roles, |
|||
"Bench" |
|||
}; |
|||
|
|||
var configurationSection = Configuration.GetSection("OpenIddict:Applications"); |
|||
|
|||
|
|||
// Console Test / Angular Client
|
|||
|
|||
var appClientId = configurationSection["Bench_App:ClientId"]; |
|||
if (!appClientId.IsNullOrWhiteSpace()) |
|||
{ |
|||
var appClientRootUrl = configurationSection["Bench_App:RootUrl"]?.TrimEnd('/'); |
|||
await CreateOrUpdateApplicationAsync( |
|||
applicationType: OpenIddictConstants.ApplicationTypes.Web, |
|||
name: appClientId!, |
|||
type: OpenIddictConstants.ClientTypes.Public, |
|||
consentType: OpenIddictConstants.ConsentTypes.Implicit, |
|||
displayName: "Console Test / Angular Application", |
|||
secret: null, |
|||
grantTypes: new List<string> { |
|||
OpenIddictConstants.GrantTypes.AuthorizationCode, |
|||
OpenIddictConstants.GrantTypes.Password, |
|||
OpenIddictConstants.GrantTypes.ClientCredentials, |
|||
OpenIddictConstants.GrantTypes.RefreshToken, |
|||
"LinkLogin", |
|||
"Impersonation" |
|||
}, |
|||
scopes: commonScopes, |
|||
redirectUris: new List<string> { appClientRootUrl }, |
|||
postLogoutRedirectUris: new List<string> { appClientRootUrl }, |
|||
clientUri: appClientRootUrl, |
|||
logoUri: "/images/clients/angular.svg" |
|||
); |
|||
} |
|||
|
|||
|
|||
|
|||
|
|||
|
|||
|
|||
|
|||
// Swagger Client
|
|||
var swaggerClientId = configurationSection["Bench_Swagger:ClientId"]; |
|||
if (!swaggerClientId.IsNullOrWhiteSpace()) |
|||
{ |
|||
var swaggerRootUrl = configurationSection["Bench_Swagger:RootUrl"]?.TrimEnd('/'); |
|||
|
|||
await CreateOrUpdateApplicationAsync( |
|||
applicationType: OpenIddictConstants.ApplicationTypes.Web, |
|||
name: swaggerClientId!, |
|||
type: OpenIddictConstants.ClientTypes.Public, |
|||
consentType: OpenIddictConstants.ConsentTypes.Implicit, |
|||
displayName: "Swagger Application", |
|||
secret: null, |
|||
grantTypes: new List<string> { OpenIddictConstants.GrantTypes.AuthorizationCode, }, |
|||
scopes: commonScopes, |
|||
redirectUris: new List<string> { $"{swaggerRootUrl}/swagger/oauth2-redirect.html" }, |
|||
clientUri: swaggerRootUrl.EnsureEndsWith('/') + "swagger", |
|||
logoUri: "/images/clients/swagger.svg" |
|||
); |
|||
} |
|||
|
|||
|
|||
} |
|||
} |
|||
@ -0,0 +1,3 @@ |
|||
using System.Runtime.CompilerServices; |
|||
[assembly:InternalsVisibleToAttribute("Bench.Domain.Tests")] |
|||
[assembly:InternalsVisibleToAttribute("Bench.TestBase")] |
|||
@ -0,0 +1,12 @@ |
|||
using Volo.Abp.Settings; |
|||
|
|||
namespace Bench.Settings; |
|||
|
|||
public class BenchSettingDefinitionProvider : SettingDefinitionProvider |
|||
{ |
|||
public override void Define(ISettingDefinitionContext context) |
|||
{ |
|||
//Define your own settings here. Example:
|
|||
//context.Add(new SettingDefinition(BenchSettings.MySetting1));
|
|||
} |
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
namespace Bench.Settings; |
|||
|
|||
public static class BenchSettings |
|||
{ |
|||
private const string Prefix = "Bench"; |
|||
|
|||
//Add your own setting names here. Example:
|
|||
//public const string MySetting1 = Prefix + ".MySetting1";
|
|||
} |
|||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue