diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..618638d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +root = true + +[*] +charset = utf-8 +end_of_line = crlf +insert_final_newline = true + +[*.{cs,csproj,props,targets,sln}] +indent_style = space +indent_size = 4 + +[*.{json,yml,yaml,md}] +indent_style = space +indent_size = 2 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3ac92b7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +* text=auto eol=crlf + +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.ico binary +*.nupkg binary +*.snupkg binary diff --git a/.github/actions/setup-dotnet/action.yml b/.github/actions/setup-dotnet/action.yml deleted file mode 100644 index d93b008..0000000 --- a/.github/actions/setup-dotnet/action.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: 'Setup .NET' -description: 'Setup .NET SDK with specified versions' - -runs: - using: "composite" - steps: - - name: Setup .NET - uses: actions/setup-dotnet@v4 - with: - dotnet-version: | - 3.1.x - 5.0.x - 6.0.x - 7.0.x - 8.0.x - 9.0.x diff --git a/.github/actions/setup-env/action.yml b/.github/actions/setup-env/action.yml new file mode 100644 index 0000000..f982081 --- /dev/null +++ b/.github/actions/setup-env/action.yml @@ -0,0 +1,20 @@ +name: Setup Environment +description: Sets up the .NET SDK used to build and test the repository + +inputs: + dotnet-version: + description: One or more .NET SDK channels to install + required: false + default: 10.0.x + +runs: + using: composite + steps: + - name: Set up .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: ${{ inputs.dotnet-version }} + + - name: Show .NET information + shell: bash + run: dotnet --info diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..c1eae9e --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1 @@ +Always add XML documents in English. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..c78c9d8 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,114 @@ +name: Publish NuGet Packages + +on: + workflow_dispatch: + inputs: + version: + description: Optional package version; defaults to the project version + required: false + type: string + release: + types: + - published + +concurrency: + group: publish-nuget + cancel-in-progress: false + +env: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: true + +jobs: + compatibility-test: + permissions: + contents: read + runs-on: windows-latest + timeout-minutes: 30 + + steps: + - name: Checkout code + uses: actions/checkout@v7 + with: + persist-credentials: false + + - uses: ./.github/actions/setup-env + with: + dotnet-version: | + 3.1.x + 5.0.x + 6.0.x + 7.0.x + 8.0.x + 9.0.x + 10.0.x + + - name: Restore dependencies + run: dotnet restore Ling.Audit.sln + + - name: Build + run: dotnet build Ling.Audit.sln --configuration Release --no-restore -p:ContinuousIntegrationBuild=true + + - name: Run tests on their target runtimes + run: dotnet test Ling.Audit.sln --configuration Release --no-build --no-restore --verbosity normal + + publish: + needs: compatibility-test + environment: production + # MSBuild imports environment variables as properties. Do not name this PackageVersion: + # release tags conventionally start with "v", which makes restore fail before pack can strip it. + env: + NUGET_DIRECTORY: ${{ github.workspace }}/artifacts/packages + RELEASE_VERSION: ${{ github.event.release.tag_name || inputs.version }} + permissions: + contents: read + id-token: write + runs-on: ubuntu-latest + timeout-minutes: 25 + + steps: + - name: Checkout code + uses: actions/checkout@v7 + with: + persist-credentials: false + + - uses: ./.github/actions/setup-env + + - name: Restore dependencies + run: dotnet restore Ling.Audit.sln + + - name: Pack + shell: bash + run: | + version="${RELEASE_VERSION#v}" + for project in \ + src/Ling.Audit/Ling.Audit.csproj \ + src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj \ + src/Ling.Audit.AspNetCore/Ling.Audit.AspNetCore.csproj + do + arguments=("$project" --configuration Release --no-restore \ + --output "$NUGET_DIRECTORY" -p:ContinuousIntegrationBuild=true) + if [ -n "$version" ]; then arguments+=("-p:Version=$version"); fi + dotnet pack "${arguments[@]}" + done + + - name: NuGet login (OIDC to temporary API key) + uses: NuGet/login@v1 + id: login + with: + user: ${{ secrets.NUGET_USER }} + + - name: Publish to NuGet.org + shell: bash + run: | + packages=$(find "$NUGET_DIRECTORY" -maxdepth 1 -name '*.nupkg' ! -name '*.snupkg' -print) + if [ -z "$packages" ]; then + echo "No NuGet package was produced." >&2 + exit 1 + fi + while IFS= read -r package; do + dotnet nuget push "$package" \ + --api-key "${{ steps.login.outputs.NUGET_API_KEY }}" \ + --source https://api.nuget.org/v3/index.json \ + --skip-duplicate + done <<< "$packages" diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml deleted file mode 100644 index 7fbdde7..0000000 --- a/.github/workflows/pull-request.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: Pull Request - -on: - pull_request: - branches: - - '*' - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - - uses: ./.github/actions/setup-dotnet - - - name: Run tests - run: dotnet test --configuration Release diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 2ec2ac0..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Release - -on: - release: - types: - - published - -env: - NuGetDirectory: ${{ github.workspace }}/nuget - -jobs: - publish: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - - uses: ./.github/actions/setup-dotnet - - - name: Pack - run: dotnet pack ./src/Ling.Audit/Ling.Audit.csproj --configuration Release --output ${{ env.NuGetDirectory }} - - - name: Publish to NuGet - run: | - for file in ${{ env.NuGetDirectory }}/*.{nupkg,snupkg}; do - if [ -f "$file" ]; then - dotnet nuget push "$file" --api-key "${{ secrets.NUGET_APIKEY }}" --source https://api.nuget.org/v3/index.json --skip-duplicate - fi - done diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..f53445b --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,114 @@ +name: Build and Test + +on: + workflow_dispatch: + push: + branches: + - master + - develop + pull_request: + branches: + - master + - develop + +concurrency: + group: test-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +env: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: true + NUGET_DIRECTORY: ${{ github.workspace }}/artifacts/packages + +jobs: + test: + permissions: + contents: read + runs-on: ubuntu-latest + timeout-minutes: 25 + + steps: + - name: Checkout code + uses: actions/checkout@v7 + with: + persist-credentials: false + + - uses: ./.github/actions/setup-env + + - name: Restore dependencies + run: dotnet restore Ling.Audit.sln + + - name: Build + run: dotnet build Ling.Audit.sln --configuration Release --no-restore -p:ContinuousIntegrationBuild=true + + - name: Verify NuGet packages can be created + shell: bash + run: | + for project in \ + src/Ling.Audit/Ling.Audit.csproj \ + src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj \ + src/Ling.Audit.AspNetCore/Ling.Audit.AspNetCore.csproj + do + dotnet pack "$project" --configuration Release --no-build --no-restore \ + --output "$NUGET_DIRECTORY" -p:ContinuousIntegrationBuild=true + done + + - name: Verify package boundaries + shell: bash + run: | + core=$(find "$NUGET_DIRECTORY" -maxdepth 1 -name 'Ling.Audit.*.nupkg' \ + ! -name '*.EntityFrameworkCore.*' ! -name '*.AspNetCore.*' ! -name '*.snupkg' -print -quit) + efcore=$(find "$NUGET_DIRECTORY" -maxdepth 1 -name 'Ling.Audit.EntityFrameworkCore.*.nupkg' \ + ! -name '*.snupkg' -print -quit) + aspnetcore=$(find "$NUGET_DIRECTORY" -maxdepth 1 -name 'Ling.Audit.AspNetCore.*.nupkg' \ + ! -name '*.snupkg' -print -quit) + + test -n "$core" + test -n "$efcore" + test -n "$aspnetcore" + + unzip -Z1 "$core" | grep -Fx 'analyzers/dotnet/cs/Ling.Audit.SourceGenerators.dll' + unzip -Z1 "$core" | grep -Fx 'lib/netstandard2.0/Ling.Audit.dll' + unzip -Z1 "$efcore" | grep -Fx 'lib/net6.0/Ling.Audit.EntityFrameworkCore.dll' + unzip -Z1 "$efcore" | grep -Fx 'lib/net9.0/Ling.Audit.EntityFrameworkCore.dll' + unzip -Z1 "$aspnetcore" | grep -Fx 'lib/net6.0/Ling.Audit.AspNetCore.dll' + unzip -Z1 "$aspnetcore" | grep -Fx 'lib/net9.0/Ling.Audit.AspNetCore.dll' + + - name: Verify package consumption + run: | + dotnet restore tests/Ling.Audit.PackageConsumer/Ling.Audit.PackageConsumer.csproj \ + --configfile tests/Ling.Audit.PackageConsumer/NuGet.config + dotnet build tests/Ling.Audit.PackageConsumer/Ling.Audit.PackageConsumer.csproj \ + --configuration Release --no-restore + + compatibility-test: + permissions: + contents: read + runs-on: windows-latest + timeout-minutes: 30 + + steps: + - name: Checkout code + uses: actions/checkout@v7 + with: + persist-credentials: false + + - uses: ./.github/actions/setup-env + with: + dotnet-version: | + 3.1.x + 5.0.x + 6.0.x + 7.0.x + 8.0.x + 9.0.x + 10.0.x + + - name: Restore dependencies + run: dotnet restore Ling.Audit.sln + + - name: Build + run: dotnet build Ling.Audit.sln --configuration Release --no-restore -p:ContinuousIntegrationBuild=true + + - name: Run tests on their target runtimes + run: dotnet test Ling.Audit.sln --configuration Release --no-build --no-restore --verbosity normal diff --git a/Ling.Audit.sln b/Ling.Audit.sln index 8f48dca..fbe94b1 100644 --- a/Ling.Audit.sln +++ b/Ling.Audit.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.31903.59 +# Visual Studio Version 18 +VisualStudioVersion = 18.0.11201.2 d18.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{BB2FED91-147D-47A5-9F12-87B30AF8B772}" ProjectSection(SolutionItems) = preProject @@ -16,6 +16,21 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{8572F9E1 EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ling.Audit.SourceGenerators.Tests", "tests\Ling.Audit.SourceGenerators.Tests\Ling.Audit.SourceGenerators.Tests.csproj", "{AD209C64-6C95-43A3-85CA-5EFDFF059DEF}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ling.Audit.EntityFrameworkCore", "src\Ling.Audit.EntityFrameworkCore\Ling.Audit.EntityFrameworkCore.csproj", "{49EC8F86-4D37-4880-B8C4-A9F49C4CA871}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ling.Audit.AspNetCore", "src\Ling.Audit.AspNetCore\Ling.Audit.AspNetCore.csproj", "{D168B363-6EFB-45D3-8BD8-BABADE073444}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ling.Audit.EntityFrameworkCore.Tests", "tests\Ling.Audit.EntityFrameworkCore.Tests1\Ling.Audit.EntityFrameworkCore.Tests.csproj", "{05BEB921-D67B-4F40-9334-E176127F37C0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ling.Audit.AspNetCore.Tests", "tests\Ling.Audit.AspNetCore.Tests\Ling.Audit.AspNetCore.Tests.csproj", "{7406F507-6A52-49B3-8F67-8E72BC6506E5}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "git", "git", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}" + ProjectSection(SolutionItems) = preProject + .gitignore = .gitignore + LICENSE = LICENSE + README.md = README.md + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -34,6 +49,22 @@ Global {AD209C64-6C95-43A3-85CA-5EFDFF059DEF}.Debug|Any CPU.Build.0 = Debug|Any CPU {AD209C64-6C95-43A3-85CA-5EFDFF059DEF}.Release|Any CPU.ActiveCfg = Release|Any CPU {AD209C64-6C95-43A3-85CA-5EFDFF059DEF}.Release|Any CPU.Build.0 = Release|Any CPU + {49EC8F86-4D37-4880-B8C4-A9F49C4CA871}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {49EC8F86-4D37-4880-B8C4-A9F49C4CA871}.Debug|Any CPU.Build.0 = Debug|Any CPU + {49EC8F86-4D37-4880-B8C4-A9F49C4CA871}.Release|Any CPU.ActiveCfg = Release|Any CPU + {49EC8F86-4D37-4880-B8C4-A9F49C4CA871}.Release|Any CPU.Build.0 = Release|Any CPU + {D168B363-6EFB-45D3-8BD8-BABADE073444}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D168B363-6EFB-45D3-8BD8-BABADE073444}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D168B363-6EFB-45D3-8BD8-BABADE073444}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D168B363-6EFB-45D3-8BD8-BABADE073444}.Release|Any CPU.Build.0 = Release|Any CPU + {05BEB921-D67B-4F40-9334-E176127F37C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {05BEB921-D67B-4F40-9334-E176127F37C0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {05BEB921-D67B-4F40-9334-E176127F37C0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {05BEB921-D67B-4F40-9334-E176127F37C0}.Release|Any CPU.Build.0 = Release|Any CPU + {7406F507-6A52-49B3-8F67-8E72BC6506E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7406F507-6A52-49B3-8F67-8E72BC6506E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7406F507-6A52-49B3-8F67-8E72BC6506E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7406F507-6A52-49B3-8F67-8E72BC6506E5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -42,5 +73,12 @@ Global {B1C735B7-5F67-4F65-9A5D-9E30B046934D} = {BB2FED91-147D-47A5-9F12-87B30AF8B772} {ADF318B0-2EB4-405C-B93A-DC23346655C9} = {BB2FED91-147D-47A5-9F12-87B30AF8B772} {AD209C64-6C95-43A3-85CA-5EFDFF059DEF} = {8572F9E1-6926-42F1-BE77-41EFE1775C40} + {49EC8F86-4D37-4880-B8C4-A9F49C4CA871} = {BB2FED91-147D-47A5-9F12-87B30AF8B772} + {D168B363-6EFB-45D3-8BD8-BABADE073444} = {BB2FED91-147D-47A5-9F12-87B30AF8B772} + {05BEB921-D67B-4F40-9334-E176127F37C0} = {8572F9E1-6926-42F1-BE77-41EFE1775C40} + {7406F507-6A52-49B3-8F67-8E72BC6506E5} = {8572F9E1-6926-42F1-BE77-41EFE1775C40} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {523730A8-DA1E-4D7D-BF87-DB79B2F060F4} EndGlobalSection EndGlobal diff --git a/README.md b/README.md index ec1d671..52871d6 100644 --- a/README.md +++ b/README.md @@ -1,51 +1,288 @@ -# Ling.Audit [![NuGet](https://img.shields.io/nuget/v/Ling.Audit.svg)](https://www.nuget.org/packages/Ling.Audit/) +# Ling.Audit -A source generator for automatically implementing audit properties in C# classes. +English | [简体中文](README.zh-CN.md) + +`Ling.Audit` adds strongly typed audit properties to domain entities at compile time, maintains them through Entity Framework Core, and can resolve the current user and request information from ASP.NET Core. The core contracts remain independent of EF Core and ASP.NET Core, so applications can adopt only the layers they need. + +## Packages + +| Package | Purpose | Target frameworks | +| --- | --- | --- | +| [`Ling.Audit`](https://www.nuget.org/packages/Ling.Audit/) [![NuGet](https://img.shields.io/nuget/v/Ling.Audit.svg)](https://www.nuget.org/packages/Ling.Audit/) | Audit contracts, source generator, analyzers, and code fixes. | .NET Standard 2.0/2.1, .NET Core 3.1, .NET 5–9 | +| [`Ling.Audit.EntityFrameworkCore`](https://www.nuget.org/packages/Ling.Audit.EntityFrameworkCore/) [![NuGet](https://img.shields.io/nuget/v/Ling.Audit.EntityFrameworkCore.svg)](https://www.nuget.org/packages/Ling.Audit.EntityFrameworkCore/) | Audit-property maintenance, soft deletion, and entity/field change logs. | .NET 6–9 | +| [`Ling.Audit.AspNetCore`](https://www.nuget.org/packages/Ling.Audit.AspNetCore/) [![NuGet](https://img.shields.io/nuget/v/Ling.Audit.AspNetCore.svg)](https://www.nuget.org/packages/Ling.Audit.AspNetCore/) | User, IP address, and client information from the current HTTP request. | .NET 6–9 | + +The EF Core and ASP.NET Core packages reference the matching EF Core major version for each target framework. ## Features -- 🚀 Zero runtime overhead - all code is generated at compile time -- 💡 Analyzer and code fixes for better audit interface usage -- 🔄 Supports inheritance and nested types -- 🛡️ Full type safety with generic support -- 📝 XML documentation included +- Generates audit properties at compile time without reflection or runtime proxies. +- Provides focused interfaces for creation, modification, deletion, and full auditing. +- Supports classes, records, generic types, inheritance, and nested partial types. +- Reports invalid audit declarations through compiler diagnostics and code fixes. +- Automatically maintains audit fields during `SaveChanges`. +- Converts audited deletes into soft deletes and composes the soft-delete filter with existing query filters. +- Records entity-level and field-level changes, including composite and shadow primary keys. +- Resolves claims from ASP.NET Core Identity, JWT Bearer, OpenID Connect, and custom authentication schemes. +- Supports custom user providers, principal resolvers, serializers, anonymous handlers, and time providers. +- Offers an explicit-transaction mode when business changes and audit logs must commit atomically. -## Quick Start +## Quick start + +Install the core package in the project that owns the entity types: ```shell -dotnet add package Ling.Audit +dotnet add package Ling.Audit --version 2.0.1 +``` + +Implement the audit interface that matches the entity lifecycle. The type and every containing type must be `partial`: + +```csharp +using Ling.Audit; + +namespace MyApplication.Domain; + +public sealed partial class Post : IFullAudited +{ + public int Id { get; set; } + public string Title { get; set; } = string.Empty; +} +``` + +The source generator supplies the interface properties in the same compilation: + +```csharp +public sealed partial class Post +{ + public string? CreatedBy { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public string? LastModifiedBy { get; set; } + public DateTimeOffset? LastModifiedAt { get; set; } + public bool IsDeleted { get; set; } + public string? DeletedBy { get; set; } + public DateTimeOffset? DeletedAt { get; set; } +} +``` + +Use a basic interface for one value, or a composite interface for a complete lifecycle: + +| Interface | Generated properties | +| --- | --- | +| `IHasCreator` | `CreatedBy` | +| `IHasCreationTime` | `CreatedAt` | +| `IHasModifier` | `LastModifiedBy` | +| `IHasModificationTime` | `LastModifiedAt` | +| `ISoftDelete` | `IsDeleted` | +| `IHasDeleter` | `DeletedBy` | +| `IHasDeletionTime` | `DeletedAt` | +| `ICreationAudited` | `CreatedBy`, `CreatedAt` | +| `IModificationAudited` | `LastModifiedBy`, `LastModifiedAt` | +| `IDeletionAudited` | `IsDeleted`, `DeletedBy`, `DeletedAt` | +| `IFullAudited` | All creation, modification, and deletion properties | + +## Entity Framework Core + +Install the integration that matches the application's target framework: + +```shell +dotnet add package Ling.Audit.EntityFrameworkCore --version 2.0.1 +``` + +Create a provider for the current user and client context: + +```csharp +using Ling.Audit.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; + +public sealed class ApplicationAuditUserProvider( + ICurrentDbContext currentDbContext) + : AuditContextProviderBase(currentDbContext) +{ + protected override AuditContext? GetAuditContext() + { + var currentUser = GetService(); + + return currentUser?.Id is { } id + ? new AuditContext(id, currentUser.Name, null, null) + : null; + } +} ``` +Register auditing while configuring the `DbContext`: + ```csharp -// Just implement the interface -public partial class Post : IFullAudited +services.AddDbContext(options => +{ + options.UseSqlServer(connectionString); + options.UseAudit(); +}); +``` + +Mark only entities whose changes should be written to the audit-log tables. Properties are included by default and can be excluded individually: + +```csharp +using Ling.Audit.EntityFrameworkCore; + +[Auditable] +public sealed partial class Account : IFullAudited { - public string Title { get; set; } - public string Content { get; set; } + public Guid Id { get; set; } + public string DisplayName { get; set; } = string.Empty; + + [NotAudited] + public string PasswordHash { get; set; } = string.Empty; } +``` + +The same configuration is available through the model builder: + +```csharp +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity().IsAuditable(); + modelBuilder.Entity() + .Property(account => account.PasswordHash) + .IsNotAudited(); -// All audit properties are automatically generated -// - CreatedBy, CreatedAt -// - LastModifiedBy, LastModifiedAt -// - IsDeleted, DeletedBy, DeletedAt + modelBuilder.SetupSoftDeleteQueryFilter(); + modelBuilder.ConfigureAuditLogTableNames( + "AuditEntityChanges", + "AuditFieldChanges"); +} ``` -## Documentation +`SetupSoftDeleteQueryFilter` combines its predicate with an existing filter instead of replacing tenant or authorization filters. Create a normal EF Core migration after enabling auditing so the audit properties and log tables are added to the database. + +### Transaction guarantees + +The default `BestEffort` mode preserves the two-save behavior used by earlier releases. Business changes can succeed even if the subsequent audit-log save fails. -See [detailed documentation](src/Ling.Audit/README.md) for: -- Available interfaces and properties -- Advanced usage examples -- Best practices -- API reference +For atomic behavior, require an application-owned transaction: -## Contributing +```csharp +options.UseAudit(audit => +{ + audit.TransactionMode = AuditTransactionMode.RequireExplicitTransaction; +}); +``` + +```csharp +await using var transaction = + await dbContext.Database.BeginTransactionAsync(cancellationToken); + +dbContext.Add(order); +await dbContext.SaveChangesAsync(cancellationToken); +await transaction.CommitAsync(cancellationToken); +``` + +In this mode, an audited save without an active relational transaction is rejected. The business changes and generated audit rows participate in the same transaction. + +### Anonymous operations + +An audited operation with no resolved user is rejected by default. Allow selected operations on an entity when anonymous access is intentional: + +```csharp +[Auditable(AllowedAnonymous = DataOperation.Create)] +public sealed partial class Registration : ICreationAudited +{ +} +``` + +Global behavior can be changed with `AuditOptions.AllowAnonymous`, or customized with `UseAnonymousHandler()`. + +## ASP.NET Core + +For applications whose audit user ID is a string claim, install the ASP.NET Core package instead of configuring an EF user provider manually: + +```shell +dotnet add package Ling.Audit.AspNetCore --version 2.0.1 +``` + +```csharp +using Ling.Audit.AspNetCore; + +services.AddDbContext(options => +{ + options.UseSqlServer(connectionString); + options.UseAspNetCoreAudit(); +}); +``` + +The default resolver selects the first authenticated `ClaimsIdentity` and resolves values in this order: + +1. Explicit `UserIdClaimType` or `UserNameClaimType` options. +2. ASP.NET Core `IdentityOptions.ClaimsIdentity` claim types, when Identity is registered. +3. `ClaimsIdentity.Name` for the user name. +4. `ClaimTypes.NameIdentifier`, then `sub`, for the user ID. +5. `ClaimTypes.Name`, then `name`, for the user name. + +Override claim types without changing the application's authentication configuration: + +```csharp +options.UseAspNetCoreAudit(http => +{ + http.UserIdClaimType = "employee_id"; + http.UserNameClaimType = "preferred_username"; + http.MaxClientNameLength = 256; +}); +``` + +No `HttpContext` is treated as a background or non-HTTP operation and flows into the configured anonymous policy. The integration reads `HttpContext.User`; it does not invoke authentication again. + +For multiple identities or application-specific selection rules, implement `IAuditPrincipalResolver`: + +```csharp +public sealed class ApplicationPrincipalResolver : IAuditPrincipalResolver +{ + public AuditPrincipal Resolve(HttpContext httpContext) + { + var user = httpContext.User; + return new AuditPrincipal( + user.FindFirst("actor_id")?.Value, + user.Identity?.Name); + } +} +``` + +```csharp +options.UseAspNetCoreAudit(); +``` + +`Ling.Audit.AspNetCore` deliberately uses string user IDs. Applications using `Guid`, `int`, or another key type should use `Ling.Audit.EntityFrameworkCore` and register a matching `AuditContextProviderBase` implementation. + +## Customization + +- `UseSerializer()` replaces property serialization. +- `UseAnonymousHandler()` controls rejected anonymous operations. +- `UseAuditTimeProvider()` supplies deterministic UTC timestamps. +- `UseAspNetCoreAudit()` changes HTTP principal selection. + +## Design + +- `Ling.Audit` owns domain-facing contracts and compile-time tooling. It has no EF Core or ASP.NET Core dependency. +- `Ling.Audit.EntityFrameworkCore` owns persistence behavior, soft deletion, and change-log models. It does not depend on HTTP or claims APIs. +- `Ling.Audit.AspNetCore` adapts the current request to the EF Core user-provider contract. Principal resolution remains replaceable and does not perform authentication. + +This separation keeps entity contracts reusable across web applications, workers, tests, and other hosts while making request-specific behavior opt-in. + +## Migration from 1.x + +The former `Ling.EntityFrameworkCore.Audit` package was renamed to `Ling.Audit.EntityFrameworkCore`. ASP.NET Core claim settings now belong to the dedicated ASP.NET Core integration, and anonymous audited operations are rejected by default. + +See the [2.0 migration guide](docs/migrating-to-2.0.md) for package, API, transaction, and data-format changes. + +## Development + +```shell +dotnet build Ling.Audit.sln -c Release +dotnet test Ling.Audit.sln -c Release +``` -1. Fork the repository -2. Create a feature branch -3. Commit your changes -4. Push to the branch -5. Create a Pull Request +The test matrix runs the EF Core and ASP.NET Core integration suites against .NET 6, 7, 8, and 9. Pull requests that change behavior should include corresponding tests. ## License -[Apache 2.0](LICENSE) +[Apache License 2.0](LICENSE) diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 0000000..425b7ea --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,288 @@ +# Ling.Audit + +[English](README.md) | 简体中文 + +`Ling.Audit` 在编译期为领域实体生成强类型审计属性,通过 Entity Framework Core 自动维护这些属性,并可从 ASP.NET Core 获取当前用户和请求信息。核心契约不依赖 EF Core 或 ASP.NET Core,因此应用可以只引入实际需要的层。 + +## NuGet 包 + +| 包 | 用途 | 目标框架 | +| --- | --- | --- | +| [`Ling.Audit`](https://www.nuget.org/packages/Ling.Audit/) [![NuGet](https://img.shields.io/nuget/v/Ling.Audit.svg)](https://www.nuget.org/packages/Ling.Audit/) | 审计契约、源代码生成器、Analyzer 和 Code Fix。 | .NET Standard 2.0/2.1、.NET Core 3.1、.NET 5–9 | +| [`Ling.Audit.EntityFrameworkCore`](https://www.nuget.org/packages/Ling.Audit.EntityFrameworkCore/) [![NuGet](https://img.shields.io/nuget/v/Ling.Audit.EntityFrameworkCore.svg)](https://www.nuget.org/packages/Ling.Audit.EntityFrameworkCore/) | 审计属性维护、软删除以及实体/字段变更日志。 | .NET 6–9 | +| [`Ling.Audit.AspNetCore`](https://www.nuget.org/packages/Ling.Audit.AspNetCore/) [![NuGet](https://img.shields.io/nuget/v/Ling.Audit.AspNetCore.svg)](https://www.nuget.org/packages/Ling.Audit.AspNetCore/) | 从当前 HTTP 请求获取用户、IP 地址和客户端信息。 | .NET 6–9 | + +EF Core 与 ASP.NET Core 包会为每个目标框架引用对应主版本的 EF Core。 + +## 功能 + +- 在编译期生成审计属性,无需反射或运行时代理类型。 +- 提供创建、修改、删除和完整审计等粒度明确的接口。 +- 支持 class、record、泛型类型、继承和嵌套 partial 类型。 +- 通过编译器诊断与 Code Fix 提示无效的审计声明。 +- 在 `SaveChanges` 时自动维护审计字段。 +- 将被审计实体的删除转换为软删除,并与已有 Query Filter 合并。 +- 记录实体级和字段级变更,支持复合主键和影子主键。 +- 支持从 ASP.NET Core Identity、JWT Bearer、OpenID Connect 和自定义认证方案解析 Claims。 +- 可替换用户提供器、Principal 解析器、序列化器、匿名处理器和时间提供器。 +- 在业务写入与审计日志必须原子提交时提供显式事务模式。 + +## 快速开始 + +在定义实体的项目中安装核心包: + +```shell +dotnet add package Ling.Audit --version 2.0.1 +``` + +根据实体生命周期实现相应审计接口。实体类型及其所有包含类型都必须是 `partial`: + +```csharp +using Ling.Audit; + +namespace MyApplication.Domain; + +public sealed partial class Post : IFullAudited +{ + public int Id { get; set; } + public string Title { get; set; } = string.Empty; +} +``` + +源代码生成器会在当前编译中补充接口属性: + +```csharp +public sealed partial class Post +{ + public string? CreatedBy { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public string? LastModifiedBy { get; set; } + public DateTimeOffset? LastModifiedAt { get; set; } + public bool IsDeleted { get; set; } + public string? DeletedBy { get; set; } + public DateTimeOffset? DeletedAt { get; set; } +} +``` + +只需要单个属性时使用基础接口,需要完整生命周期时使用组合接口: + +| 接口 | 生成的属性 | +| --- | --- | +| `IHasCreator` | `CreatedBy` | +| `IHasCreationTime` | `CreatedAt` | +| `IHasModifier` | `LastModifiedBy` | +| `IHasModificationTime` | `LastModifiedAt` | +| `ISoftDelete` | `IsDeleted` | +| `IHasDeleter` | `DeletedBy` | +| `IHasDeletionTime` | `DeletedAt` | +| `ICreationAudited` | `CreatedBy`、`CreatedAt` | +| `IModificationAudited` | `LastModifiedBy`、`LastModifiedAt` | +| `IDeletionAudited` | `IsDeleted`、`DeletedBy`、`DeletedAt` | +| `IFullAudited` | 全部创建、修改和删除属性 | + +## Entity Framework Core + +安装与应用目标框架相匹配的集成包: + +```shell +dotnet add package Ling.Audit.EntityFrameworkCore --version 2.0.1 +``` + +实现当前用户与客户端上下文提供器: + +```csharp +using Ling.Audit.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; + +public sealed class ApplicationAuditUserProvider( + ICurrentDbContext currentDbContext) + : AuditContextProviderBase(currentDbContext) +{ + protected override AuditContext? GetAuditContext() + { + var currentUser = GetService(); + + return currentUser?.Id is { } id + ? new AuditContext(id, currentUser.Name, null, null) + : null; + } +} +``` + +在配置 `DbContext` 时启用审计: + +```csharp +services.AddDbContext(options => +{ + options.UseSqlServer(connectionString); + options.UseAudit(); +}); +``` + +只有明确标记的实体会写入审计日志。实体属性默认参与审计,可以单独排除敏感或无意义的字段: + +```csharp +using Ling.Audit.EntityFrameworkCore; + +[Auditable] +public sealed partial class Account : IFullAudited +{ + public Guid Id { get; set; } + public string DisplayName { get; set; } = string.Empty; + + [NotAudited] + public string PasswordHash { get; set; } = string.Empty; +} +``` + +也可以使用 Fluent API 完成相同配置: + +```csharp +protected override void OnModelCreating(ModelBuilder modelBuilder) +{ + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity().IsAuditable(); + modelBuilder.Entity() + .Property(account => account.PasswordHash) + .IsNotAudited(); + + modelBuilder.SetupSoftDeleteQueryFilter(); + modelBuilder.ConfigureAuditLogTableNames( + "AuditEntityChanges", + "AuditFieldChanges"); +} +``` + +`SetupSoftDeleteQueryFilter` 会把软删除条件与已有过滤器组合,不会覆盖多租户或权限过滤器。启用审计后应正常创建 EF Core Migration,将审计属性和日志表加入数据库。 + +### 事务保证 + +默认的 `BestEffort` 模式保留旧版本的两次保存行为。业务写入成功后,后续的审计日志保存仍可能失败。 + +需要原子性时,让应用显式持有事务: + +```csharp +options.UseAudit(audit => +{ + audit.TransactionMode = AuditTransactionMode.RequireExplicitTransaction; +}); +``` + +```csharp +await using var transaction = + await dbContext.Database.BeginTransactionAsync(cancellationToken); + +dbContext.Add(order); +await dbContext.SaveChangesAsync(cancellationToken); +await transaction.CommitAsync(cancellationToken); +``` + +此模式会拒绝没有活动关系型事务的审计写入,业务数据和生成的审计日志将参与同一个事务。 + +### 匿名操作 + +默认情况下,无法解析用户的审计操作会被拒绝。确实允许匿名访问时,可以按实体开放指定操作: + +```csharp +[Auditable(AllowedAnonymous = DataOperation.Create)] +public sealed partial class Registration : ICreationAudited +{ +} +``` + +也可以通过 `AuditOptions.AllowAnonymous` 修改全局行为,或使用 `UseAnonymousHandler()` 自定义处理方式。 + +## ASP.NET Core + +如果应用使用字符串 Claim 作为用户 ID,可以直接安装 ASP.NET Core 包,无需自行实现 EF 用户提供器: + +```shell +dotnet add package Ling.Audit.AspNetCore --version 2.0.1 +``` + +```csharp +using Ling.Audit.AspNetCore; + +services.AddDbContext(options => +{ + options.UseSqlServer(connectionString); + options.UseAspNetCoreAudit(); +}); +``` + +默认解析器选择第一个已认证的 `ClaimsIdentity`,并按以下顺序取值: + +1. 显式配置的 `UserIdClaimType` 或 `UserNameClaimType`。 +2. 注册 ASP.NET Core Identity 时的 `IdentityOptions.ClaimsIdentity` ClaimType。 +3. 使用 `ClaimsIdentity.Name` 获取用户名。 +4. 用户 ID 依次回退到 `ClaimTypes.NameIdentifier` 和 `sub`。 +5. 用户名依次回退到 `ClaimTypes.Name` 和 `name`。 + +可以在不修改应用认证设置的情况下覆盖 ClaimType: + +```csharp +options.UseAspNetCoreAudit(http => +{ + http.UserIdClaimType = "employee_id"; + http.UserNameClaimType = "preferred_username"; + http.MaxClientNameLength = 256; +}); +``` + +没有 `HttpContext` 会被视为后台任务或非 HTTP 操作,并进入已配置的匿名策略。集成只读取 `HttpContext.User`,不会再次发起认证。 + +多 Identity 或应用具有特殊选择规则时,可以实现 `IAuditPrincipalResolver`: + +```csharp +public sealed class ApplicationPrincipalResolver : IAuditPrincipalResolver +{ + public AuditPrincipal Resolve(HttpContext httpContext) + { + var user = httpContext.User; + return new AuditPrincipal( + user.FindFirst("actor_id")?.Value, + user.Identity?.Name); + } +} +``` + +```csharp +options.UseAspNetCoreAudit(); +``` + +`Ling.Audit.AspNetCore` 明确使用字符串用户 ID。使用 `Guid`、`int` 或其他键类型的应用应使用 `Ling.Audit.EntityFrameworkCore`,并注册相应的 `AuditContextProviderBase` 实现。 + +## 自定义扩展 + +- `UseSerializer()` 替换属性序列化器。 +- `UseAnonymousHandler()` 处理被拒绝的匿名操作。 +- `UseAuditTimeProvider()` 提供可测试的 UTC 时间。 +- `UseAspNetCoreAudit()` 修改 HTTP Principal 选择规则。 + +## 设计 + +- `Ling.Audit` 负责面向领域层的契约和编译期工具,不依赖 EF Core 或 ASP.NET Core。 +- `Ling.Audit.EntityFrameworkCore` 负责持久化行为、软删除和变更日志模型,不依赖 HTTP 或 Claims API。 +- `Ling.Audit.AspNetCore` 将当前请求适配到 EF Core 用户提供器契约;Principal 解析可以替换,并且不会主动执行认证。 + +这种边界使实体契约可以复用于 Web 应用、Worker、测试和其他宿主,同时让请求相关行为保持可选。 + +## 从 1.x 迁移 + +原来的 `Ling.EntityFrameworkCore.Audit` 已更名为 `Ling.Audit.EntityFrameworkCore`。ASP.NET Core Claim 设置移动到了独立的 ASP.NET Core 集成中,匿名审计操作现在默认拒绝。 + +包名、API、事务和数据格式变化请参阅 [2.0 迁移指南](docs/migrating-to-2.0.md)。 + +## 开发 + +```shell +dotnet build Ling.Audit.sln -c Release +dotnet test Ling.Audit.sln -c Release +``` + +测试矩阵会在 .NET 6、7、8 和 9 上分别运行 EF Core 与 ASP.NET Core 集成测试。行为变更应同时包含相应测试。 + +## 协议 + +[Apache License 2.0](LICENSE) diff --git a/docs/migrating-to-2.0.md b/docs/migrating-to-2.0.md new file mode 100644 index 0000000..09f5f71 --- /dev/null +++ b/docs/migrating-to-2.0.md @@ -0,0 +1,29 @@ +# Migrating to Ling.Audit.EntityFrameworkCore 2.0 + +The EF Core package has moved from `Ling.EntityFrameworkCore.Audit` to `Ling.Audit.EntityFrameworkCore`. The old package should be deprecated on NuGet.org with the new package configured as its recommended replacement. + +## Package changes + +```shell +dotnet remove package Ling.EntityFrameworkCore.Audit +dotnet add package Ling.Audit.EntityFrameworkCore --version 2.0.1 +``` + +ASP.NET Core applications can additionally install `Ling.Audit.AspNetCore`. The core EF package does not depend on HTTP or claims APIs. + +## Configuration changes + +- Use `UseAudit()` for framework-independent EF Core auditing. +- Use `UseAspNetCoreAudit()` for the built-in string claim provider. +- Claim settings now belong to `AspNetCoreAuditOptions`, not `AuditOptions`. +- Custom HTTP principal selection is implemented with `IAuditPrincipalResolver`. +- Anonymous operations are rejected by default. Set `AuditOptions.AllowAnonymous`, configure `AuditableAttribute.AllowedAnonymous`, or register a custom `IAuditAnonymousHandler` to opt in. +- Primary keys in new audit rows are stored as JSON objects, including composite and shadow keys. + +## Transaction behavior + +The default `BestEffort` mode writes audit rows immediately after the audited save and is backward-compatible, but the two saves may use separate transactions. Set `TransactionMode` to `RequireExplicitTransaction` and begin a transaction before saving when atomicity is required. + +## Target frameworks + +Version 2.0 of the EF Core and ASP.NET Core packages provides assets for .NET 6, 7, 8 and 9, each compiled against the corresponding EF Core major version. .NET 10 support is planned as an additive 2.1 release. diff --git a/global.json b/global.json deleted file mode 100644 index 8f612bb..0000000 --- a/global.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "sdk": { - "version": "9.0.101" - } -} \ No newline at end of file diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 56d4157..24e677f 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -8,8 +8,13 @@ - 2.0.0 + 2.0.1 + ling921 + true + true + snupkg + true @@ -18,4 +23,4 @@ - \ No newline at end of file + diff --git a/src/Ling.Audit.AspNetCore/AspNetCoreAuditOptions.cs b/src/Ling.Audit.AspNetCore/AspNetCoreAuditOptions.cs new file mode 100644 index 0000000..d502383 --- /dev/null +++ b/src/Ling.Audit.AspNetCore/AspNetCoreAuditOptions.cs @@ -0,0 +1,32 @@ +namespace Ling.Audit.AspNetCore; + +/// +/// Configures how audit user information is resolved from the current HTTP request. +/// +public sealed class AspNetCoreAuditOptions +{ + /// + /// Gets or sets an explicit claim type for the user identifier. A null value enables automatic resolution. + /// + public string? UserIdClaimType { get; set; } + + /// + /// Gets or sets an explicit claim type for the user name. A null value enables automatic resolution. + /// + public string? UserNameClaimType { get; set; } + + /// + /// Gets or sets whether only authenticated identities may provide audit user information. + /// + public bool RequireAuthenticatedIdentity { get; set; } = true; + + /// + /// Gets or sets whether the User-Agent header should be parsed into a friendly client name. + /// + public bool ParseUserAgent { get; set; } = true; + + /// + /// Gets or sets the maximum stored length of the client name or User-Agent value. + /// + public int MaxClientNameLength { get; set; } = 512; +} diff --git a/src/Ling.Audit.AspNetCore/AspNetCoreDbContextOptionsBuilderExtensions.cs b/src/Ling.Audit.AspNetCore/AspNetCoreDbContextOptionsBuilderExtensions.cs new file mode 100644 index 0000000..976e22b --- /dev/null +++ b/src/Ling.Audit.AspNetCore/AspNetCoreDbContextOptionsBuilderExtensions.cs @@ -0,0 +1,41 @@ +using Ling.Audit.AspNetCore.Internal; +using Ling.Audit.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; + +namespace Ling.Audit.AspNetCore; + +/// +/// Extension methods for configuring HTTP request based auditing. +/// +public static class AspNetCoreDbContextOptionsBuilderExtensions +{ + /// + /// Configures auditing to resolve string user identifiers from the current HTTP request. + /// + public static DbContextOptionsBuilder UseAspNetCoreAudit( + this DbContextOptionsBuilder builder, + Action? setupAction = null, + Action? auditSetupAction = null) + { + return builder.UseAspNetCoreAudit(setupAction, auditSetupAction); + } + + /// + /// Configures auditing with a custom HTTP principal resolver. + /// + public static DbContextOptionsBuilder UseAspNetCoreAudit( + this DbContextOptionsBuilder builder, + Action? setupAction = null, + Action? auditSetupAction = null) + where TPrincipalResolver : class, IAuditPrincipalResolver + { + ArgumentNullException.ThrowIfNull(builder); + + var extension = builder.Options.FindExtension>() + ?? new AspNetCoreAuditOptionsExtension(setupAction); + + ((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(extension); + return builder.UseAudit(auditSetupAction); + } +} diff --git a/src/Ling.Audit.AspNetCore/DefaultAuditPrincipalResolver.cs b/src/Ling.Audit.AspNetCore/DefaultAuditPrincipalResolver.cs new file mode 100644 index 0000000..3def4de --- /dev/null +++ b/src/Ling.Audit.AspNetCore/DefaultAuditPrincipalResolver.cs @@ -0,0 +1,51 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using System.Security.Claims; + +namespace Ling.Audit.AspNetCore; + +internal sealed class DefaultAuditPrincipalResolver( + IOptions auditOptions, + IOptions identityOptions) : IAuditPrincipalResolver +{ + public AuditPrincipal Resolve(HttpContext httpContext) + { + ArgumentNullException.ThrowIfNull(httpContext); + + var options = auditOptions.Value; + var principal = httpContext.User; + var identity = principal.Identities.FirstOrDefault(i => i.IsAuthenticated); + + if (identity is null && !options.RequireAuthenticatedIdentity) + { + identity = principal.Identities.FirstOrDefault(); + } + + if (identity is null) + { + return new AuditPrincipal(null, null); + } + + var identityClaims = identityOptions.Value.ClaimsIdentity; + var userId = FindFirst(identity, options.UserIdClaimType) + ?? FindFirst(identity, identityClaims.UserIdClaimType) + ?? FindFirst(identity, ClaimTypes.NameIdentifier) + ?? FindFirst(identity, "sub"); + + var userName = FindFirst(identity, options.UserNameClaimType) + ?? identity.Name + ?? FindFirst(identity, identityClaims.UserNameClaimType) + ?? FindFirst(identity, ClaimTypes.Name) + ?? FindFirst(identity, "name"); + + return new AuditPrincipal(userId, userName); + } + + private static string? FindFirst(ClaimsIdentity identity, string? claimType) + { + return string.IsNullOrWhiteSpace(claimType) + ? null + : identity.FindFirst(claimType)?.Value; + } +} diff --git a/src/Ling.Audit.AspNetCore/HttpAuditUserProvider.cs b/src/Ling.Audit.AspNetCore/HttpAuditUserProvider.cs new file mode 100644 index 0000000..cb6f732 --- /dev/null +++ b/src/Ling.Audit.AspNetCore/HttpAuditUserProvider.cs @@ -0,0 +1,57 @@ +using Ling.Audit.EntityFrameworkCore; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.Options; + +namespace Ling.Audit.AspNetCore; + +internal sealed class HttpAuditUserProvider(ICurrentDbContext current) + : AuditContextProviderBase(current) +{ + protected override AuditContext? GetAuditContext() + { + var httpContext = GetService()?.HttpContext; + if (httpContext is null) + { + return null; + } + + var principal = GetService()!.Resolve(httpContext); + var options = GetService>()!.Value; + var clientName = GetClientName(httpContext, options); + + return new AuditContext( + principal.UserId, + principal.UserName, + httpContext.Connection.RemoteIpAddress?.ToString(), + clientName); + } + + private static string? GetClientName(HttpContext context, AspNetCoreAuditOptions options) + { + var userAgent = context.Request.Headers.UserAgent.ToString(); + if (string.IsNullOrWhiteSpace(userAgent) || options.MaxClientNameLength <= 0) + { + return null; + } + + var value = options.ParseUserAgent + ? TryParseUserAgent(userAgent) ?? userAgent + : userAgent; + + return value.Length <= options.MaxClientNameLength + ? value + : value[..options.MaxClientNameLength]; + } + + private static string? TryParseUserAgent(string userAgent) + { + // UAParser is an optional integration. If the application references it, use it; + // otherwise retain the original header without adding a mandatory package dependency. + var parserType = Type.GetType("UAParser.Parser, UAParser", throwOnError: false); + var getDefault = parserType?.GetMethod("GetDefault", Type.EmptyTypes); + var parser = getDefault?.Invoke(null, null); + var parse = parserType?.GetMethod("Parse", [typeof(string)]); + return parse?.Invoke(parser, [userAgent])?.ToString(); + } +} diff --git a/src/Ling.Audit.AspNetCore/IAuditPrincipalResolver.cs b/src/Ling.Audit.AspNetCore/IAuditPrincipalResolver.cs new file mode 100644 index 0000000..f2fa3fc --- /dev/null +++ b/src/Ling.Audit.AspNetCore/IAuditPrincipalResolver.cs @@ -0,0 +1,21 @@ +using Microsoft.AspNetCore.Http; + +namespace Ling.Audit.AspNetCore; + +/// +/// Resolves audit principal information from an HTTP request. +/// +public interface IAuditPrincipalResolver +{ + /// + /// Resolves audit principal information from . + /// + AuditPrincipal Resolve(HttpContext httpContext); +} + +/// +/// Represents user information resolved from a claims principal. +/// +/// The user identifier. +/// The user name. +public sealed record AuditPrincipal(string? UserId, string? UserName); diff --git a/src/Ling.Audit.AspNetCore/Internal/AspNetCoreAuditOptionsExtension.cs b/src/Ling.Audit.AspNetCore/Internal/AspNetCoreAuditOptionsExtension.cs new file mode 100644 index 0000000..16f75f4 --- /dev/null +++ b/src/Ling.Audit.AspNetCore/Internal/AspNetCoreAuditOptionsExtension.cs @@ -0,0 +1,48 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace Ling.Audit.AspNetCore.Internal; + +internal sealed class AspNetCoreAuditOptionsExtension( + Action? setupAction) : IDbContextOptionsExtension + where TPrincipalResolver : class, IAuditPrincipalResolver +{ + internal Action? SetupAction { get; } = setupAction; + + public DbContextOptionsExtensionInfo Info => new ExtensionInfo(this); + + public void ApplyServices(IServiceCollection services) + { + services.AddOptions(); + if (SetupAction is not null) + { + services.Configure(SetupAction); + } + + services.TryAddSingleton(); + services.TryAddScoped(); + } + + public void Validate(IDbContextOptions options) + { + } + + private sealed class ExtensionInfo(IDbContextOptionsExtension extension) + : DbContextOptionsExtensionInfo(extension) + { + private AspNetCoreAuditOptionsExtension TypedExtension => + (AspNetCoreAuditOptionsExtension)Extension; + + public override bool IsDatabaseProvider => false; + public override string LogFragment => "using Ling.Audit.AspNetCore "; + public override int GetServiceProviderHashCode() => + HashCode.Combine(typeof(TPrincipalResolver), TypedExtension.SetupAction); + public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => + other.Extension is AspNetCoreAuditOptionsExtension extension && + ReferenceEquals(TypedExtension.SetupAction, extension.SetupAction); + public override void PopulateDebugInfo(IDictionary debugInfo) => + debugInfo["Ling.Audit.AspNetCore:Resolver"] = typeof(TPrincipalResolver).FullName!; + } +} diff --git a/src/Ling.Audit.AspNetCore/Ling.Audit.AspNetCore.csproj b/src/Ling.Audit.AspNetCore/Ling.Audit.AspNetCore.csproj new file mode 100644 index 0000000..6cffc89 --- /dev/null +++ b/src/Ling.Audit.AspNetCore/Ling.Audit.AspNetCore.csproj @@ -0,0 +1,30 @@ + + + + net6.0;net7.0;net8.0;net9.0 + true + $(NoWarn);IDE0130 + Ling.Audit.AspNetCore + ASP.NET Core user and request context integration for Ling.Audit. + ling;audit;aspnetcore;claims;entity-framework-core + Apache-2.0 + https://github.com/ling921/ling-audit + $(RepositoryUrl) + README.md + icon.png + + + + + + + + + + + + + + + + diff --git a/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditableAttribute.cs b/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditableAttribute.cs new file mode 100644 index 0000000..ea60a6d --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditableAttribute.cs @@ -0,0 +1,15 @@ +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Marks an entity class as requiring audit logging. +/// By default, all mapped properties are audited unless marked with [NotAudited]. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AuditableAttribute : Attribute +{ + /// + /// Gets or sets the operations that are allowed to be performed anonymously (without user context). + /// Defaults to , requiring user context for all audited operations. + /// + public DataOperation AllowedAnonymous { get; set; } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Attributes/NotAuditedAttribute.cs b/src/Ling.Audit.EntityFrameworkCore/Attributes/NotAuditedAttribute.cs new file mode 100644 index 0000000..3c808c2 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Attributes/NotAuditedAttribute.cs @@ -0,0 +1,8 @@ +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Marks an entity property to be excluded from audit logging, +/// even if the containing entity is marked as [Auditable]. +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] +public class NotAuditedAttribute : Attribute; diff --git a/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs b/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs new file mode 100644 index 0000000..887ba62 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs @@ -0,0 +1,18 @@ +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Define the audit configuration items. +/// +public static class AuditDefaults +{ + /// + /// The switch to control whether auditing is disabled. + /// + /// To disable auditing: + /// + /// AppContext.SetSwitch("Ling.Audit.EntityFrameworkCore.DisableAuditing", true); + /// + /// + /// + public const string DisableAuditingSwitch = "Ling.Audit.EntityFrameworkCore.DisableAuditing"; +} diff --git a/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs b/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs new file mode 100644 index 0000000..24cab70 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs @@ -0,0 +1,78 @@ +using System.Text.Json; + +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Option to configure the behavior of audited entities. +/// +public class AuditOptions +{ + /// + /// Whether to allow anonymous operation of audit entities, default to . + /// + /// will be invoke when anonymous operation occurred. + /// + /// + public bool AllowAnonymous { get; set; } + + /// + /// Comments. + /// + public AuditEntityComments Comments { get; set; } = new(); + + /// + /// Whether to audit entities that has no field changes, default to . + /// + public bool AuditNoFieldChangeEntity { get; set; } + + /// + /// Gets or sets the transaction guarantee required when audit logs are persisted. + /// + public AuditTransactionMode TransactionMode { get; set; } + + /// + /// Gets or sets for default . + /// + public JsonSerializerOptions? PropertySerializerOptions { get; set; } +} + +/// +/// Comments to the audited entities. +/// +public class AuditEntityComments +{ + /// + /// Comment to CreatedAt property. + /// + public string CreatedAt { get; set; } = "The date and time when created this entity."; + + /// + /// Comment to CreatedBy property. + /// + public string CreatedBy { get; set; } = "The primary key of the user who created this entity."; + + /// + /// Comment to ModifiedAt property. + /// + public string ModifiedAt { get; set; } = "The date and time when modified this entity."; + + /// + /// Comment to ModifiedBy property. + /// + public string ModifiedBy { get; set; } = "The primary key of the user who modified this entity."; + + /// + /// Comment to IsDeleted property. + /// + public string IsDeleted { get; set; } = "A flag indicating if the entity has mark as deleted instead of actually deleting it."; + + /// + /// Comment to DeletedAt property. + /// + public string DeletedAt { get; set; } = "The date and time when marked this entity as deleted."; + + /// + /// Comment to DeletedBy property. + /// + public string DeletedBy { get; set; } = "The primary key of the user who marked this entity as deleted."; +} diff --git a/src/Ling.Audit.EntityFrameworkCore/AuditTransactionMode.cs b/src/Ling.Audit.EntityFrameworkCore/AuditTransactionMode.cs new file mode 100644 index 0000000..4bbbac3 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/AuditTransactionMode.cs @@ -0,0 +1,17 @@ +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Specifies the transaction guarantee used when audit logs are persisted. +/// +public enum AuditTransactionMode +{ + /// + /// Writes audit logs after the audited save. This preserves compatibility but may use a separate transaction. + /// + BestEffort, + + /// + /// Requires the caller to start a transaction so the audited save and audit logs share that transaction. + /// + RequireExplicitTransaction, +} diff --git a/src/Ling.Audit.EntityFrameworkCore/DataOperation.cs b/src/Ling.Audit.EntityFrameworkCore/DataOperation.cs new file mode 100644 index 0000000..a3b72e9 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/DataOperation.cs @@ -0,0 +1,34 @@ +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Specifies fundamental data manipulation operations, typically corresponding to CUD actions. +/// Can be combined using bitwise flags. +/// +[Flags] +public enum DataOperation : byte +{ + /// + /// Represents no specific data operation. + /// + None = 0, + + /// + /// Represents the creation of new data (e.g., SQL INSERT). + /// + Create = 1 << 0, + + /// + /// Represents the modification of existing data (e.g., SQL UPDATE). + /// + Modify = 1 << 1, + + /// + /// Represents the deletion of existing data (e.g., SQL DELETE). + /// + Delete = 1 << 2, + + /// + /// Represents all primary data writing operations (Create, Modify, Delete). + /// + All = Create | Modify | Delete +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs new file mode 100644 index 0000000..85d226b --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs @@ -0,0 +1,79 @@ +using Ling.Audit.EntityFrameworkCore.Internal; +using Ling.Audit.EntityFrameworkCore.Internal.Extensions; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.EntityFrameworkCore.Infrastructure; + +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Extension methods for . +/// +public static class DbContextOptionsBuilderExtensions +{ + /// + /// Sets the , , to be used for the auditing. + /// + /// The . + /// The action used to configure the . + public static DbContextOptionsBuilder UseAudit( + this DbContextOptionsBuilder builder, + Action? setupAction = null) + where TUserProvider : AuditContextProviderBase + { + ArgumentNullException.ThrowIfNull(builder); + + var extension = builder.Options.FindExtension>() + ?? new AuditOptionsExtension(setupAction); + + ((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(extension); + + // Add interceptor for audit + builder.AddInterceptors(new AuditSaveChangesInterceptor()); + + // Add model customizer for audit + builder.ReplaceService>(); + + return builder; + } + + /// + /// Configures the options builder to use a specified property serializer for the context. + /// + /// This type parameter specifies the class that will handle property serialization. + /// This parameter is the options builder being configured for the database context. + /// Returns the modified options builder with the new property serializer. + public static DbContextOptionsBuilder UseSerializer(this DbContextOptionsBuilder builder) + where TSerializer : class, IPropertySerializer + { + builder.ReplaceService(); + + return builder; + } + + /// + /// Configures the options builder to use custom handler for handling anonymous audit operations. + /// + /// The type of handler + /// This parameter is the options builder being configured for the database context. + /// Returns the modified options builder with the custom handler. + public static DbContextOptionsBuilder UseAnonymousHandler(this DbContextOptionsBuilder builder) + where THandler : class, IAuditAnonymousHandler + { + builder.ReplaceService(); + + return builder; + } + + /// + /// Configures the time provider used for audit timestamps. + /// + public static DbContextOptionsBuilder UseAuditTimeProvider(this DbContextOptionsBuilder builder) + where TTimeProvider : class, IAuditTimeProvider + { + ArgumentNullException.ThrowIfNull(builder); + builder.ReplaceService(); + return builder; + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs new file mode 100644 index 0000000..b92077a --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs @@ -0,0 +1,429 @@ +using Ling.Audit.EntityFrameworkCore.Internal; +using Ling.Audit.EntityFrameworkCore.Internal.Extensions; +using Ling.Audit.EntityFrameworkCore.Internal.Models; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Microsoft.Extensions.Logging; +using System.Diagnostics.CodeAnalysis; +using System.Linq.Expressions; + +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Extension methods for building model. +/// +public static class ModelBuilderExtensions +{ + #region Public Methods + + /// + /// Setup a global query filter for entities has "IsDeleted" property. + /// + /// Entity model builder. + public static void SetupSoftDeleteQueryFilter(this ModelBuilder builder) + { + foreach (var entityType in builder.Model.GetEntityTypes()) + { + var type = entityType.ClrType; + + if (entityType.HasProperty(Constants.IsDeleted)) + { + var typeParameter = Expression.Parameter(type, "e"); + var propertyParameter = Expression.Property(typeParameter, Constants.IsDeleted); + Expression body = Expression.Not(propertyParameter); + + if (entityType.GetQueryFilter() is { } existingFilter) + { + var existingBody = new ReplacingExpressionVisitor( + existingFilter.Parameters[0], + typeParameter).Visit(existingFilter.Body)!; + body = Expression.AndAlso(existingBody, body); + } + + var lambda = Expression.Lambda(body, typeParameter); + + builder.Entity(type).HasQueryFilter(lambda); + } + } + } + + /// + /// Configures enable auditing to be applied to the table this entity is mapped to. + /// + /// The builder for the entity type being configured. + /// + /// Allowed anonymous operations to the table this entity is mapped to. + /// + /// The same builder instance so that multiple calls can be chained. + public static EntityTypeBuilder IsAuditable(this EntityTypeBuilder entityTypeBuilder, DataOperation anonymousOperations = DataOperation.None) + { + ArgumentNullException.ThrowIfNull(entityTypeBuilder); + + entityTypeBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, true); + entityTypeBuilder.Metadata.SetAuditMetadata(new AuditMetadata { AnonymousOperations = anonymousOperations }); + + return entityTypeBuilder; + } + + /// + /// The entity type being configured. + public static EntityTypeBuilder IsAuditable(this EntityTypeBuilder entityTypeBuilder, DataOperation anonymousOperations = DataOperation.None) + where TEntity : class + { + EntityTypeBuilder builder = entityTypeBuilder; + + builder.IsAuditable(anonymousOperations); + + return entityTypeBuilder; + } + + /// + /// Configures whether to apply auditing to the column. + /// + /// The builder for the property being configured. + /// Whether not to audit the column, defaults to . + /// The same builder instance so that multiple calls can be chained. + public static PropertyBuilder IsNotAudited(this PropertyBuilder propertyBuilder, bool notAudited = true) + { + ArgumentNullException.ThrowIfNull(propertyBuilder); + + propertyBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, !notAudited); + return propertyBuilder; + } + + /// + /// The type of the property being configured. + public static PropertyBuilder IsNotAudited(this PropertyBuilder propertyBuilder, bool notAudited = true) + { + PropertyBuilder builder = propertyBuilder; + + builder.IsNotAudited(notAudited); + + return propertyBuilder; + } + + /// + /// Configures the table names for audit log entities. + /// + /// The model builder. + /// The table name for entity change logs. + /// The table name for field change logs. + /// The same builder instance so that multiple calls can be chained. + /// Thrown when audit log entity types are not found in the model. + /// Thrown when table names is null or whitespaces. + public static ModelBuilder ConfigureAuditLogTableNames( + this ModelBuilder builder, + string entityChangeLogTableName, + string fieldChangeLogTableName) + { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNullOrWhiteSpace(entityChangeLogTableName); + ThrowHelper.ThrowIfNullOrWhiteSpace(fieldChangeLogTableName); + + var entityLogType = builder.Model.GetEntityTypes() + .FirstOrDefault(e => e.ClrType.IsGenericType && e.ClrType.GetGenericTypeDefinition() == typeof(AuditEntityChangeLog<>)) + ?.ClrType + ?? throw new InvalidOperationException("'AuditEntityChangeLog' entity type not found. Please ensure you have called 'UseAudit()' when configuring your DbContext."); + + builder.Entity(entityLogType) + .ToTable(entityChangeLogTableName); + + var fieldLogType = builder.Model.GetEntityTypes() + .FirstOrDefault(e => e.ClrType == typeof(AuditFieldChangeLog)) + ?.ClrType + ?? throw new InvalidOperationException( + "'AuditFieldChangeLog' entity type not found. Please ensure you have called 'UseAudit()' when configuring your DbContext."); + + builder.Entity(fieldLogType) + .ToTable(fieldChangeLogTableName); + + return builder; + } + + #endregion Public Methods + + #region Internal Methods + +#if NET6_0 + + /// + /// Gets whether the current program is running at design time. + /// + internal static bool IsDesignTime => Path.GetFileName(Environment.GetCommandLineArgs().FirstOrDefault()) == "ef.dll"; + +#endif + + /// + /// Configure properties of auditable entities. + /// + /// Entity model builder. + /// Audit options to configure the behavior of audited entities. + /// Logger to log the configuration process. + /// The identity type of user for current . + internal static void ConfigureAuditableEntities(this ModelBuilder builder, AuditOptions options, ILogger logger) + { + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(options); + + var userIdType = typeof(TUserId); + logger.LogInformation("Starting to configure auditable entities. Initial user ID type: {UserIdType}", userIdType.GetFriendlyName()); + + foreach (var entityType in builder.Model.GetEntityTypes()) + { + var metadata = new AuditMetadata(); + var entityClrType = entityType.ClrType; + var entityName = entityClrType.GetFriendlyName(); + + logger.LogDebug("Configuring audit properties for entity: {EntityName}", entityName); + + // Configure creation audit properties + if (entityType.HasProperty(Constants.CreatedAt, out var createdAtType)) + { + ValidatePropertyType(entityClrType, Constants.CreatedAt, createdAtType, typeof(DateTimeOffset)); + ConfigureProperty(builder, entityClrType, createdAtType, Constants.CreatedAt, 991, options.Comments.CreatedAt); + metadata.HasCreatedAt = true; + } + + if (entityType.HasProperty(Constants.CreatedBy, out var createdByType)) + { + ValidateAndUpdateUserIdType(entityClrType, Constants.CreatedBy, createdByType, userIdType); + ConfigureProperty(builder, entityClrType, createdByType, Constants.CreatedBy, 992, options.Comments.CreatedBy); + metadata.HasCreatedBy = true; + metadata.UserIdType = createdByType; + } + + // Configure modification audit properties + if (entityType.HasProperty(Constants.ModifiedAt, out var modifiedAtType)) + { + ValidatePropertyType(entityClrType, Constants.ModifiedAt, modifiedAtType, typeof(DateTimeOffset?)); + ConfigureProperty(builder, entityClrType, modifiedAtType, Constants.ModifiedAt, 994, options.Comments.ModifiedAt); + metadata.HasModifiedAt = true; + } + + if (entityType.HasProperty(Constants.ModifiedBy, out var modifiedByType)) + { + ValidateAndUpdateUserIdType(entityClrType, Constants.ModifiedBy, modifiedByType, userIdType); + ConfigureProperty(builder, entityClrType, modifiedByType, Constants.ModifiedBy, 995, options.Comments.ModifiedBy); + metadata.HasModifiedBy = true; + metadata.UserIdType = modifiedByType; + } + + // Configure deletion audit properties + if (entityType.HasProperty(Constants.IsDeleted, out var isDeletedType)) + { + ValidatePropertyType(entityClrType, Constants.IsDeleted, isDeletedType, typeof(bool)); + ConfigureProperty(builder, entityClrType, isDeletedType, Constants.IsDeleted, 997, options.Comments.IsDeleted); + metadata.HasIsDeleted = true; + } + + if (entityType.HasProperty(Constants.DeletedAt, out var deletedAtType)) + { + ValidatePropertyType(entityClrType, Constants.DeletedAt, deletedAtType, typeof(DateTimeOffset?)); + ConfigureProperty(builder, entityClrType, deletedAtType, Constants.DeletedAt, 998, options.Comments.DeletedAt); + metadata.HasDeletedAt = true; + } + + if (entityType.HasProperty(Constants.DeletedBy, out var deletedByType)) + { + ValidateAndUpdateUserIdType(entityClrType, Constants.DeletedBy, deletedByType, userIdType); + ConfigureProperty(builder, entityClrType, deletedByType, Constants.DeletedBy, 999, options.Comments.DeletedBy); + metadata.HasDeletedBy = true; + metadata.UserIdType = deletedByType; + } + + entityType.SetAuditMetadata(metadata); + + logger.LogDebug("Configured audit metadata for {EntityName}: CreatedAt={HasCreatedAt}, CreatedBy={HasCreatedBy}, ModifiedAt={HasModifiedAt}, ModifiedBy={HasModifiedBy}, IsDeleted={HasIsDeleted}, DeletedAt={HasDeletedAt}, DeletedBy={HasDeletedBy}", + entityName, + metadata.HasCreatedAt, + metadata.HasCreatedBy, + metadata.HasModifiedAt, + metadata.HasModifiedBy, + metadata.HasIsDeleted, + metadata.HasDeletedAt, + metadata.HasDeletedBy); + +#if NET6_0 + if (IsDesignTime) +#else + if (EF.IsDesignTime) +#endif + { + logger.LogDebug("Running in design time, removing audit metadata for entity {EntityName}", entityName); + entityType.RemoveAnnotation(Constants.MetadataAnnotationName); + } + } + + logger.LogInformation("Completed configuring auditable entities."); + } + + /// + /// Sets the audit metadata for the specified entity type. + /// + /// The entity type to set the audit metadata for. + /// The audit metadata to set. + internal static void SetAuditMetadata(this IMutableEntityType entityType, AuditMetadata metadata) + { + ArgumentNullException.ThrowIfNull(entityType); + ArgumentNullException.ThrowIfNull(metadata); + + if (entityType.FindAnnotation(Constants.MetadataAnnotationName)?.Value is AuditMetadata original) + { + entityType.SetAnnotation(Constants.MetadataAnnotationName, original | metadata); + } + else + { + entityType.SetAnnotation(Constants.MetadataAnnotationName, metadata); + } + } + + /// + /// Gets the audit metadata for the specified entity type. + /// + /// The entity type to get the audit metadata for. + /// The audit metadata for the specified entity type. + internal static AuditMetadata GetAuditMetadata(this IReadOnlyAnnotatable entityType) + { + ArgumentNullException.ThrowIfNull(entityType); + + return entityType.FindAnnotation(Constants.MetadataAnnotationName)?.Value is AuditMetadata metadata + ? metadata + : new AuditMetadata(); + } + + /// + /// Gets whether auditing is included for the specified annotatable. + /// + /// The annotatable to check. + /// if auditing is included; otherwise, . + internal static bool IsAuditable(this IReadOnlyAnnotatable annotatable) + { + ArgumentNullException.ThrowIfNull(annotatable); + + var value = annotatable.FindAnnotation(Constants.AuditableAnnotationName)?.Value; + + if (annotatable is IEntityType) + { + // Entity auditable is false by default + return value is true; + } + else if (annotatable is IProperty property) + { + if (property.DeclaringType.FindAnnotation(Constants.AuditableAnnotationName) is { Value: true }) + { + if (Constants.PropertyNames.Contains(property.Name)) + { + // Includes audit property if configured as true + return value is true; + } + + // Includes other property if not configured as false + return value is not false; + } + else + { + return false; + } + } + else + { + // Returns false if not IEntityType or IProperty + return false; + } + } + + #endregion Internal Methods + + private sealed class ReplacingExpressionVisitor(Expression source, Expression target) : ExpressionVisitor + { + public override Expression? Visit(Expression? node) => + node == source ? target : base.Visit(node); + } + + #region Private Methods + + /// + /// Checks if the entity type has the specified property. + /// + /// The entity type to check. + /// The name of the property to check for. + /// if the entity type has the specified property; otherwise, . + private static bool HasProperty(this IMutableEntityType entityType, string propertyName) + { + return entityType.FindProperty(propertyName) is not null; + } + + /// + /// Checks if the entity type has the specified property and gets its type. + /// + /// The entity type to check. + /// The name of the property to check for. + /// When this method returns, contains the type of the property, if found; otherwise, . + /// if the entity type has the specified property; otherwise, . + private static bool HasProperty(this IMutableEntityType entityType, string propertyName, [NotNullWhen(true)] out Type? type) + { + type = entityType.FindProperty(propertyName)?.ClrType; + return type is not null; + } + + /// + /// Configures the specified property for the specified entity type. + /// + /// The model builder. + /// The entity type to configure the property for. + /// The type of the property to configure. + /// The name of the property to configure. + /// The order of the column in the table. + /// The comment for the property. + private static void ConfigureProperty( + ModelBuilder builder, + Type entityType, + Type propertyType, + string propertyName, + int columnOrder, + string comment) + { + builder.Entity(entityType) + .Property(propertyType, propertyName) + .HasColumnOrder(columnOrder) + .HasComment(comment); + } + + /// + /// Validates the type of the specified property. + /// + /// The CLR type of the entity. + /// The name of the property to validate. + /// The type of the property to validate. + /// The expected type of the property. + /// Thrown when the property type does not match the expected type. + private static void ValidatePropertyType(Type entityClrType, string propertyName, Type propertyType, Type targetType) + { + if (!propertyType.IsAssignableTo(targetType)) + { + throw new InvalidOperationException( + $"Property '{propertyName}' in entity '{entityClrType.GetFriendlyName()}' must be of type {targetType.Name}"); + } + } + + /// + /// Validates and updates the user ID type. + /// + /// The CLR type of the entity. + /// The name of the property to validate. + /// The type of the property to validate. + /// The user ID type to update. + /// Thrown when the user ID type does not match the expected type. + private static void ValidateAndUpdateUserIdType(Type entityClrType, string propertyName, Type propertyType, Type userIdType) + { + if (userIdType != propertyType) + { + throw new InvalidOperationException( + $"User ID type mismatch in entity '{entityClrType.GetFriendlyName()}.{propertyName}'. Expected '{userIdType.GetFriendlyName()}' but found '{propertyType.GetFriendlyName()}'."); + } + } + + #endregion Private Methods +} diff --git a/src/Ling.Audit.EntityFrameworkCore/IAuditAnonymousHandler.cs b/src/Ling.Audit.EntityFrameworkCore/IAuditAnonymousHandler.cs new file mode 100644 index 0000000..ebe66bd --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/IAuditAnonymousHandler.cs @@ -0,0 +1,32 @@ +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Handles an operation for which no audit user could be resolved. +/// +public interface IAuditAnonymousHandler +{ + /// + /// Handles an anonymous audit operation for the specified entity. + /// + Task HandleAsync( + Type entityType, + DataOperation operation, + object? entity, + CancellationToken cancellationToken = default); +} + +/// +/// Rejects anonymous operations unless they were explicitly allowed. +/// +internal sealed class DefaultAuditAnonymousHandler : IAuditAnonymousHandler +{ + public Task HandleAsync( + Type entityType, + DataOperation operation, + object? entity, + CancellationToken cancellationToken = default) + { + throw new InvalidOperationException( + $"Anonymous {operation} operation is not allowed for entity type '{entityType.FullName}'."); + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/IAuditTimeProvider.cs b/src/Ling.Audit.EntityFrameworkCore/IAuditTimeProvider.cs new file mode 100644 index 0000000..3aa66ae --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/IAuditTimeProvider.cs @@ -0,0 +1,17 @@ +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Provides timestamps for audit operations. +/// +public interface IAuditTimeProvider +{ + /// + /// Gets the current time in UTC. + /// + DateTimeOffset GetUtcNow(); +} + +internal sealed class SystemAuditTimeProvider : IAuditTimeProvider +{ + public DateTimeOffset GetUtcNow() => DateTimeOffset.UtcNow; +} diff --git a/src/Ling.Audit.EntityFrameworkCore/IAuditUserProvider.cs b/src/Ling.Audit.EntityFrameworkCore/IAuditUserProvider.cs new file mode 100644 index 0000000..8b14ae7 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/IAuditUserProvider.cs @@ -0,0 +1,91 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; + +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Interface for audit user information. +/// +public interface IAuditUserProvider<[MustNull] TUserId> +{ + /// + /// Gets the identity of user. + /// + TUserId? Id { get; } + + /// + /// Gets the name of user. + /// + string? Name { get; } + + /// + /// Gets the IP address of the user. + /// + string? IPAddress { get; } + + /// + /// Gets the client name or device name of the user. + /// + string? ClientName { get; } +} + +/// +/// Provides an abstract base for managing audit context, including user and client information. +/// +/// Used to represent the unique identifier for the user associated with the audit context. +public abstract class AuditContextProviderBase : IAuditUserProvider +{ + private readonly ICurrentDbContext _currentDbContext; + private readonly Lazy _lazyContext; + + /// + public TUserId? Id => _lazyContext.Value is null ? default : _lazyContext.Value.Id; + + /// + public string? Name => _lazyContext.Value?.Name; + + /// + public string? IPAddress => _lazyContext.Value?.IPAddress; + + /// + public string? ClientName => _lazyContext.Value?.ClientName; + + /// + /// Initializes an instance of the AuditContextProviderBase class with a database context provider. + /// + /// Provides access to the current database context for auditing purposes. + protected AuditContextProviderBase(ICurrentDbContext current) + { + _currentDbContext = current; + _lazyContext = new Lazy(GetAuditContext); + } + + /// + /// Retrieves a service of a specified type from the current database context. + /// + /// Represents the type of service to be retrieved from the database context. + /// Returns the requested service instance or null if not found. + protected TService? GetService() where TService : class + { + return _currentDbContext.Context.GetService(); + } + + /// + /// Retrieves the current audit context, which may be null. It is an abstract method that must be implemented in + /// derived classes. + /// + /// An optional AuditContext object representing the current audit state. + protected abstract AuditContext? GetAuditContext(); + + /// + /// Represents the context for an audit event, including user identification and client details. + /// + /// Represents the unique identifier of the user associated with the audit event. + /// Holds the name of the user involved in the audit event. + /// Contains the IP address from which the user accessed the system. + /// Stores the name of the client application used by the user. + protected sealed record AuditContext( + TUserId? Id, + string? Name, + string? IPAddress, + string? ClientName) : IAuditUserProvider; +} diff --git a/src/Ling.Audit.EntityFrameworkCore/IPropertySerializer.cs b/src/Ling.Audit.EntityFrameworkCore/IPropertySerializer.cs new file mode 100644 index 0000000..3a76d4c --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/IPropertySerializer.cs @@ -0,0 +1,112 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; + +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Interface for serializing and deserializing property values. +/// +public interface IPropertySerializer +{ + /// + /// Converts an object into its string representation based on the specified type. + /// + /// The object to be converted into a string format. + /// Specifies the type of the object being serialized to ensure correct conversion. + /// A string representation of the object, or if the conversion fails. + string? Serialize(object? value, Type valueType); + + /// + /// Converts a string representation into an object of a specified type. It handles potential null values + /// gracefully. + /// + /// The string representation of the object to be converted. + /// Specifies the type of the object that the string will be converted into. + /// Returns the deserialized object or if the input string is . + object? Deserialize(string? value, Type valueType); +} + +internal sealed class DefaultPropertySerializer : IPropertySerializer +{ + private static readonly JsonSerializerOptions DefaultOptions = CreateDefaultOptions(); + private static readonly HashSet AdditionalSimpleTypes = new() + { + typeof(string), + typeof(Guid), + typeof(DateTime), + typeof(DateTimeOffset), + typeof(TimeSpan), + typeof(decimal) + }; + private readonly JsonSerializerOptions _options; + + public DefaultPropertySerializer(JsonSerializerOptions? options) + { + _options = options ?? DefaultOptions; + } + + private static JsonSerializerOptions CreateDefaultOptions() + { +#if NET9_0_OR_GREATER + var options = JsonSerializerOptions.Web; +#else + var options = new JsonSerializerOptions(JsonSerializerDefaults.Web); +#endif + return options; + } + + [RequiresUnreferencedCode("The type being serialized may not be preserved in the trimmed output.")] + public string? Serialize(object? value, Type valueType) + { + if (valueType == null) + { + throw new ArgumentNullException(nameof(valueType)); + } + + if (value == null) + { + return null; + } + + try + { + var typeToCheck = Nullable.GetUnderlyingType(valueType) ?? valueType; + return IsSimpleType(typeToCheck) ? value.ToString() : JsonSerializer.Serialize(value, valueType, _options); + } + catch (Exception ex) + { + throw new InvalidOperationException($"Failed to serialize value of type {valueType.FullName}", ex); + } + } + + [RequiresUnreferencedCode("The type being deserialized may not be preserved in the trimmed output.")] + public object? Deserialize(string? value, Type valueType) + { + if (valueType == null) + { + throw new ArgumentNullException(nameof(valueType)); + } + + if (value == null) + { + return Nullable.GetUnderlyingType(valueType) is null + ? Activator.CreateInstance(valueType) + : null; + } + + try + { + var typeToCheck = Nullable.GetUnderlyingType(valueType) ?? valueType; + return IsSimpleType(typeToCheck) ? Convert.ChangeType(value, typeToCheck) : JsonSerializer.Deserialize(value, valueType, _options); + } + catch (Exception ex) + { + throw new InvalidOperationException($"Failed to deserialize value to type {valueType.FullName}", ex); + } + } + + private static bool IsSimpleType(Type type) + { + return type.IsPrimitive || AdditionalSimpleTypes.Contains(type) || type.IsEnum; + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs new file mode 100644 index 0000000..6c27a13 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs @@ -0,0 +1,91 @@ +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Ling.Audit.EntityFrameworkCore.Internal.Models; +using Microsoft.EntityFrameworkCore.Metadata.Conventions; +using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; +using System.Reflection; + +namespace Ling.Audit.EntityFrameworkCore.Internal; + +/// +/// Plugin to add audit-related conventions to EF Core's convention set. +/// +internal sealed class AuditConventionSetPlugin : IConventionSetPlugin +{ + private readonly ProviderConventionSetBuilderDependencies _dependencies; + + /// + /// Initializes a new instance of the class. + /// + /// The dependencies required for this plugin. + public AuditConventionSetPlugin(ProviderConventionSetBuilderDependencies dependencies) + { + _dependencies = dependencies; + } + + /// + public ConventionSet ModifyConventions(ConventionSet conventionSet) + { + conventionSet.EntityTypeAddedConventions.Add(new AuditIncludeAttributeConvention(_dependencies)); + conventionSet.PropertyAddedConventions.Add(new AuditIgnoreAttributeConvention(_dependencies)); + return conventionSet; + } + + /// + /// Convention to process on entity types. + /// + private sealed class AuditIncludeAttributeConvention : +#if NET8_0_OR_GREATER + TypeAttributeConventionBase +#else + EntityTypeAttributeConventionBase +#endif + { + /// + /// Initializes a new instance of the class. + /// + /// The dependencies required for this convention. + public AuditIncludeAttributeConvention(ProviderConventionSetBuilderDependencies dependencies) + : base(dependencies) + { + } + + /// + protected override void ProcessEntityTypeAdded( + IConventionEntityTypeBuilder entityTypeBuilder, + AuditableAttribute attribute, + IConventionContext context) + { + entityTypeBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, true); + entityTypeBuilder.Metadata.SetAnnotation(Constants.MetadataAnnotationName, new AuditMetadata + { + IsAuditable = true, + AnonymousOperations = attribute.AllowedAnonymous, + }); + } + } + + /// + /// Convention to process on properties and fields. + /// + private sealed class AuditIgnoreAttributeConvention : PropertyAttributeConventionBase + { + /// + /// Initializes a new instance of the class. + /// + /// The dependencies required for this convention. + public AuditIgnoreAttributeConvention(ProviderConventionSetBuilderDependencies dependencies) + : base(dependencies) + { + } + + /// + protected override void ProcessPropertyAdded( + IConventionPropertyBuilder propertyBuilder, + NotAuditedAttribute attribute, + MemberInfo clrMember, + IConventionContext context) + { + propertyBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, false); + } + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs new file mode 100644 index 0000000..762ff3d --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs @@ -0,0 +1,179 @@ +using Ling.Audit.EntityFrameworkCore.Internal.Extensions; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Microsoft.Extensions.Logging; + +namespace Ling.Audit.EntityFrameworkCore.Internal; + +/// +/// Customizes the model building process to configure audit-related entities and behaviors. +/// +/// The type of the user ID used in audit entities. +internal sealed class AuditModelCustomizer : ModelCustomizer +{ + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The dependencies needed for model customization. + /// The factory to create loggers. + public AuditModelCustomizer( + ModelCustomizerDependencies dependencies, + ILoggerFactory loggerFactory) : base(dependencies) + { + _logger = loggerFactory.CreateLogger>(); + } + + /// + public override void Customize(ModelBuilder modelBuilder, DbContext context) + { + modelBuilder.ApplyConfiguration(new AuditEntityLogTypeConfiguration()); + modelBuilder.ApplyConfiguration(new AuditFieldLogTypeConfiguration()); + + base.Customize(modelBuilder, context); + + var auditOptions = context.GetAuditOptions(); + + modelBuilder.ConfigureAuditableEntities(auditOptions, _logger); + + modelBuilder.SetupSoftDeleteQueryFilter(); + + _logger.LogInformation("Complete the audit entity model configuration."); + } + + /// + /// Configures the entity type. + /// + private sealed class AuditEntityLogTypeConfiguration : IEntityTypeConfiguration> + { + /// + /// Configures the entity type. + /// + /// The builder to be used to configure the entity type. + public void Configure(EntityTypeBuilder> builder) + { +#if NET7_0_OR_GREATER + builder.ToTable(nameof(AuditEntityChangeLog), t => t.HasComment("Table to record changes in entities.")) + .HasKey(al => al.Id); +#else + builder.ToTable(nameof(AuditEntityChangeLog)) + .HasComment("Table to record changes in entities."); + + builder.HasKey(al => al.Id); +#endif + + builder.Property(al => al.Id) + .ValueGeneratedOnAdd() + .HasComment("Primary key."); + + builder.Property(al => al.DatabaseSchema) + .IsUnicode(false) + .HasMaxLength(64) + .HasComment("Database schema name."); + + builder.Property(al => al.TableName) + .IsUnicode(false) + .HasMaxLength(128) + .HasComment("Table name."); + + builder.Property(al => al.EntityKey) + .IsUnicode(false) + .HasMaxLength(512) + .HasComment("Primary key of the changed entity."); + + builder.Property(al => al.EntityTypeName) + .IsUnicode(false) + .HasMaxLength(64) + .HasComment("Type of the changed entity."); + + builder.Property(al => al.EventType) + .IsUnicode(false) + .HasMaxLength(16) + .HasConversion() + .HasComment("Type of the audit event."); + + builder.Property(al => al.EventTime) + .HasComment("Time the audit event occurred."); + + builder.Property(al => al.UserId) + .IsRequired(false) + .HasComment("Identity of the user who changed the entity."); + + builder.Property(al => al.UserName) + .IsUnicode(true) + .HasMaxLength(256) + .IsRequired(false) + .HasComment("Name of the user who changed the entity."); + + builder.Property(al => al.IPAddress) + .IsUnicode(false) + .HasMaxLength(64) + .IsRequired(false) + .HasComment("IP address of the client that made the change."); + + builder.Property(al => al.ClientName) + .IsUnicode(true) + .HasMaxLength(512) + .IsRequired(false) + .HasComment("Name of the client that made the change."); + + builder.HasIndex(al => new { al.EntityTypeName, al.EntityKey, al.EventTime }); + builder.HasIndex(al => new { al.UserId, al.EventTime }); + + builder.HasMany(al => al.Details) + .WithOne() + .HasForeignKey(ald => ald.EntityLogId) + .OnDelete(DeleteBehavior.Cascade); + } + } + + /// + /// Configures the entity type. + /// + private sealed class AuditFieldLogTypeConfiguration : IEntityTypeConfiguration + { + /// + /// Configures the entity type. + /// + /// The builder to be used to configure the entity type. + public void Configure(EntityTypeBuilder builder) + { +#if NET7_0_OR_GREATER + builder.ToTable(nameof(AuditFieldChangeLog), t => t.HasComment("Table to record changes in entity fields.")) + .HasKey(al => al.Id); +#else + builder.ToTable(nameof(AuditFieldChangeLog)) + .HasComment("Table to record changes in entity fields."); + + builder.HasKey(al => al.Id); +#endif + + builder.Property(al => al.Id) + .ValueGeneratedOnAdd() + .HasComment("Primary key."); + + builder.Property(al => al.EntityLogId) + .HasComment("Primary key of the associated entity change log."); + + builder.Property(al => al.FieldName) + .IsUnicode(false) + .HasMaxLength(256) + .HasComment("Name of the field (format: entity class name + '.' + field name)."); + + builder.Property(al => al.ValueType) + .IsUnicode(false) + .HasMaxLength(256) + .HasComment("Type of the field value."); + + builder.Property(al => al.OriginalValue) + .IsUnicode(true) + .HasComment("Original value of the field."); + + builder.Property(al => al.NewValue) + .IsUnicode(true) + .HasComment("New value of the field."); + } + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditSaveChangesInterceptor.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditSaveChangesInterceptor.cs new file mode 100644 index 0000000..67511a2 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditSaveChangesInterceptor.cs @@ -0,0 +1,355 @@ +using Ling.Audit.EntityFrameworkCore.Internal.Extensions; +using Ling.Audit.EntityFrameworkCore.Internal.Models; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.Logging; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace Ling.Audit.EntityFrameworkCore.Internal; + +internal sealed class AuditSaveChangesInterceptor : SaveChangesInterceptor +{ + private readonly ConditionalWeakTable _states = new(); + + public override InterceptionResult SavingChanges( + DbContextEventData eventData, + InterceptionResult result) + { + InternalSavingChangesAsync(eventData, default).ConfigureAwait(false).GetAwaiter().GetResult(); + return base.SavingChanges(eventData, result); + } + + public override async ValueTask> SavingChangesAsync( + DbContextEventData eventData, + InterceptionResult result, + CancellationToken cancellationToken = default) + { + await InternalSavingChangesAsync(eventData, cancellationToken).ConfigureAwait(false); + return await base.SavingChangesAsync(eventData, result, cancellationToken).ConfigureAwait(false); + } + + public override int SavedChanges(SaveChangesCompletedEventData eventData, int result) + { + InternalSavedChanges(eventData, async: false, default).ConfigureAwait(false).GetAwaiter().GetResult(); + return result; + } + + public override async ValueTask SavedChangesAsync( + SaveChangesCompletedEventData eventData, + int result, + CancellationToken cancellationToken = default) + { + await InternalSavedChanges(eventData, async: true, cancellationToken).ConfigureAwait(false); + return result; + } + + public override void SaveChangesFailed(DbContextErrorEventData eventData) + { + if (eventData.Context is { } context) + { + _states.Remove(context); + } + + base.SaveChangesFailed(eventData); + } + + public override Task SaveChangesFailedAsync( + DbContextErrorEventData eventData, + CancellationToken cancellationToken = default) + { + if (eventData.Context is { } context) + { + _states.Remove(context); + } + + return base.SaveChangesFailedAsync(eventData, cancellationToken); + } + + internal async Task InternalSavingChangesAsync( + DbContextEventData eventData, + CancellationToken cancellationToken) + { + var context = eventData.Context; + if (context is null) + { + return; + } + + if (_states.TryGetValue(context, out var activeState) && activeState.IsSavingAuditLogs) + { + return; + } + + _states.Remove(context); + var state = new SaveState(); + _states.Add(context, state); + + try + { + var userProvider = context.GetService>(); + var handler = context.GetService(); + var timeProvider = context.GetService(); + var options = context.GetAuditOptions(); + var now = timeProvider.GetUtcNow(); + var userId = userProvider.Id; + var isAnonymous = EqualityComparer.Default.Equals(userId, default); + var entries = new List(); + + foreach (var entityEntry in context.ChangeTracker.Entries()) + { + var entityType = entityEntry.Metadata.ClrType; + var metadata = entityEntry.Metadata.GetAuditMetadata(); + var eventType = AuditEventType.None; + + switch (entityEntry.State) + { + case EntityState.Deleted: + if (metadata.HasDeletedAt) + { + entityEntry.Property(Constants.DeletedAt).CurrentValue = now; + } + + if (metadata.HasDeletedBy) + { + await EnsureUserAsync( + options, metadata, handler, isAnonymous, entityType, + DataOperation.Delete, entityEntry.Entity, cancellationToken).ConfigureAwait(false); + entityEntry.Property(Constants.DeletedBy).CurrentValue = userId; + } + + if (metadata.HasIsDeleted) + { + entityEntry.Property(Constants.IsDeleted).CurrentValue = true; + entityEntry.State = EntityState.Modified; + eventType = AuditEventType.SoftDelete; + } + else + { + eventType = AuditEventType.Delete; + } + break; + + case EntityState.Modified: + if (metadata.HasModifiedAt) + { + entityEntry.Property(Constants.ModifiedAt).CurrentValue = now; + } + + if (metadata.HasModifiedBy) + { + await EnsureUserAsync( + options, metadata, handler, isAnonymous, entityType, + DataOperation.Modify, entityEntry.Entity, cancellationToken).ConfigureAwait(false); + entityEntry.Property(Constants.ModifiedBy).CurrentValue = userId; + } + + eventType = GetModifiedType(entityEntry, metadata); + break; + + case EntityState.Added: + if (metadata.HasCreatedAt) + { + entityEntry.Property(Constants.CreatedAt).CurrentValue = now; + } + + if (metadata.HasCreatedBy) + { + await EnsureUserAsync( + options, metadata, handler, isAnonymous, entityType, + DataOperation.Create, entityEntry.Entity, cancellationToken).ConfigureAwait(false); + entityEntry.Property(Constants.CreatedBy).CurrentValue = userId; + } + + eventType = AuditEventType.Create; + break; + } + + if (eventType is not AuditEventType.None && TryGetAuditEntry(entityEntry, out var auditEntry)) + { + auditEntry.EventType = eventType; + entries.Add(auditEntry); + } + } + + if (AppContext.TryGetSwitch(AuditDefaults.DisableAuditingSwitch, out var disabled) && disabled) + { + _states.Remove(context); + return; + } + + if (entries.Count > 0 && + options.TransactionMode is AuditTransactionMode.RequireExplicitTransaction && + context.Database.IsRelational() && + context.Database.CurrentTransaction is null) + { + throw new InvalidOperationException( + "AuditOptions.TransactionMode requires an explicit database transaction. " + + "Begin a transaction before calling SaveChanges so entity changes and audit logs are atomic."); + } + + state.Entries = entries; + state.OccurredAt = now; + state.UserId = userId; + state.UserName = userProvider.Name; + state.IPAddress = userProvider.IPAddress; + state.ClientName = userProvider.ClientName; + } + catch + { + _states.Remove(context); + throw; + } + } + + private async Task InternalSavedChanges( + SaveChangesCompletedEventData eventData, + bool async, + CancellationToken cancellationToken) + { + var context = eventData.Context; + if (context is null || !_states.TryGetValue(context, out var state) || state.IsSavingAuditLogs) + { + return; + } + + try + { + var options = context.GetAuditOptions(); + var serializer = context.GetService(); + var logger = context.GetService().CreateLogger(GetType()); + var entityCount = 0; + var fieldCount = 0; + + foreach (var entry in state.Entries) + { + var log = new AuditEntityChangeLog + { + DatabaseSchema = entry.Schema, + TableName = entry.Table, + EntityKey = entry.PrimaryKey, + EntityTypeName = entry.EntityType, + EventType = entry.EventType, + EventTime = state.OccurredAt, + UserId = state.UserId, + UserName = state.UserName, + IPAddress = state.IPAddress, + ClientName = state.ClientName, + Details = entry.Properties.ConvertAll(property => new AuditFieldChangeLog + { + FieldName = entry.EntityType + '.' + property.Name, + OriginalValue = serializer.Serialize(property.OriginalValue, property.ValueType), + NewValue = serializer.Serialize(property.NewValue, property.ValueType), + ValueType = property.ValueType.AssemblyQualifiedName ?? property.ValueType.FullName ?? property.ValueType.Name, + }), + }; + + if (log.Details.Count == 0 && !options.AuditNoFieldChangeEntity) + { + continue; + } + + context.Add(log); + entityCount++; + fieldCount += log.Details.Count; + } + + if (entityCount > 0) + { + state.IsSavingAuditLogs = true; + if (async) + { + await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + else + { + context.SaveChanges(); + } + } + + logger.LogInformation( + "Added {EntityCount} entity and {FieldCount} field audit logs to {DbContextType}[{ContextId}].", + entityCount, + fieldCount, + context.GetType().GetFriendlyName(), + context.ContextId); + } + finally + { + _states.Remove(context); + } + } + + private static Task EnsureUserAsync( + AuditOptions options, + AuditMetadata metadata, + IAuditAnonymousHandler handler, + bool isAnonymous, + Type entityType, + DataOperation operation, + object entity, + CancellationToken cancellationToken) + { + return !options.AllowAnonymous && !metadata.IsAnonymousAllowed(operation) && isAnonymous + ? handler.HandleAsync(entityType, operation, entity, cancellationToken) + : Task.CompletedTask; + } + + private static bool TryGetAuditEntry( + EntityEntry entityEntry, + [NotNullWhen(true)] out AuditEntityEntry? auditEntry) + { + if (!entityEntry.Metadata.IsAuditable()) + { + auditEntry = null; + return false; + } + + auditEntry = new AuditEntityEntry(entityEntry); + foreach (var propertyEntry in entityEntry.Properties) + { + if (propertyEntry.Metadata.IsAuditable() && + (entityEntry.State is EntityState.Added || + !Equals(propertyEntry.OriginalValue, propertyEntry.CurrentValue))) + { + auditEntry.Properties.Add(new AuditPropertyEntry + { + Name = propertyEntry.Metadata.Name, + ValueType = propertyEntry.Metadata.ClrType, + OriginalValue = entityEntry.State is EntityState.Added ? null : propertyEntry.OriginalValue, + NewValue = entityEntry.State is EntityState.Deleted ? null : propertyEntry.CurrentValue, + }); + } + } + + return true; + } + + private static AuditEventType GetModifiedType(EntityEntry entityEntry, AuditMetadata metadata) + { + if (metadata.HasIsDeleted) + { + var originalValue = (bool)entityEntry.Property(Constants.IsDeleted).OriginalValue!; + var newValue = (bool)entityEntry.Property(Constants.IsDeleted).CurrentValue!; + if (originalValue != newValue) + { + return newValue ? AuditEventType.SoftDelete : AuditEventType.Recovery; + } + } + + return AuditEventType.Modify; + } + + private sealed class SaveState + { + public IReadOnlyList Entries { get; set; } = []; + public DateTimeOffset OccurredAt { get; set; } + public TUserId? UserId { get; set; } + public string? UserName { get; set; } + public string? IPAddress { get; set; } + public string? ClientName { get; set; } + public bool IsSavingAuditLogs { get; set; } + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs new file mode 100644 index 0000000..3f29180 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs @@ -0,0 +1,35 @@ +using Microsoft.Extensions.Configuration; + +namespace Ling.Audit.EntityFrameworkCore.Internal; + +internal static class Constants +{ + /// + /// The key for the configuration. + /// It will be used to get the from 's section. + /// + public const string ConfigurationSection = "Audit"; + + public const string AuditableAnnotationName = "Ling:Audit:Auditable"; + public const string MetadataAnnotationName = "Ling:Audit:Metadata"; + + public const string Id = "Id"; + public const string CreatedAt = nameof(IHasCreationTime.CreatedAt); + public const string CreatedBy = nameof(IHasCreator.CreatedBy); + public const string ModifiedAt = nameof(IHasModificationTime.LastModifiedAt); + public const string ModifiedBy = nameof(IHasModifier.LastModifiedBy); + public const string IsDeleted = nameof(ISoftDelete.IsDeleted); + public const string DeletedAt = nameof(IHasDeletionTime.DeletedAt); + public const string DeletedBy = nameof(IHasDeleter.DeletedBy); + + public static readonly IReadOnlyCollection PropertyNames = + [ + CreatedAt, + CreatedBy, + ModifiedAt, + ModifiedBy, + IsDeleted, + DeletedAt, + DeletedBy, + ]; +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs new file mode 100644 index 0000000..7c57114 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs @@ -0,0 +1,96 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; + +namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; + +internal sealed class AuditOptionsExtension : IDbContextOptionsExtension + where TUserProvider : class, IAuditUserProvider +{ + public Action? Action { get; } + + /// + public DbContextOptionsExtensionInfo Info => new ExtensionInfo(this); + + public AuditOptionsExtension(Action? setupAction) + { + Action = setupAction; + } + + public AuditOptionsExtension([NotNull] AuditOptionsExtension copyFrom) + { + Action = copyFrom.Action; + } + + /// + public void ApplyServices(IServiceCollection services) + { + JsonSerializerOptions? jsonSerializerOptions = null; + + // Configure audit options + if (Action is null) + { + services.AddOptions() + .Configure((options, context) => + context.Context.GetService() + .GetSection(Constants.ConfigurationSection) + .Bind(options)); + } + else + { + services.Configure(Action); + + var tempOptions = new AuditOptions(); + Action.Invoke(tempOptions); + jsonSerializerOptions = tempOptions.PropertySerializerOptions; + } + + // Add serializer for property conversion + services.TryAddSingleton( + new DefaultPropertySerializer(jsonSerializerOptions)); + + // Add handler for anonymous audit operations + services.TryAddSingleton(); + + // Add the UTC time source used for audit fields and log events. + services.TryAddSingleton(); + + // Add custom plugin for audit annotations + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + + // Add audit context for user + services.TryAddScoped, TUserProvider>(); + } + + /// + public void Validate(IDbContextOptions options) + { + } + + private class ExtensionInfo : DbContextOptionsExtensionInfo + { + private readonly AuditOptionsExtension _extension; + + public override bool IsDatabaseProvider { get; } + public override string LogFragment { get; } = string.Empty; + + public ExtensionInfo(IDbContextOptionsExtension extension) : base(extension) + { + _extension = (AuditOptionsExtension)extension; + } + + public override int GetServiceProviderHashCode() => _extension.Action?.GetHashCode() ?? 0; + + public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => + other is ExtensionInfo info && ReferenceEquals(_extension.Action, info._extension.Action); + + public override void PopulateDebugInfo(IDictionary debugInfo) + { + debugInfo["Ling.Audit:Options"] = GetServiceProviderHashCode().ToString(); + } + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs new file mode 100644 index 0000000..2d89381 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs @@ -0,0 +1,40 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.Extensions.Options; +using System.Text.Json; + +namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; + +internal static class DbContextExtensions +{ + internal static AuditOptions GetAuditOptions(this DbContext context) + { + return context.GetService>().Value; + } + + /// + /// Gets the primary key value(s) of the entity as a string. + /// + /// The entity entry. + /// A string representation of the primary key(s) in format "Key1=Value1,Key2=Value2". + /// Thrown when is null. + internal static string GetPrimaryKey(this EntityEntry entityEntry) + { + ThrowHelper.ThrowIfNull(entityEntry); + + return entityEntry.Metadata.FindPrimaryKey()?.GetPrimaryKey(entityEntry) ?? string.Empty; + } + + internal static string GetPrimaryKey(this IKey key, EntityEntry entityEntry) + { + ThrowHelper.ThrowIfNull(key); + ThrowHelper.ThrowIfNull(entityEntry); + + var values = key.Properties.ToDictionary( + property => property.Name, + property => entityEntry.Property(property.Name).CurrentValue); + return JsonSerializer.Serialize(values); + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ReflectionExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ReflectionExtensions.cs new file mode 100644 index 0000000..69fffbf --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ReflectionExtensions.cs @@ -0,0 +1,39 @@ +using System.Text; + +namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; + +/// +/// Extension methods for reflection operations. +/// +internal static class ReflectionExtensions +{ + /// + /// Gets a friendly name for the type, handling generic type definitions. + /// + /// The type to get the friendly name for. + /// A readable string representation of the type name. + /// Thrown when is null. + internal static string GetFriendlyName(this Type type) + { + ArgumentNullException.ThrowIfNull(type); + + if (!type.IsGenericType) + { + return type.Name; + } + + var builder = new StringBuilder(); + var nameParts = type.Name.Split('`'); + builder.Append(nameParts[0]); + + var genericArgs = type.GetGenericArguments(); + if (genericArgs.Length > 0) + { + builder.Append('<'); + builder.AppendJoin(",", genericArgs.Select(t => t.GetFriendlyName())); + builder.Append('>'); + } + + return builder.ToString(); + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditEntityEntry.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditEntityEntry.cs new file mode 100644 index 0000000..99d1c53 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditEntityEntry.cs @@ -0,0 +1,59 @@ +using Ling.Audit.EntityFrameworkCore.Internal.Extensions; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; + +namespace Ling.Audit.EntityFrameworkCore.Internal.Models; + +/// +/// Represents an entity entry for auditing purposes, containing temporary tracking information +/// before and during the save operation. +/// +internal sealed class AuditEntityEntry +{ + /// + /// Gets the original entity entry. + /// + public EntityEntry EntityEntry { get; } + + /// + /// Gets the database schema name. + /// + public string? Schema { get; } + + /// + /// Gets the database table name. + /// + public string? Table { get; } + + /// + /// Gets the primary key value of the entity. + /// + public string PrimaryKey => EntityEntry.GetPrimaryKey(); + + /// + /// Gets or sets the entity type name. + /// + public string EntityType { get; set; } = default!; + + /// + /// Gets or sets the type of change event. + /// + public AuditEventType EventType { get; set; } + + /// + /// Gets or sets the collection of property changes. + /// + public List Properties { get; set; } = new(); + + /// + /// Initializes a new instance of the class. + /// + /// The entity entry being audited. + public AuditEntityEntry(EntityEntry entry) + { + EntityEntry = entry; + Schema = entry.Metadata.GetSchema(); + Table = entry.Metadata.GetTableName(); + EntityType = entry.Metadata.DisplayName(); + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditMetadata.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditMetadata.cs new file mode 100644 index 0000000..31cf90a --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditMetadata.cs @@ -0,0 +1,78 @@ +namespace Ling.Audit.EntityFrameworkCore.Internal.Models; + +/// +/// Represents audit metadata for an entity type. +/// +internal sealed class AuditMetadata +{ + public bool IsAuditable { get; set; } + + /// + /// Gets or sets the operations that can be performed anonymously. + /// + public DataOperation AnonymousOperations { get; set; } + + /// + /// Gets or sets the type of the user ID. + /// + public Type? UserIdType { get; set; } + + /// + /// Gets or sets a value indicating whether the entity has a CreatedAt property. + /// + public bool HasCreatedAt { get; set; } + + /// + /// Gets or sets a value indicating whether the entity has a CreatedBy property. + /// + public bool HasCreatedBy { get; set; } + + /// + /// Gets or sets a value indicating whether the entity has a ModifiedAt property. + /// + public bool HasModifiedAt { get; set; } + + /// + /// Gets or sets a value indicating whether the entity has a ModifiedBy property. + /// + public bool HasModifiedBy { get; set; } + + /// + /// Gets or sets a value indicating whether the entity has an IsDeleted property. + /// + public bool HasIsDeleted { get; set; } + + /// + /// Gets or sets a value indicating whether the entity has a DeletedAt property. + /// + public bool HasDeletedAt { get; set; } + + /// + /// Gets or sets a value indicating whether the entity has a DeletedBy property. + /// + public bool HasDeletedBy { get; set; } + + /// + /// Determines whether the specified operation can be performed anonymously. + /// + /// The operation to check. + /// if the operation can be performed anonymously; otherwise, . + public bool IsAnonymousAllowed(DataOperation operate) => AnonymousOperations.HasFlag(operate); + + /// + /// Combines two instances using the bitwise OR operator. + /// + public static AuditMetadata operator |(AuditMetadata left, AuditMetadata right) => new() + { + IsAuditable = right.IsAuditable, + AnonymousOperations = left.AnonymousOperations | right.AnonymousOperations, + UserIdType = left.UserIdType ?? right.UserIdType, + HasCreatedAt = left.HasCreatedAt || right.HasCreatedAt, + HasCreatedBy = left.HasCreatedBy || right.HasCreatedBy, + HasModifiedAt = left.HasModifiedAt || right.HasModifiedAt, + HasModifiedBy = left.HasModifiedBy || right.HasModifiedBy, + HasIsDeleted = left.HasIsDeleted || right.HasIsDeleted, + HasDeletedAt = left.HasDeletedAt || right.HasDeletedAt, + HasDeletedBy = left.HasDeletedBy || right.HasDeletedBy + }; +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditPropertyEntry.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditPropertyEntry.cs new file mode 100644 index 0000000..5ab33e6 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditPropertyEntry.cs @@ -0,0 +1,27 @@ +namespace Ling.Audit.EntityFrameworkCore.Internal.Models; + +/// +/// Represents temporary tracking information for a property change during auditing. +/// +internal sealed class AuditPropertyEntry +{ + /// + /// Gets or sets the property name. + /// + public string Name { get; set; } = default!; + + /// + /// Gets or sets the original value before change. + /// + public object? OriginalValue { get; set; } + + /// + /// Gets or sets the new value after change. + /// + public object? NewValue { get; set; } + + /// + /// Gets or sets the type of the property value. + /// + public Type ValueType { get; set; } = default!; +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/ThrowHelper.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/ThrowHelper.cs new file mode 100644 index 0000000..864da2a --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/ThrowHelper.cs @@ -0,0 +1,31 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace Ling.Audit.EntityFrameworkCore.Internal; + +internal static class ThrowHelper +{ + public static void ThrowIfNull([NotNull] object? value, [CallerArgumentExpression(nameof(value))] string? paramName = null) + { + if (value is null) + { + throw new ArgumentNullException(paramName); + } + } + + public static void ThrowIfNullOrEmpty([NotNull] string? value, [CallerArgumentExpression(nameof(value))] string? paramName = null) + { + if (string.IsNullOrEmpty(value)) + { + throw new ArgumentException("Value cannot be null or empty.", paramName); + } + } + + public static void ThrowIfNullOrWhiteSpace([NotNull] string? value, [CallerArgumentExpression(nameof(value))] string? paramName = null) + { + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Value cannot be null or whitespace.", paramName); + } + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj b/src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj new file mode 100644 index 0000000..c1781bd --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj @@ -0,0 +1,52 @@ + + + + net6.0;net7.0;net8.0;net9.0 + true + $(NoWarn);IDE0130 + Ling.Audit.EntityFrameworkCore + Entity Framework Core integration for Ling.Audit. + ling;audit;entity-framework-core;soft-delete + Apache-2.0 + https://github.com/ling921/ling-audit + $(RepositoryUrl) + README.md + icon.png + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_Parameter1>Ling.Audit.AspNetCore + + + + diff --git a/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs b/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs new file mode 100644 index 0000000..c1da31e --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs @@ -0,0 +1,72 @@ +using Microsoft.EntityFrameworkCore.ChangeTracking; +using System.Diagnostics; + +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Represents the audit log for entities. +/// +/// The type of the user ID. +[DebuggerDisplay("Schema = {DatabaseSchema}, Table = {TableName}, PrimaryKey = {EntityKey}, EventType = {EventType}, PropertyCount = {Details.Count}")] +public class AuditEntityChangeLog<[MustNull] TUserId> +{ + /// + /// Gets or sets the primary key. + /// + public long Id { get; set; } + + /// + /// Gets or sets the schema of the database. + /// + public string? DatabaseSchema { get; set; } + + /// + /// Gets or sets the table name of the data changed. + /// + public string? TableName { get; set; } + + /// + /// Gets or sets the primary key of the . + /// + public string EntityKey { get; set; } = default!; + + /// + /// Gets or sets the type name of the changed entity. + /// + public string EntityTypeName { get; set; } = default!; + + /// + /// Gets or sets the type of the audit event. + /// + public AuditEventType EventType { get; set; } + + /// + /// Gets or sets the time the audit event occurred. + /// + public DateTimeOffset EventTime { get; set; } + + /// + /// Gets or sets the identity of the user who changed the entity. + /// + public TUserId? UserId { get; set; } + + /// + /// Gets or sets the name of the user who changed the entity. + /// + public string? UserName { get; set; } + + /// + /// Gets or sets the IP address of the client that made the change. + /// + public string? IPAddress { get; set; } + + /// + /// Gets or sets the name of the client that made the change. + /// + public string? ClientName { get; set; } + + /// + /// Gets or sets the details of this audit log. + /// + public virtual ICollection Details { get; set; } = []; +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Models/AuditEventType.cs b/src/Ling.Audit.EntityFrameworkCore/Models/AuditEventType.cs new file mode 100644 index 0000000..8c38808 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Models/AuditEventType.cs @@ -0,0 +1,37 @@ +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Enum that specifies audit event type. +/// +public enum AuditEventType +{ + /// + /// No event. + /// + None, + + /// + /// Event for creating an entity. + /// + Create, + + /// + /// Event for modifying an entity. + /// + Modify, + + /// + /// Event for deleting an entity. + /// + Delete, + + /// + /// Event for soft deleting an entity. + /// + SoftDelete, + + /// + /// Event for recovering a soft-deleted entity. + /// + Recovery, +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Models/AuditFieldChangeLog.cs b/src/Ling.Audit.EntityFrameworkCore/Models/AuditFieldChangeLog.cs new file mode 100644 index 0000000..0b69277 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Models/AuditFieldChangeLog.cs @@ -0,0 +1,40 @@ +using System.Diagnostics; + +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Represents the detail of . +/// +[DebuggerDisplay("{FieldName} = {OriginalValue} => {NewValue}, Type = {ValueType}")] +public class AuditFieldChangeLog +{ + /// + /// Gets or sets the primary key. + /// + public long Id { get; set; } + + /// + /// Gets or sets the primary key of . + /// + public long EntityLogId { get; set; } + + /// + /// Gets or sets the field name. + /// + public string FieldName { get; set; } = default!; + + /// + /// Gets or sets the type of the value. + /// + public string ValueType { get; set; } = default!; + + /// + /// Gets or sets the original value. + /// + public string? OriginalValue { get; set; } + + /// + /// Gets or sets the new value. + /// + public string? NewValue { get; set; } +} diff --git a/src/Ling.Audit.SourceGenerators/AnalyzerReleases.Shipped.md b/src/Ling.Audit.SourceGenerators/AnalyzerReleases.Shipped.md index 3475bc6..4116258 100644 --- a/src/Ling.Audit.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/Ling.Audit.SourceGenerators/AnalyzerReleases.Shipped.md @@ -1,14 +1,24 @@ ; Shipped analyzer releases ; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md -## Release 1.0.0 + +## Release 2.0.1 + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|-------------------- +LA002 | Design | Error | LA002_MustNullAttributeAnalyzer + + +## Release 2.0.0 ### New Rules Rule ID | Category | Severity | Notes --------|----------|----------|-------------------- -LA001 | Design | Error | LA001_MustNullAttributeAnalyzer [Documentation](LA001_Documentation_Link) -LA101 | Design | Error | LA101_AuditTypeAnalyzer, [Documentation](LA101_Documentation_Link) -LA102 | Design | Warning | LA102_AuditTypeAnalyzer, [Documentation](LA102_Documentation_Link) -LA103 | Design | Error | LA103__AuditKeyTypeAnalyzer [Documentation](LA103_Documentation_Link) -LA901 | Design | Info | LA901__AuditInterfaceAnalyzer [Documentation](LA901_Documentation_Link) +LA001 | Design | Error | LA001_MustNullAttributeAnalyzer +LA101 | Design | Error | LA101_AuditTypeAnalyzer +LA102 | Design | Warning | LA102_AuditTypeAnalyzer +LA103 | Design | Error | LA103__AuditKeyTypeAnalyzer +LA901 | Design | Info | LA901__AuditInterfaceAnalyzer diff --git a/src/Ling.Audit.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/Ling.Audit.SourceGenerators/AnalyzerReleases.Unshipped.md index b1b99aa..6eea619 100644 --- a/src/Ling.Audit.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/src/Ling.Audit.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -1,3 +1,2 @@ ; Unshipped analyzer release ; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md - diff --git a/src/Ling.Audit.SourceGenerators/Analyzers/AuditTypeAnalyzer.cs b/src/Ling.Audit.SourceGenerators/Analyzers/AuditTypeAnalyzer.cs index 2c4f5dc..f3ddefa 100644 --- a/src/Ling.Audit.SourceGenerators/Analyzers/AuditTypeAnalyzer.cs +++ b/src/Ling.Audit.SourceGenerators/Analyzers/AuditTypeAnalyzer.cs @@ -56,11 +56,6 @@ private static void AnalyzeNode(SyntaxNodeAnalysisContext context) private static void AnalyzeReferenceTypeDeclarationNode(SyntaxNodeAnalysisContext context, TypeDeclarationSyntax typeDeclaration, INamedTypeSymbol typeSymbol) { - if (typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword)) - { - return; - } - var existingProperties = typeSymbol.GetMembers() .Where(m => m.Kind == SymbolKind.Property) .Cast() @@ -69,20 +64,35 @@ private static void AnalyzeReferenceTypeDeclarationNode(SyntaxNodeAnalysisContex .Select(p => p.Name) .ToList(); - foreach (var propertyName in GetAuditPropertyNames(context, typeSymbol)) + var requiresGeneration = GetAuditPropertyNames(context, typeSymbol) + .Any(propertyName => !existingProperties.Contains(propertyName)); + if (!requiresGeneration) + { + return; + } + + foreach (var containingType in typeDeclaration.Ancestors().OfType()) { - if (!existingProperties.Contains(propertyName)) + if (!containingType.Modifiers.Any(SyntaxKind.PartialKeyword)) { - var typeName = typeSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); + var containingSymbol = context.SemanticModel.GetDeclaredSymbol(containingType, context.CancellationToken); var diagnostic = Diagnostic.Create( DiagnosticDescriptors.PartialType, - typeDeclaration.Identifier.GetLocation(), - typeName); + containingType.Identifier.GetLocation(), + containingSymbol?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) ?? containingType.Identifier.Text); context.ReportDiagnostic(diagnostic); - return; } } + + if (!typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword)) + { + var typeName = typeSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); + context.ReportDiagnostic(Diagnostic.Create( + DiagnosticDescriptors.PartialType, + typeDeclaration.Identifier.GetLocation(), + typeName)); + } } private static void AnalyzeValueTypeDeclarationNode(SyntaxNodeAnalysisContext context, TypeDeclarationSyntax typeDeclaration, INamedTypeSymbol typeSymbol) diff --git a/src/Ling.Audit.SourceGenerators/Analyzers/MustNullAttributeAnalyzer.cs b/src/Ling.Audit.SourceGenerators/Analyzers/MustNullAttributeAnalyzer.cs index 8f0e3d4..9383ee1 100644 --- a/src/Ling.Audit.SourceGenerators/Analyzers/MustNullAttributeAnalyzer.cs +++ b/src/Ling.Audit.SourceGenerators/Analyzers/MustNullAttributeAnalyzer.cs @@ -13,7 +13,8 @@ internal class MustNullAttributeAnalyzer : DiagnosticAnalyzer { public override ImmutableArray SupportedDiagnostics => [ - DiagnosticDescriptors.TypeParameterMustBeNullable + DiagnosticDescriptors.TypeParameterMustBeNullable, + DiagnosticDescriptors.ParameterTypeMustBeNullable ]; public override void Initialize(AnalysisContext context) @@ -29,7 +30,8 @@ public override void Initialize(AnalysisContext context) SyntaxKind.VariableDeclaration, SyntaxKind.MethodDeclaration, SyntaxKind.Parameter, - SyntaxKind.DelegateDeclaration); + SyntaxKind.DelegateDeclaration, + SyntaxKind.InvocationExpression); } private static void AnalyzeNode(SyntaxNodeAnalysisContext context) @@ -63,6 +65,10 @@ private static void AnalyzeNode(SyntaxNodeAnalysisContext context) case DelegateDeclarationSyntax delegateDeclaration: AnalyzeDelegateDeclaration(context, delegateDeclaration); break; + + case InvocationExpressionSyntax invocation: + AnalyzeInvocation(context, invocation); + break; } } @@ -119,6 +125,14 @@ private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context, { CheckGenericTypeArguments(context, genericReturnType); } + + if (methodDeclaration.TypeParameterList != null) + { + foreach (var typeParam in methodDeclaration.TypeParameterList.Parameters) + { + AnalyzeTypeParameterDeclaration(context, typeParam); + } + } } private static void AnalyzeParameter(SyntaxNodeAnalysisContext context, ParameterSyntax parameter) @@ -137,29 +151,111 @@ private static void AnalyzeDelegateDeclaration(SyntaxNodeAnalysisContext context } } + private static void AnalyzeInvocation(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocation) + { + ExpressionSyntax? expression = invocation.Expression; + while (expression is not null) + { + if (expression is GenericNameSyntax genericName) + { + CheckGenericTypeArguments(context, genericName); + expression = null; + } + else if (expression is IdentifierNameSyntax identifierName) + { + if (context.SemanticModel.GetSymbolInfo(identifierName) is { Symbol: IMethodSymbol methodSymbol }) + { + CheckGenericMethodSymbol(context, methodSymbol, identifierName); + } + expression = null; + } + else if (expression is MemberAccessExpressionSyntax memberAccess) + { + if (memberAccess.Name is GenericNameSyntax genericName2) + { + CheckGenericTypeArguments(context, genericName2); + } + else if (memberAccess.Name is IdentifierNameSyntax identifierName2 && + context.SemanticModel.GetSymbolInfo(memberAccess) is { Symbol: IMethodSymbol methodSymbol }) + { + CheckGenericMethodSymbol(context, methodSymbol, identifierName2); + } + expression = null; + } + else if (expression is InvocationExpressionSyntax invocationExpression) + { + expression = invocationExpression.Expression; + } + else + { + expression = null; + } + } + } + private static void CheckGenericTypeArguments(SyntaxNodeAnalysisContext context, GenericNameSyntax genericName) { - if (context.SemanticModel.GetSymbolInfo(genericName).Symbol is not INamedTypeSymbol typeSymbol) + var symbolInfo = context.SemanticModel.GetSymbolInfo(genericName); + if (symbolInfo is { Symbol: INamedTypeSymbol typeSymbol }) { - return; + var mustNullAttribute = GetMustNullAttributeSymbol(context.Compilation); + + for (var i = 0; i < typeSymbol.TypeArguments.Length; i++) + { + var argument = typeSymbol.TypeArguments[i]; + var argumentSyntax = genericName.TypeArgumentList.Arguments[i]; + + // Check if current type parameter has MustNullAttribute or its base type has + if (HasAttributeSymbol(typeSymbol.TypeParameters[i], mustNullAttribute) || + (argument is INamedTypeSymbol && HasMustNullDefinitionInBaseTypes(typeSymbol, i, mustNullAttribute))) + { + // Check argument is nullable + if (argument is not ITypeParameterSymbol && !argument.CanAssignNull()) + { + var diagnostic = Diagnostic.Create( + DiagnosticDescriptors.TypeParameterMustBeNullable, + argumentSyntax.GetLocation(), + argumentSyntax.ToFullString()); + context.ReportDiagnostic(diagnostic); + } + } + + // If type argument is a generic type, check itself + if (argument is INamedTypeSymbol namedTypeArgument && + namedTypeArgument.IsGenericType && + argumentSyntax is GenericNameSyntax nestedGenericName) + { + CheckGenericTypeArguments(context, nestedGenericName); + } + } + } + else if (symbolInfo is { Symbol: IMethodSymbol methodSymbol }) + { + CheckGenericMethodSymbol(context, methodSymbol, genericName); } + } + private static void CheckGenericMethodSymbol(SyntaxNodeAnalysisContext context, IMethodSymbol methodSymbol, SimpleNameSyntax nameSyntax) + { var mustNullAttribute = GetMustNullAttributeSymbol(context.Compilation); - for (var i = 0; i < typeSymbol.TypeArguments.Length; i++) + for (var i = 0; i < methodSymbol.TypeArguments.Length; i++) { - var argument = typeSymbol.TypeArguments[i]; - var argumentSyntax = genericName.TypeArgumentList.Arguments[i]; + var argument = methodSymbol.TypeArguments[i]; + SyntaxNode argumentSyntax = nameSyntax is GenericNameSyntax genericName + ? genericName.TypeArgumentList.Arguments[i] + : nameSyntax.FirstAncestorOrSelf()!.ArgumentList.Arguments[i]; // Check if current type parameter has MustNullAttribute or its base type has - if (HasAttributeSymbol(typeSymbol.TypeParameters[i], mustNullAttribute) || - (argument is INamedTypeSymbol && HasMustNullDefinitionInBaseTypes(typeSymbol, i, mustNullAttribute))) + if (HasAttributeSymbol(methodSymbol.TypeParameters[i], mustNullAttribute)) { // Check argument is nullable if (argument is not ITypeParameterSymbol && !argument.CanAssignNull()) { var diagnostic = Diagnostic.Create( - DiagnosticDescriptors.TypeParameterMustBeNullable, + argumentSyntax is TypeSyntax + ? DiagnosticDescriptors.TypeParameterMustBeNullable + : DiagnosticDescriptors.ParameterTypeMustBeNullable, argumentSyntax.GetLocation(), argumentSyntax.ToFullString()); context.ReportDiagnostic(diagnostic); diff --git a/src/Ling.Audit.SourceGenerators/AuditPropertyGenerator.Execute.cs b/src/Ling.Audit.SourceGenerators/AuditPropertyGenerator.Execute.cs index 2113fa4..19ecf0c 100644 --- a/src/Ling.Audit.SourceGenerators/AuditPropertyGenerator.Execute.cs +++ b/src/Ling.Audit.SourceGenerators/AuditPropertyGenerator.Execute.cs @@ -21,8 +21,11 @@ private static string GetGeneratedCode(TypeDeclarationSyntax typeDeclaration, Eq """); - cb.AppendLine($"namespace {namespaceName}") - .OpenBrace(); + if (!string.IsNullOrEmpty(namespaceName)) + { + cb.AppendLine($"namespace {namespaceName}") + .OpenBrace(); + } var i = 0; for (; i < containingTypes.Count - 1; i++) @@ -54,8 +57,16 @@ private static string GetGeneratedCode(TypeDeclarationSyntax typeDeclaration, Eq _ => string.Empty, }; - cb.AppendFormatLine("/// ", inheritDocClass, property.PropertyName) - .AppendFormatLine("public {0}{1} {2} {{ get; set; }}", virtualModifier, property.PropertyType, property.PropertyName); + if (property.InterfaceName.EndsWith("`1", StringComparison.Ordinal)) + { + cb.AppendLine("/// "); + } + else + { + cb.AppendFormatLine("/// ", inheritDocClass, property.PropertyName); + } + + cb.AppendFormatLine("public {0}{1} {2} {{ get; set; }}", virtualModifier, property.PropertyType, property.PropertyName); if (++index < properties.Count) { @@ -91,7 +102,7 @@ private static (string Namespace, List ContainingTypes) GetType { var types = new List(); SyntaxNode? parent = typeDeclaration; - var namespaceName = "global::System"; + var namespaceName = string.Empty; while (parent != null) { diff --git a/src/Ling.Audit.SourceGenerators/AuditPropertyGenerator.Parser.cs b/src/Ling.Audit.SourceGenerators/AuditPropertyGenerator.Parser.cs index 6b1d8cc..958f994 100644 --- a/src/Ling.Audit.SourceGenerators/AuditPropertyGenerator.Parser.cs +++ b/src/Ling.Audit.SourceGenerators/AuditPropertyGenerator.Parser.cs @@ -41,7 +41,7 @@ private static AuditGenerationContext GetGenerationContext(GeneratorSyntaxContex globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, - miscellaneousOptions: SymbolDisplayMiscellaneousOptions.ExpandNullable | SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier + miscellaneousOptions: SymbolDisplayMiscellaneousOptions.ExpandNullable ); foreach (var @interface in allInterfaces) @@ -113,9 +113,9 @@ private static string GetNormalizedTypeName(INamedTypeSymbol namedTypeSymbol) { var sb = new StringBuilder(); - if (!string.IsNullOrEmpty(namedTypeSymbol.ContainingNamespace?.ToString())) + if (namedTypeSymbol.ContainingNamespace is { IsGlobalNamespace: false } containingNamespace) { - sb.Append(namedTypeSymbol.ContainingNamespace).Append('.'); + sb.Append(containingNamespace).Append('.'); } BuildTypeFullName(namedTypeSymbol, sb); diff --git a/src/Ling.Audit.SourceGenerators/AuditPropertyGenerator.cs b/src/Ling.Audit.SourceGenerators/AuditPropertyGenerator.cs index 1293912..0d605f2 100644 --- a/src/Ling.Audit.SourceGenerators/AuditPropertyGenerator.cs +++ b/src/Ling.Audit.SourceGenerators/AuditPropertyGenerator.cs @@ -14,12 +14,8 @@ public void Initialize(IncrementalGeneratorInitializationContext context) var declarations = context.SyntaxProvider .CreateSyntaxProvider( predicate: static (s, _) => IsSyntaxTargetForGeneration(s), - transform: static (ctx, _) => ctx) - .Collect() - .SelectMany((ctxs, _) => ctxs - .GroupBy(ctx => ctx.Node.SyntaxTree) - .Select(group => GetGenerationContext(group.First())) - .Where(ctx => ctx.ShouldGenerate)); + transform: static (ctx, _) => GetGenerationContext(ctx)) + .Where(static ctx => ctx.ShouldGenerate); context.RegisterSourceOutput(declarations, Execute); } diff --git a/src/Ling.Audit.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/Ling.Audit.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 5bfe7b1..28b49cd 100644 --- a/src/Ling.Audit.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/Ling.Audit.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -16,6 +16,11 @@ internal static class DiagnosticDescriptors /// public const string TypeParameterMustBeNullableId = "LA001"; + /// + /// Diagnostic ID for : Parameter type must be nullable + /// + public const string ParameterTypeMustBeNullableId = "LA002"; + /// /// Diagnostic ID for : Audit operations are not supported on value types /// @@ -53,6 +58,19 @@ internal static class DiagnosticDescriptors isEnabledByDefault: true, description: L(nameof(SR.TypeParameterMustBeNullable_Description))); + /// + /// Diagnostic rule for parameter type must be nullable. + /// Message format: "The parameter type inferred from '{0}' must be nullable." + /// + public static readonly DiagnosticDescriptor ParameterTypeMustBeNullable = new( + ParameterTypeMustBeNullableId, + L(nameof(SR.ParameterTypeMustBeNullable_Title)), + L(nameof(SR.ParameterTypeMustBeNullable_Message)), + Category, + DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: L(nameof(SR.ParameterTypeMustBeNullable_Description))); + /// /// Diagnostic rule for audit operations not supported on value types. /// Message format: "Type '{0}' is a value type and cannot be audited." diff --git a/src/Ling.Audit.SourceGenerators/Helpers/ITypeSymbolHelpers.cs b/src/Ling.Audit.SourceGenerators/Helpers/ITypeSymbolHelpers.cs index afea42d..dfd3129 100644 --- a/src/Ling.Audit.SourceGenerators/Helpers/ITypeSymbolHelpers.cs +++ b/src/Ling.Audit.SourceGenerators/Helpers/ITypeSymbolHelpers.cs @@ -27,4 +27,4 @@ public static bool CanAssignNull(this ITypeSymbol type) { return type.IsReferenceType || type.IsNullable(); } -} \ No newline at end of file +} diff --git a/src/Ling.Audit.SourceGenerators/Ling.Audit.SourceGenerators.csproj b/src/Ling.Audit.SourceGenerators/Ling.Audit.SourceGenerators.csproj index d53d578..52cfc0a 100644 --- a/src/Ling.Audit.SourceGenerators/Ling.Audit.SourceGenerators.csproj +++ b/src/Ling.Audit.SourceGenerators/Ling.Audit.SourceGenerators.csproj @@ -42,4 +42,4 @@ - \ No newline at end of file + diff --git a/src/Ling.Audit.SourceGenerators/Properties/launchSettings.json b/src/Ling.Audit.SourceGenerators/Properties/launchSettings.json index 9bae0ca..b4dcace 100644 --- a/src/Ling.Audit.SourceGenerators/Properties/launchSettings.json +++ b/src/Ling.Audit.SourceGenerators/Properties/launchSettings.json @@ -5,4 +5,4 @@ "targetProject": "..\\..\\samples\\Sample.Console\\Sample.Console.csproj" } } -} \ No newline at end of file +} diff --git a/src/Ling.Audit.SourceGenerators/Resources/SR.Designer.cs b/src/Ling.Audit.SourceGenerators/Resources/SR.Designer.cs index 442aab1..cb1a3d0 100644 --- a/src/Ling.Audit.SourceGenerators/Resources/SR.Designer.cs +++ b/src/Ling.Audit.SourceGenerators/Resources/SR.Designer.cs @@ -141,6 +141,33 @@ internal static string AuditRequiresPartialType_Title { } } + /// + /// Looks up a localized string similar to The parameter type must be nullable. This ensures that the parameter can represent the absence of a value.. + /// + internal static string ParameterTypeMustBeNullable_Description { + get { + return ResourceManager.GetString("ParameterTypeMustBeNullable_Description", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter type inferred from '{0}' must be nullable. + /// + internal static string ParameterTypeMustBeNullable_Message { + get { + return ResourceManager.GetString("ParameterTypeMustBeNullable_Message", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Parameter type must be nullable. + /// + internal static string ParameterTypeMustBeNullable_Title { + get { + return ResourceManager.GetString("ParameterTypeMustBeNullable_Title", resourceCulture); + } + } + /// /// Looks up a localized string similar to The type parameter is marked with the MustNullable attribute, indicating that it must be a nullable type. This ensures that the type can represent the absence of a value.. /// diff --git a/src/Ling.Audit.SourceGenerators/Resources/SR.resx b/src/Ling.Audit.SourceGenerators/Resources/SR.resx index eeab874..64d497a 100644 --- a/src/Ling.Audit.SourceGenerators/Resources/SR.resx +++ b/src/Ling.Audit.SourceGenerators/Resources/SR.resx @@ -131,6 +131,19 @@ Detailed explanation of why the type parameter is marked as must be nullable and how to fix it + + Parameter type must be nullable + Title of the diagnostic for parameters that must be nullable + + + The parameter type inferred from '{0}' must be nullable + Message shown when a parameter is not nullable + + + The parameter type must be nullable. This ensures that the parameter can represent the absence of a value. + Detailed explanation of why the parameter type is marked as must be nullable and how to fix it + + Audit operations not supported on value types Title of the diagnostic for value types that cannot be audited @@ -183,4 +196,4 @@ Detailed explanation of why to use a more comprehensive interface - \ No newline at end of file + diff --git a/src/Ling.Audit/Assembly.cs b/src/Ling.Audit/Assembly.cs deleted file mode 100644 index de0172c..0000000 --- a/src/Ling.Audit/Assembly.cs +++ /dev/null @@ -1,3 +0,0 @@ -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("Ling.EntityFrameworkCore.Audit")] diff --git a/src/Ling.Audit/Ling.Audit.csproj b/src/Ling.Audit/Ling.Audit.csproj index 3d38b2d..2aef56c 100644 --- a/src/Ling.Audit/Ling.Audit.csproj +++ b/src/Ling.Audit/Ling.Audit.csproj @@ -1,7 +1,7 @@  - netstandard2.0;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0 + netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0 true .nuget true @@ -43,6 +43,12 @@ + + + <_Parameter1>Ling.Audit.EntityFrameworkCore + + + @@ -55,10 +61,10 @@ - + - \ No newline at end of file + diff --git a/src/Ling.Audit/MustNullAttribute.cs b/src/Ling.Audit/MustNullAttribute.cs index 55009f0..9cf0cb4 100644 --- a/src/Ling.Audit/MustNullAttribute.cs +++ b/src/Ling.Audit/MustNullAttribute.cs @@ -4,4 +4,4 @@ /// Marks a generic parameter as nullable. /// [AttributeUsage(AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = true)] -public sealed class MustNullAttribute : Attribute; +internal sealed class MustNullAttribute : Attribute; diff --git a/tests/Ling.Audit.AspNetCore.Tests/DefaultAuditPrincipalResolverTests.cs b/tests/Ling.Audit.AspNetCore.Tests/DefaultAuditPrincipalResolverTests.cs new file mode 100644 index 0000000..1419596 --- /dev/null +++ b/tests/Ling.Audit.AspNetCore.Tests/DefaultAuditPrincipalResolverTests.cs @@ -0,0 +1,93 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using System.Security.Claims; + +namespace Ling.Audit.AspNetCore.Tests; + +public sealed class DefaultAuditPrincipalResolverTests +{ + [Fact] + public void Resolve_ExplicitClaimTypesTakePrecedence() + { + var identityOptions = new IdentityOptions(); + identityOptions.ClaimsIdentity.UserIdClaimType = "identity-id"; + var resolver = CreateResolver(new AspNetCoreAuditOptions + { + UserIdClaimType = "audit-id", + UserNameClaimType = "audit-name", + }, identityOptions); + var context = CreateContext(new ClaimsIdentity( + [ + new Claim("audit-id", "explicit-id"), + new Claim("identity-id", "identity-id"), + new Claim("audit-name", "Explicit Name"), + ], "test")); + + var principal = resolver.Resolve(context); + + principal.UserId.Should().Be("explicit-id"); + principal.UserName.Should().Be("Explicit Name"); + } + + [Fact] + public void Resolve_UsesIdentityNameAndIdentityOptionsUserId() + { + var identityOptions = new IdentityOptions(); + identityOptions.ClaimsIdentity.UserIdClaimType = "custom-id"; + var resolver = CreateResolver(new AspNetCoreAuditOptions(), identityOptions); + var identity = new ClaimsIdentity( + [new Claim("custom-id", "42"), new Claim("custom-name", "Alice")], + "test", + "custom-name", + ClaimTypes.Role); + + var principal = resolver.Resolve(CreateContext(identity)); + + principal.UserId.Should().Be("42"); + principal.UserName.Should().Be("Alice"); + } + + [Fact] + public void Resolve_FallsBackToSubjectClaim() + { + var resolver = CreateResolver(new AspNetCoreAuditOptions(), new IdentityOptions()); + var identity = new ClaimsIdentity([new Claim("sub", "subject-id")], "jwt"); + + resolver.Resolve(CreateContext(identity)).UserId.Should().Be("subject-id"); + } + + [Fact] + public void Resolve_SelectsFirstAuthenticatedIdentity() + { + var resolver = CreateResolver(new AspNetCoreAuditOptions(), new IdentityOptions()); + var anonymous = new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "anonymous")]); + var authenticated = new ClaimsIdentity( + [new Claim(ClaimTypes.NameIdentifier, "authenticated")], "cookie"); + var context = new DefaultHttpContext + { + User = new ClaimsPrincipal([anonymous, authenticated]), + }; + + resolver.Resolve(context).UserId.Should().Be("authenticated"); + } + + [Fact] + public void Resolve_ReturnsAnonymousWhenNoAuthenticatedIdentityExists() + { + var resolver = CreateResolver(new AspNetCoreAuditOptions(), new IdentityOptions()); + var identity = new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "ignored")]); + + resolver.Resolve(CreateContext(identity)).Should().Be(new AuditPrincipal(null, null)); + } + + private static DefaultAuditPrincipalResolver CreateResolver( + AspNetCoreAuditOptions options, + IdentityOptions identityOptions) => + new(Options.Create(options), Options.Create(identityOptions)); + + private static DefaultHttpContext CreateContext(ClaimsIdentity identity) => new() + { + User = new ClaimsPrincipal(identity), + }; +} diff --git a/tests/Ling.Audit.AspNetCore.Tests/Ling.Audit.AspNetCore.Tests.csproj b/tests/Ling.Audit.AspNetCore.Tests/Ling.Audit.AspNetCore.Tests.csproj new file mode 100644 index 0000000..c55088a --- /dev/null +++ b/tests/Ling.Audit.AspNetCore.Tests/Ling.Audit.AspNetCore.Tests.csproj @@ -0,0 +1,31 @@ + + + + net6.0;net7.0;net8.0;net9.0 + enable + enable + false + latest + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/AttributeTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/AttributeTests.cs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/AttributeTests.cs @@ -0,0 +1 @@ + diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditAttributesTest.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditAttributesTest.cs new file mode 100644 index 0000000..abb2e89 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditAttributesTest.cs @@ -0,0 +1,117 @@ +using Ling.Audit.EntityFrameworkCore.Tests.Core; +using Microsoft.EntityFrameworkCore; + +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class AuditAttributesTest +{ + [Fact] + public void AuditIgnoreAttribute_Should_BeDecoratedCorrectly() + { + // Assert + typeof(NotAuditedAttribute).Should().BeDecoratedWith( + attr => attr.AllowMultiple == false && + attr.Inherited == true && + attr.ValidOn == AttributeTargets.Property); + } + + [Fact] + public void AuditIncludeAttribute_Should_BeDecoratedCorrectly() + { + // Assert + typeof(AuditableAttribute).Should().BeDecoratedWith( + attr => attr.AllowMultiple == false && + attr.Inherited == true); + } + + [Fact] + public void AuditIncludeAttribute_Should_StoreOperationType() + { + // Arrange & Act + var attribute = new AuditableAttribute(DataOperation.Create | DataOperation.Modify); + + // Assert + attribute.AnonymousOperations.Should().Be(DataOperation.Create | DataOperation.Modify); + attribute.AnonymousOperations.Should().HaveFlag(DataOperation.Create); + attribute.AnonymousOperations.Should().HaveFlag(DataOperation.Modify); + attribute.AnonymousOperations.Should().NotHaveFlag(DataOperation.Delete); + } + + [Fact] + public async Task AuditIgnoreAttribute_Should_ExcludeProperty_FromAuditLogs() + { + // Arrange + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: $"IgnoreTest_{Guid.NewGuid()}") + .UseAudit() + .Options; + + // Act + using var context = new TestIgnoreDbContext(options); + context.Database.EnsureCreated(); + var entity = new TestEntityWithIgnore + { + Id = 1, + Name = "Test", + IgnoredProperty = "Should be ignored" + }; + context.TestEntities.Add(entity); + await context.SaveChangesAsync(); + + // Assert + var auditLog = await context.AuditLogs + .Include(a => a.Details) + .FirstOrDefaultAsync(); + + auditLog.Should().NotBeNull(); + auditLog!.Details.Should().NotContain(d => d.FieldName.Contains("IgnoredProperty")); + auditLog.Details.Should().Contain(d => d.FieldName.Contains("Name")); + } + + private class TestEntityWithIgnore + { + public int Id { get; set; } + public string Name { get; set; } = null!; + + [NotAudited] + public string IgnoredProperty { get; set; } = null!; + } + + private class TestIgnoreDbContext : DbContext + { + public DbSet TestEntities { get; set; } = null!; + public DbSet> AuditLogs { get; set; } = null!; + + public TestIgnoreDbContext(DbContextOptions options) + : base(options) + { + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity(b => + { + b.HasKey(e => e.Id); + b.ToTable("TestEntities"); + b.IsAuditable(DataOperation.All); + }); + + modelBuilder.Entity>(b => + { + b.HasKey(e => e.Id); + b.HasMany(e => e.Details) + .WithOne() + .HasForeignKey(e => e.EntityLogId); + b.ToTable("AuditLogs"); + }); + + modelBuilder.Entity(b => + { + b.HasKey(e => e.Id); + b.ToTable("AuditLogDetails"); + }); + } + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditChangeLogTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditChangeLogTests.cs new file mode 100644 index 0000000..a19ed05 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditChangeLogTests.cs @@ -0,0 +1,105 @@ +using Ling.Audit.EntityFrameworkCore.Tests.Core; +using Ling.Audit.EntityFrameworkCore.Tests.Core.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; + +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class AuditChangeLogTests : IDisposable +{ + private readonly IServiceProvider _serviceProvider; + private readonly DbContextOptions _options; + + public AuditChangeLogTests() + { + _options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: $"AuditLogTest_{Guid.NewGuid()}") + .UseAudit() + .Options; + + var services = new ServiceCollection(); + services.AddScoped(sp => new TestDbContext(_options)); + services.AddScoped>(sp => + new TestAuditContextProvider(sp.GetRequiredService(), 1, "TestUser")); + + _serviceProvider = services.BuildServiceProvider(); + + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Database.EnsureCreated(); + } + + [Fact] + public async Task AuditEntityChangeLog_Should_Record_User_Information() + { + // Arrange + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + // Act + var user = new TestUser { Id = 1, Name = "TestUser" }; + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + + // Assert + var auditLog = await dbContext.AuditLogs.FirstOrDefaultAsync(); + auditLog.Should().NotBeNull(); + auditLog!.UserId.Should().Be(1); + auditLog.UserName.Should().Be("TestUser"); + auditLog.IPAddress.Should().Be("127.0.0.1"); + auditLog.ClientName.Should().Be("TestClient"); + } + + [Fact] + public async Task AuditEntityChangeLog_Should_Record_Entity_Information() + { + // Arrange + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + // Act + var item = new TestItem { Name = "Test Item", Price = 9.99m, Stock = 10 }; + dbContext.Items.Add(item); + await dbContext.SaveChangesAsync(); + + // Assert + var auditLog = await dbContext.AuditLogs.FirstOrDefaultAsync(); + auditLog.Should().NotBeNull(); + auditLog!.EntityTypeName.Should().Be(nameof(TestItem)); + auditLog.EntityKey.Should().NotBeEmpty(); + auditLog.TableName.Should().Be("Items"); + auditLog.EventType.Should().Be(AuditEventType.Create); + } + + [Fact] + public async Task AuditEntityChangeLog_Should_Have_Details() + { + // Arrange + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + // Act + var item = new TestItem { Name = "Test Item", Price = 9.99m, Stock = 10 }; + dbContext.Items.Add(item); + await dbContext.SaveChangesAsync(); + + // Assert + var auditLog = await dbContext.AuditLogs + .Include(a => a.Details) + .FirstOrDefaultAsync(); + + auditLog.Should().NotBeNull(); + auditLog!.Details.Should().NotBeEmpty(); + auditLog.Details.Should().Contain(d => d.FieldName.Contains("Name") && d.NewValue == "Test Item"); + auditLog.Details.Should().Contain(d => d.FieldName.Contains("Price") && d.NewValue == "9.99"); + auditLog.Details.Should().Contain(d => d.FieldName.Contains("Stock") && d.NewValue == "10"); + } + + public void Dispose() + { + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Database.EnsureDeleted(); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditEntityChangeLogTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditEntityChangeLogTests.cs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditEntityChangeLogTests.cs @@ -0,0 +1 @@ + diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditOptionsTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditOptionsTests.cs new file mode 100644 index 0000000..a700465 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditOptionsTests.cs @@ -0,0 +1,160 @@ +using Ling.Audit.EntityFrameworkCore.Tests.Core; +using Ling.Audit.EntityFrameworkCore.Tests.Core.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; + +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class AuditOptionsTests : IDisposable +{ + private readonly string _dbName; + + public AuditOptionsTests() + { + _dbName = $"AuditOptionsTest_{Guid.NewGuid()}"; + } + + [Fact] + public async Task AllowAnonymousCreate_True_Should_Allow_Anonymous_Creation() + { + // Arrange + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: _dbName) + .UseAudit(options => + { + options.AllowAnonymousCreate = true; + }) + .Options; + + var services = new ServiceCollection(); + services.AddScoped(sp => new TestDbContext(options)); + services.AddScoped>(sp => + new TestAuditContextProvider(sp.GetRequiredService())); + + var serviceProvider = services.BuildServiceProvider(); + using var scope = serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + // Act + var user = new TestUser + { + Id = 1, + Name = "AnonymousUser" + }; + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + + // Assert + var auditLog = await dbContext.AuditLogs.FirstOrDefaultAsync(); + auditLog.Should().NotBeNull(); + auditLog!.UserId.Should().BeNull(); + auditLog.UserName.Should().BeNull(); + } + + [Fact] + public async Task AllowAnonymousModify_False_Should_Throw_Exception() + { + // Arrange + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: _dbName) + .UseAudit(options => + { + options.AllowAnonymousCreate = true; + options.AllowAnonymousModify = false; + }) + .Options; + + var services = new ServiceCollection(); + services.AddScoped(sp => new TestDbContext(options)); + + // 先用有用户ID的上下文添加实体 + services.AddScoped>(sp => + new TestAuditContextProvider(sp.GetRequiredService(), 1, "TestUser")); + + var serviceProvider = services.BuildServiceProvider(); + using (var scope = serviceProvider.CreateScope()) + { + var dbContext = scope.ServiceProvider.GetRequiredService(); + var user = new TestUser + { + Id = 1, + Name = "OriginalName" + }; + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + } + + // 再用匿名上下文修改实体 + var anonymousServices = new ServiceCollection(); + anonymousServices.AddScoped(sp => new TestDbContext(options)); + anonymousServices.AddScoped>(sp => + new TestAuditContextProvider(sp.GetRequiredService())); + + var anonymousProvider = anonymousServices.BuildServiceProvider(); + using var anonymousScope = anonymousProvider.CreateScope(); + var anonymousContext = anonymousScope.ServiceProvider.GetRequiredService(); + + // Act & Assert + var user1 = await anonymousContext.Users.FirstAsync(); + user1.Name = "UpdatedName"; + + await Assert.ThrowsAsync(() => anonymousContext.SaveChangesAsync()); + } + + [Fact] + public async Task AuditNoFieldChangeEntity_True_Should_Audit_Unchanged_Entities() + { + // Arrange + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: _dbName) + .UseAudit(options => + { + options.AuditNoFieldChangeEntity = true; + }) + .Options; + + var services = new ServiceCollection(); + services.AddScoped(sp => new TestDbContext(options)); + services.AddScoped>(sp => + new TestAuditContextProvider(sp.GetRequiredService(), 1, "TestUser")); + + var serviceProvider = services.BuildServiceProvider(); + using var scope = serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + // 添加实体 + var user = new TestUser { Id = 1, Name = "TestUser" }; + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + + // 清除跟踪 + dbContext.ChangeTracker.Clear(); + + // Act - 不修改任何字段,但标记为修改状态 + var userToModify = await dbContext.Users.FindAsync(user.Id); + dbContext.Entry(userToModify!).State = EntityState.Modified; + await dbContext.SaveChangesAsync(); + + // Assert + var auditLogs = await dbContext.AuditLogs + .Include(a => a.Details) + .OrderByDescending(a => a.EventTime) + .ToListAsync(); + + auditLogs.Should().HaveCount(2); + var modifyLog = auditLogs.First(); + modifyLog.EventType.Should().Be(AuditEventType.Modify); + modifyLog.Details.Should().BeEmpty(); + } + + public void Dispose() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: _dbName) + .Options; + + using var context = new TestDbContext(options); + context.Database.EnsureDeleted(); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditTests.cs new file mode 100644 index 0000000..a37033b --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditTests.cs @@ -0,0 +1,184 @@ +using Ling.Audit.EntityFrameworkCore.Tests.Core; +using Ling.Audit.EntityFrameworkCore.Tests.Core.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; + +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class AuditTests : IDisposable +{ + private readonly IServiceProvider _serviceProvider; + private readonly DbContextOptions _options; + + public AuditTests() + { + _options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: $"AuditTest_{Guid.NewGuid()}") + .UseAudit(options => + { + options.AllowAnonymousCreate = false; + options.AllowAnonymousModify = false; + options.AllowAnonymousDelete = false; + }) + .Options; + + var services = new ServiceCollection(); + services.AddScoped(sp => new TestDbContext(_options)); + services.AddScoped>(sp => + new TestAuditContextProvider(sp.GetRequiredService(), 1, "TestUser")); + + _serviceProvider = services.BuildServiceProvider(); + + // 初始化数据库 + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Database.EnsureCreated(); + } + + [Fact] + public async Task Create_Entity_Should_Generate_AuditLog() + { + // Arrange + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + // Act + var user = new TestUser + { + Id = 1, + Name = "TestUser", + Age = 25 + }; + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + + // Assert + var auditLog = await dbContext.AuditLogs + .Include(a => a.Details) + .FirstOrDefaultAsync(); + + auditLog.Should().NotBeNull(); + auditLog!.EventType.Should().Be(AuditEventType.Create); + auditLog.UserId.Should().Be(1); + auditLog.UserName.Should().Be("TestUser"); + auditLog.EntityTypeName.Should().Be(nameof(TestUser)); + auditLog.Details.Should().NotBeEmpty(); + auditLog.Details.Should().Contain(d => d.FieldName.Contains("Name") && d.NewValue == "TestUser"); + auditLog.Details.Should().Contain(d => d.FieldName.Contains("Age") && d.NewValue == "25"); + } + + [Fact] + public async Task Update_Entity_Should_Generate_AuditLog() + { + // Arrange + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + var user = new TestUser + { + Id = 1, + Name = "OriginalName", + Age = 30 + }; + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + + // 清除更改跟踪 + dbContext.ChangeTracker.Clear(); + + // Act + var userToUpdate = await dbContext.Users.FindAsync(user.Id); + userToUpdate!.Name = "UpdatedName"; + userToUpdate.Age = 35; + await dbContext.SaveChangesAsync(); + + // Assert + var auditLogs = await dbContext.AuditLogs + .Include(a => a.Details) + .OrderByDescending(a => a.EventTime) + .ToListAsync(); + + auditLogs.Should().HaveCount(2); + var updateLog = auditLogs.First(); + updateLog.EventType.Should().Be(AuditEventType.Modify); + updateLog.UserId.Should().Be(1); + updateLog.Details.Should().Contain(d => d.FieldName.Contains("Name") && d.OriginalValue == "OriginalName" && d.NewValue == "UpdatedName"); + updateLog.Details.Should().Contain(d => d.FieldName.Contains("Age") && d.OriginalValue == "30" && d.NewValue == "35"); + } + + [Fact] + public async Task Delete_Entity_Should_Generate_AuditLog() + { + // Arrange + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + var user = new TestUser + { + Id = 1, + Name = "UserToDelete", + Age = 40 + }; + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + + // 清除更改跟踪 + dbContext.ChangeTracker.Clear(); + + // Act + var userToDelete = await dbContext.Users.FindAsync(user.Id); + dbContext.Users.Remove(userToDelete!); + await dbContext.SaveChangesAsync(); + + // Assert + var auditLogs = await dbContext.AuditLogs + .Include(a => a.Details) + .OrderByDescending(a => a.EventTime) + .ToListAsync(); + + auditLogs.Should().HaveCount(2); + var deleteLog = auditLogs.First(); + deleteLog.EventType.Should().Be(AuditEventType.SoftDelete); + deleteLog.UserId.Should().Be(1); + } + + [Fact] + public async Task Anonymous_Creation_Should_Throw_Exception() + { + // Arrange + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: $"AuditTest_{Guid.NewGuid()}") + .UseAudit(options => + { + options.AllowAnonymousCreate = false; + }) + .Options; + + var services = new ServiceCollection(); + services.AddScoped(sp => new TestDbContext(options)); + services.AddScoped>(sp => + new TestAuditContextProvider(sp.GetRequiredService())); + + var serviceProvider = services.BuildServiceProvider(); + using var scope = serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + // Act & Assert + var user = new TestUser + { + Id = 1, + Name = "AnonymousUser" + }; + dbContext.Users.Add(user); + + await Assert.ThrowsAsync(() => dbContext.SaveChangesAsync()); + } + + public void Dispose() + { + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Database.EnsureDeleted(); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/Base/TestAuditContextProvider.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/Base/TestAuditContextProvider.cs new file mode 100644 index 0000000..e2df87d --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/Base/TestAuditContextProvider.cs @@ -0,0 +1,25 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; + +namespace Ling.Audit.EntityFrameworkCore.Tests.Core; + +public class TestAuditContextProvider : AuditContextProviderBase +{ + private readonly int? _userId; + private readonly string? _userName; + + public TestAuditContextProvider(ICurrentDbContext current, int? userId = null, string? userName = null) + : base(current) + { + _userId = userId; + _userName = userName; + } + + protected override AuditContext? GetAuditContext() + { + return new AuditContext( + _userId, + _userName, + "127.0.0.1", + "TestClient"); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/Base/TestBase.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/Base/TestBase.cs new file mode 100644 index 0000000..383a071 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/Base/TestBase.cs @@ -0,0 +1,80 @@ +using Ling.Audit.EntityFrameworkCore.Tests.Core; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System.Text.Json; + +namespace Ling.Audit.EntityFrameworkCore.Tests.Base; + +public abstract class TestBase : IDisposable +{ + private bool _disposedValue; + private readonly IServiceScope _scope = default!; + private readonly DbContextOptions _dbContextOptions = default!; + + protected TestBase() + { + var services = new ServiceCollection(); + + var auditOptions = new AuditOptions(); + ConfigureAuditOptions(auditOptions); + using var auditOptionsStream = new MemoryStream(JsonSerializer.SerializeToUtf8Bytes(auditOptions)); + + var configuration = new ConfigurationBuilder() + .AddJsonStream(auditOptionsStream) + .Build(); + services.AddSingleton(configuration); + + var builder = new DbContextOptionsBuilder() + .UseInMemoryDatabase("TestDB"); + + ConfigureDbContext(builder); + + _dbContextOptions = builder.Options; + + services.AddScoped(_ => new TestDbContext(_dbContextOptions)); + + ConfigureServices(services); + + var serviceProvider = services.BuildServiceProvider(); + _scope = serviceProvider.CreateAsyncScope(); + } + + protected TService GetService() where TService : notnull + { + return _scope.ServiceProvider.GetRequiredService(); + } + + protected virtual void ConfigureAuditOptions(AuditOptions options) + { + } + + protected virtual void ConfigureDbContext(DbContextOptionsBuilder builder) + { + builder.UseAudit(); + } + + protected virtual void ConfigureServices(IServiceCollection services) + { + services.AddScoped(_ => new TestDbContext(_dbContextOptions)); + } + + protected virtual void Dispose(bool disposing) + { + if (!_disposedValue) + { + if (disposing) + { + _scope?.Dispose(); + } + + _disposedValue = true; + } + } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/Base/TestDbContext.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/Base/TestDbContext.cs new file mode 100644 index 0000000..0cb9320 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/Base/TestDbContext.cs @@ -0,0 +1,66 @@ +using Microsoft.EntityFrameworkCore; + +namespace Ling.Audit.EntityFrameworkCore.Tests.Base; + +public class TestDbContext(DbContextOptions options) + : DbContext(options) +{ + public DbSet Users { get; set; } + public DbSet Products { get; set; } + public DbSet Orders { get; set; } + public DbSet Categories { get; set; } = null!; + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity(builder => + { + builder.IsAuditable(DataOperation.Create); + builder.HasData(new User() + { + Id = Guid.NewGuid(), + Name = "John Doe", + Email = "john@example.com", + Age = 20, + }); + }); + + modelBuilder.Entity(builder => + { + builder.IsAuditable(DataOperation.Create | DataOperation.Modify); + builder.Property(x => x.Stock).IsNotAudited(false); + }); + } +} + +public partial class User : ICreationAudited +{ + public Guid Id { get; set; } + public string Name { get; set; } = default!; + public string Email { get; set; } = default!; + public int Age { get; set; } +} + +[Auditable] +public partial class Product : ICreationAudited, IModificationAudited +{ + public Guid Id { get; set; } + public string Name { get; set; } = default!; + public string Description { get; set; } = default!; + public decimal Price { get; set; } + public int Stock { get; set; } +} + +[Auditable(DataOperation.All)] +public partial class Order : IFullAudited +{ + public int Id { get; set; } + public string OrderNumber { get; set; } = null!; + public decimal TotalAmount { get; set; } +} + +public class Category +{ + public int Id { get; set; } + public string Name { get; set; } = default!; + public string Description { get; set; } = default!; +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/CustomPropertySerializerTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/CustomPropertySerializerTests.cs new file mode 100644 index 0000000..fb7df7e --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/CustomPropertySerializerTests.cs @@ -0,0 +1,103 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using System.Text.Json; + +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class CustomPropertySerializerTests +{ + [Fact] + public void UseSerializer_Should_ReplaceDefaultSerializer() + { + // Arrange + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: $"CustomSerializerTest_{Guid.NewGuid()}") + .UseSerializer() + .Options; + + // Act + using var context = new TestContext(options); + var serializer = context.GetService(); + + // Assert + serializer.Should().NotBeNull(); + serializer.Should().BeOfType(); + } + + [Fact] + public void CustomSerializer_Should_SerializeAsExpected() + { + // Arrange + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: $"CustomSerializerTest_{Guid.NewGuid()}") + .UseSerializer() + .Options; + + // Act + using var context = new TestContext(options); + var serializer = context.GetService(); + var testObj = new TestClass { Id = 1, Name = "Test" }; + var serialized = serializer.Serialize(testObj, typeof(TestClass)); + + // Assert + serialized.Should().NotBeNull(); + serialized.Should().Contain("id"); // 驼峰命名 + serialized.Should().Contain("name"); // 驼峰命名 + } + + [Fact] + public void CustomSerializer_Should_DeserializeAsExpected() + { + // Arrange + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: $"CustomSerializerTest_{Guid.NewGuid()}") + .UseSerializer() + .Options; + + // Act + using var context = new TestContext(options); + var serializer = context.GetService(); + var json = "{\"id\":1,\"name\":\"Test\"}"; + var deserialized = serializer.Deserialize(json, typeof(TestClass)) as TestClass; + + // Assert + deserialized.Should().NotBeNull(); + deserialized!.Id.Should().Be(1); + deserialized.Name.Should().Be("Test"); + } + + private class TestContext : DbContext + { + public TestContext(DbContextOptions options) : base(options) + { + } + } + + private class TestClass + { + public int Id { get; set; } + public string? Name { get; set; } + } + + private class CustomSerializer : IPropertySerializer + { + private readonly JsonSerializerOptions _options = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + WriteIndented = true + }; + + public string? Serialize(object? value, Type valueType) + { + if (value == null) return null; + return JsonSerializer.Serialize(value, valueType, _options); + } + + public object? Deserialize(string? value, Type valueType) + { + if (string.IsNullOrEmpty(value)) return null; + return JsonSerializer.Deserialize(value, valueType, _options); + } + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/DisableAuditSwitchTest.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/DisableAuditSwitchTest.cs new file mode 100644 index 0000000..73dfa7e --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/DisableAuditSwitchTest.cs @@ -0,0 +1,81 @@ +using Ling.Audit.EntityFrameworkCore.Tests.Core; +using Ling.Audit.EntityFrameworkCore.Tests.Core.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; + +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class DisableAuditSwitchTest : IDisposable +{ + private readonly IServiceProvider _serviceProvider; + private readonly DbContextOptions _options; + + public DisableAuditSwitchTest() + { + _options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: $"DisableAuditTest_{Guid.NewGuid()}") + .UseAudit() + .Options; + + var services = new ServiceCollection(); + services.AddScoped(sp => new TestDbContext(_options)); + services.AddScoped>(sp => + new TestAuditContextProvider(sp.GetRequiredService(), 1, "TestUser")); + + _serviceProvider = services.BuildServiceProvider(); + + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Database.EnsureCreated(); + } + + [Fact] + public async Task When_DisableAuditingSwitch_Set_ShouldNot_GenerateAuditLogs() + { + // Arrange + AppContext.SetSwitch(AuditDefaults.DisableAuditingSwitch, true); + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + // Act + var user = new TestUser { Id = 1, Name = "TestUser" }; + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + + // Assert + var auditLogs = await dbContext.AuditLogs.ToListAsync(); + auditLogs.Should().BeEmpty(); + + // Clean up + AppContext.SetSwitch(AuditDefaults.DisableAuditingSwitch, false); + } + + [Fact] + public async Task When_DisableAuditingSwitch_NotSet_Should_GenerateAuditLogs() + { + // Arrange + AppContext.SetSwitch(AuditDefaults.DisableAuditingSwitch, false); + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + // Act + var user = new TestUser { Id = 1, Name = "TestUser" }; + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + + // Assert + var auditLogs = await dbContext.AuditLogs.ToListAsync(); + auditLogs.Should().NotBeEmpty(); + } + + public void Dispose() + { + // 恢复开关状态 + AppContext.SetSwitch(AuditDefaults.DisableAuditingSwitch, false); + + using var scope = _serviceProvider.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Database.EnsureDeleted(); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/DisableAuditSwitchTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/DisableAuditSwitchTests.cs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/DisableAuditSwitchTests.cs @@ -0,0 +1 @@ + diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/EntityOperationTypeTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/EntityOperationTypeTests.cs new file mode 100644 index 0000000..5f540a6 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/EntityOperationTypeTests.cs @@ -0,0 +1,64 @@ +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class EntityOperationTypeTests +{ + [Fact] + public void EntityOperationType_Should_BeFlags_Enum() + { + // Assert + typeof(DataOperation).Should().BeDecoratedWith(); + } + + [Fact] + public void EntityOperationType_All_Should_Include_All_Operations() + { + // Arrange + var create = DataOperation.Create; + var update = DataOperation.Modify; + var delete = DataOperation.Delete; + var all = DataOperation.All; + + // Assert + all.Should().HaveFlag(create); + all.Should().HaveFlag(update); + all.Should().HaveFlag(delete); + all.Should().Be(create | update | delete); + } + + [Fact] + public void EntityOperationType_Should_Support_FlagOperations() + { + // Arrange + var createAndUpdate = DataOperation.Create | DataOperation.Modify; + + // Assert + createAndUpdate.Should().HaveFlag(DataOperation.Create); + createAndUpdate.Should().HaveFlag(DataOperation.Modify); + createAndUpdate.Should().NotHaveFlag(DataOperation.Delete); + + // Test removing flag + var onlyCreate = createAndUpdate & ~DataOperation.Modify; + onlyCreate.Should().Be(DataOperation.Create); + onlyCreate.Should().NotHaveFlag(DataOperation.Modify); + } + + [Theory] + [InlineData(DataOperation.Create, true, false, false)] + [InlineData(DataOperation.Modify, false, true, false)] + [InlineData(DataOperation.Delete, false, false, true)] + [InlineData(DataOperation.Create | DataOperation.Modify, true, true, false)] + [InlineData(DataOperation.Create | DataOperation.Delete, true, false, true)] + [InlineData(DataOperation.Modify | DataOperation.Delete, false, true, true)] + [InlineData(DataOperation.All, true, true, true)] + public void EntityOperationType_HasFlag_Should_Work_Correctly( + DataOperation value, + bool hasCreate, + bool hasUpdate, + bool hasDelete) + { + // Assert + value.HasFlag(DataOperation.Create).Should().Be(hasCreate); + value.HasFlag(DataOperation.Modify).Should().Be(hasUpdate); + value.HasFlag(DataOperation.Delete).Should().Be(hasDelete); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/Extensions/AuditDbContextExtensionsTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/Extensions/AuditDbContextExtensionsTests.cs new file mode 100644 index 0000000..38faf8e --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/Extensions/AuditDbContextExtensionsTests.cs @@ -0,0 +1,41 @@ +using Microsoft.EntityFrameworkCore; + +namespace Ling.Audit.EntityFrameworkCore.Tests.Extensions +{ + public class AuditDbContextExtensionsTests + { + [Fact] + public void AddAudit_AddsInterceptor() + { + // Arrange + var builder = new DbContextOptionsBuilder(); + + // Act + builder.AddAudit(); + + // Assert + var options = builder.Options; + var interceptors = options.FindExtension()?.Interceptors; + Assert.Contains(interceptors, i => i is AuditSaveChangesInterceptor); + } + + [Fact] + public void UseAudit_ConfiguresAuditOptions() + { + // Arrange + var builder = new DbContextOptionsBuilder(); + + // Act + builder.UseAudit(options => + { + options.CurrentUserProvider = () => "test-user"; + options.CurrentTimeProvider = () => DateTimeOffset.Parse("2023-01-01"); + }); + + // Assert + var auditOptions = builder.Options.GetExtension(); + Assert.Equal("test-user", auditOptions.CurrentUserProvider()); + Assert.Equal(DateTimeOffset.Parse("2023-01-01"), auditOptions.CurrentTimeProvider()); + } + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/Interceptors/AuditSaveChangesInterceptorTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/Interceptors/AuditSaveChangesInterceptorTests.cs new file mode 100644 index 0000000..068a559 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/Interceptors/AuditSaveChangesInterceptorTests.cs @@ -0,0 +1,91 @@ +using Microsoft.EntityFrameworkCore; + +namespace Ling.Audit.EntityFrameworkCore.Tests.Interceptors +{ + public class AuditSaveChangesInterceptorTests + { + [Fact] + public void DisableAuditingSwitch_WhenTrue_SkipsAuditing() + { + // Arrange + AppContext.SetSwitch(AuditDefaults.DisableAuditingSwitch, true); + var interceptor = new AuditSaveChangesInterceptor(); + var context = CreateDbContextWithEntities(); + + // Act + interceptor.SaveChangesBefore(context); + + // Assert ��֤û�н����κ�����ֶε��޸� + var entry = context.ChangeTracker.Entries().First(); + Assert.Null(entry.Property("CreatedAt").CurrentValue); + Assert.Null(entry.Property("CreatedBy").CurrentValue); + + // Cleanup + AppContext.SetSwitch(AuditDefaults.DisableAuditingSwitch, false); + } + + [Fact] + public void SaveChangesBefore_ForNewEntity_SetsCreationAuditFields() + { + // Arrange + var interceptor = new AuditSaveChangesInterceptor(); + var context = CreateDbContextWithEntities(); + var entity = new TestAuditEntity(); + context.Add(entity); + + // Act + interceptor.SaveChangesBefore(context); + + // Assert + var entry = context.ChangeTracker.Entries().First(); + Assert.NotNull(entry.Property("CreatedAt").CurrentValue); + Assert.Equal("system", entry.Property("CreatedBy").CurrentValue); + } + + [Fact] + public void SaveChangesBefore_ForModifiedEntity_SetsModificationAuditFields() + { + // Arrange + var interceptor = new AuditSaveChangesInterceptor(); + var context = CreateDbContextWithEntities(); + var entity = new TestAuditEntity { Id = 1 }; + context.Attach(entity); + context.Entry(entity).State = EntityState.Modified; + + // Act + interceptor.SaveChangesBefore(context); + + // Assert + var entry = context.ChangeTracker.Entries().First(); + Assert.NotNull(entry.Property("LastModifiedAt").CurrentValue); + Assert.Equal("system", entry.Property("LastModifiedBy").CurrentValue); + } + + [Fact] + public void SaveChangesBefore_ForSoftDeletedEntity_SetsDeletionAuditFields() + { + // Arrange + var interceptor = new AuditSaveChangesInterceptor(); + var context = CreateDbContextWithEntities(); + var entity = new TestAuditEntity { Id = 1 }; + context.Attach(entity); + entity.IsDeleted = true; + + // Act + interceptor.SaveChangesBefore(context); + + // Assert + var entry = context.ChangeTracker.Entries().First(); + Assert.NotNull(entry.Property("DeletedAt").CurrentValue); + Assert.Equal("system", entry.Property("DeletedBy").CurrentValue); + } + + private DbContext CreateDbContextWithEntities() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + return new TestDbContext(options); + } + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/Ling.Audit.EntityFrameworkCore.Tests.csproj b/tests/Ling.Audit.EntityFrameworkCore.Tests/Ling.Audit.EntityFrameworkCore.Tests.csproj new file mode 100644 index 0000000..0b8ec76 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/Ling.Audit.EntityFrameworkCore.Tests.csproj @@ -0,0 +1,41 @@ + + + + net8.0 + enable + enable + false + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/PropertySerializerTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/PropertySerializerTests.cs new file mode 100644 index 0000000..9857215 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/PropertySerializerTests.cs @@ -0,0 +1,187 @@ +using System.Text.Json; + +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class PropertySerializerTests +{ + private readonly IPropertySerializer _serializer; + + public PropertySerializerTests() + { + _serializer = new DefaultPropertySerializer(null); + } + + [Fact] + public void Serialize_PrimitiveTypes_Should_Return_StringRepresentation() + { + // Arrange & Act & Assert + _serializer.Serialize(42, typeof(int)).Should().Be("42"); + _serializer.Serialize(true, typeof(bool)).Should().Be("True"); + _serializer.Serialize(3.14, typeof(double)).Should().Be("3.14"); + } + + [Fact] + public void Serialize_Null_Should_Return_Null() + { + // Arrange & Act + var result = _serializer.Serialize(null, typeof(string)); + + // Assert + result.Should().BeNull(); + } + + [Fact] + public void Serialize_String_Should_Return_SameString() + { + // Arrange + var value = "Test String"; + + // Act + var result = _serializer.Serialize(value, typeof(string)); + + // Assert + result.Should().Be(value); + } + + [Fact] + public void Serialize_DateTime_Should_Return_StringRepresentation() + { + // Arrange + var date = new DateTime(2023, 1, 1); + + // Act + var result = _serializer.Serialize(date, typeof(DateTime)); + + // Assert + result.Should().Be(date.ToString()); + } + + [Fact] + public void Serialize_Guid_Should_Return_StringRepresentation() + { + // Arrange + var guid = Guid.Parse("A52E6E92-8F6C-45EB-8B96-F6DDACC0C8F7"); + + // Act + var result = _serializer.Serialize(guid, typeof(Guid)); + + // Assert + result.Should().Be(guid.ToString()); + } + + [Fact] + public void Serialize_Enum_Should_Return_StringRepresentation() + { + // Arrange + var value = TestEnum.Value2; + + // Act + var result = _serializer.Serialize(value, typeof(TestEnum)); + + // Assert + result.Should().Be("Value2"); + } + + [Fact] + public void Serialize_ComplexType_Should_ReturnJsonString() + { + // Arrange + var complexObject = new TestComplexObject + { + Id = 1, + Name = "Test" + }; + + // Act + var result = _serializer.Serialize(complexObject, typeof(TestComplexObject)); + + // Assert + result.Should().NotBeNull(); + result.Should().Contain("\"Id\":1"); + result.Should().Contain("\"Name\":\"Test\""); + } + + [Fact] + public void Deserialize_PrimitiveTypes_Should_ReturnCorrectValue() + { + // Arrange & Act & Assert + _serializer.Deserialize("42", typeof(int)).Should().Be(42); + _serializer.Deserialize("True", typeof(bool)).Should().Be(true); + _serializer.Deserialize("3.14", typeof(double)).Should().Be(3.14); + } + + [Fact] + public void Deserialize_Null_Should_ReturnDefaultValue() + { + // Arrange & Act & Assert + _serializer.Deserialize(null, typeof(int)).Should().Be(0); + _serializer.Deserialize(null, typeof(string)).Should().Be(string.Empty); + _serializer.Deserialize(null, typeof(int?)).Should().BeNull(); + } + + [Fact] + public void Deserialize_ComplexType_Should_ReturnCorrectObject() + { + // Arrange + var json = "{\"Id\":1,\"Name\":\"Test\"}"; + + // Act + var result = _serializer.Deserialize(json, typeof(TestComplexObject)) as TestComplexObject; + + // Assert + result.Should().NotBeNull(); + result!.Id.Should().Be(1); + result.Name.Should().Be("Test"); + } + + [Fact] + public void CustomSerializer_Should_BeUsable() + { + // Arrange + var serializer = new CustomPropertySerializer(); + var value = new TestComplexObject { Id = 1, Name = "Test" }; + + // Act + var serialized = serializer.Serialize(value, typeof(TestComplexObject)); + var deserialized = serializer.Deserialize(serialized, typeof(TestComplexObject)) as TestComplexObject; + + // Assert + deserialized.Should().NotBeNull(); + deserialized!.Id.Should().Be(1); + deserialized.Name.Should().Be("Test"); + } + + private class TestComplexObject + { + public int Id { get; set; } + public string? Name { get; set; } + } + + private enum TestEnum + { + Value1, + Value2, + Value3 + } + + private class CustomPropertySerializer : IPropertySerializer + { + private readonly JsonSerializerOptions _options = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + WriteIndented = true + }; + + public string? Serialize(object? value, Type valueType) + { + if (value == null) return null; + return JsonSerializer.Serialize(value, valueType, _options); + } + + public object? Deserialize(string? value, Type valueType) + { + if (string.IsNullOrEmpty(value)) return null; + return JsonSerializer.Deserialize(value, valueType, _options); + } + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditEntityChangeLogTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditEntityChangeLogTests.cs new file mode 100644 index 0000000..174126e --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditEntityChangeLogTests.cs @@ -0,0 +1,60 @@ +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class AuditEntityChangeLogTests +{ + [Fact] + public void AuditEntityChangeLog_ShouldInitializeWithDefaultValues() + { + // Act + var log = new AuditEntityChangeLog(); + + // Assert + log.Details.Should().NotBeNull(); + log.Details.Should().BeEmpty(); + log.EventTime.Should().Be(default); + log.EventType.Should().Be(AuditEventType.None); + } + + [Fact] + public void AuditEntityChangeLog_ShouldTrackFieldChanges() + { + // Arrange + var log = new AuditEntityChangeLog(); + var fieldChange = new AuditFieldChangeLog + { + FieldName = "Name", + ValueType = "string", + OriginalValue = "OldName", + NewValue = "NewName" + }; + + // Act + log.Details.Add(fieldChange); + + // Assert + log.Details.Should().ContainSingle(); + log.Details.First().Should().BeEquivalentTo(fieldChange); + } + + [Fact] + public void AuditEntityChangeLog_ShouldHandleMultipleFieldChanges() + { + // Arrange + var log = new AuditEntityChangeLog(); + var changes = new[] + { + new AuditFieldChangeLog { FieldName = "Name", ValueType = "string", OriginalValue = "Old", NewValue = "New" }, + new AuditFieldChangeLog { FieldName = "Age", ValueType = "int", OriginalValue = "20", NewValue = "21" } + }; + + // Act + foreach (var change in changes) + { + log.Details.Add(change); + } + + // Assert + log.Details.Should().HaveCount(2); + log.Details.Should().BeEquivalentTo(changes); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditEntityTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditEntityTests.cs new file mode 100644 index 0000000..c01b752 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditEntityTests.cs @@ -0,0 +1,260 @@ +using Microsoft.EntityFrameworkCore; + +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class AuditEntityTests +{ + private readonly DbContextOptions _options; + private readonly TestDbContext _dbContext; + + public AuditEntityTests() + { + _options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "AuditTestDb") + .Options; + _dbContext = new TestDbContext(_options); + } + + [Fact] + public async Task EntityCreate_ShouldGenerateAuditLog() + { + // Arrange + var user = new TestUser { Id = Guid.NewGuid(), Name = "TestUser" }; + _dbContext.Users.Add(user); + + // Act + await _dbContext.SaveChangesAsync(); + + // Assert + var auditLog = await _dbContext.AuditLogs.FirstOrDefaultAsync(); + auditLog.Should().NotBeNull(); + auditLog!.EntityTypeName.Should().Be(nameof(TestUser)); + auditLog.EventType.Should().Be(AuditEventType.Create); + auditLog.Details.Should().HaveCount(2); // Id and Name + } + + [Fact] + public async Task EntityUpdate_ShouldGenerateAuditLog() + { + // Arrange + var user = new TestUser { Id = Guid.NewGuid(), Name = "OriginalName" }; + _dbContext.Users.Add(user); + await _dbContext.SaveChangesAsync(); + + // Act + user.Name = "UpdatedName"; + await _dbContext.SaveChangesAsync(); + + // Assert + var auditLogs = await _dbContext.AuditLogs.ToListAsync(); + auditLogs.Should().HaveCount(2); + var updateLog = auditLogs[0]; + updateLog.EventType.Should().Be(AuditEventType.Modify); + updateLog.Details.Should().ContainSingle(d => d.FieldName == "Name" && d.NewValue == "UpdatedName"); + } + + [Fact] + public async Task EntityDelete_ShouldGenerateAuditLog() + { + // Arrange + var user = new TestUser { Id = Guid.NewGuid(), Name = "TestUser" }; + _dbContext.Users.Add(user); + await _dbContext.SaveChangesAsync(); + + // Act + _dbContext.Users.Remove(user); + await _dbContext.SaveChangesAsync(); + + // Assert + var auditLogs = await _dbContext.AuditLogs.ToListAsync(); + auditLogs.Should().HaveCount(2); + var deleteLog = auditLogs[0]; + deleteLog.EventType.Should().Be(AuditEventType.Delete); + } + + [Fact] + public async Task AuditLog_ShouldTrackAllChangedProperties() + { + // Arrange + var user = new TestUser { Id = Guid.NewGuid(), Name = "OriginalName", Age = 20 }; + _dbContext.Users.Add(user); + await _dbContext.SaveChangesAsync(); + + // Act + user.Name = "NewName"; + user.Age = 21; + await _dbContext.SaveChangesAsync(); + + // Assert + var auditLog = await _dbContext.AuditLogs + .Include(x => x.Details) + .OrderByDescending(x => x.EventTime) + .FirstAsync(); + + auditLog.Details.Should().HaveCount(2); + auditLog.Details.Should().Contain(d => d.FieldName == "Name" && d.NewValue == "NewName"); + auditLog.Details.Should().Contain(d => d.FieldName == "Age" && d.NewValue == "21"); + } + + [Fact] + public async Task ConcurrentUpdates_ShouldGenerateCorrectAuditLogs() + { + // Arrange + var user = new TestUser { Id = Guid.NewGuid(), Name = "OriginalName", Age = 20 }; + _dbContext.Users.Add(user); + await _dbContext.SaveChangesAsync(); + + // Act + var tasks = new[] + { + Task.Run(async () => + { + using var context = new TestDbContext(_options); + var user2 = await context.Users.FindAsync(user.Id); + user2!.Name = "Name1"; + await context.SaveChangesAsync(); + }), + Task.Run(async () => + { + using var context = new TestDbContext(_options); + var user3 = await context.Users.FindAsync(user.Id); + user3!.Age = 21; + await context.SaveChangesAsync(); + }) + }; + + await Task.WhenAll(tasks); + + // Assert + var auditLogs = await _dbContext.AuditLogs + .Include(x => x.Details) + .OrderByDescending(x => x.EventTime) + .ToListAsync(); + + auditLogs.Should().HaveCount(3); // 创建 + 2次更新 + var lastTwoLogs = auditLogs.Take(2).ToList(); + lastTwoLogs.Should().Contain(l => l.Details.Any(d => d.FieldName == "Name" && d.NewValue == "Name1")); + lastTwoLogs.Should().Contain(l => l.Details.Any(d => d.FieldName == "Age" && d.NewValue == "21")); + } + + [Fact] + public async Task ComplexEntity_ShouldTrackNavigationProperties() + { + // Arrange + var department = new TestDepartment { Id = Guid.NewGuid(), Name = "IT" }; + var user = new TestUser + { + Id = Guid.NewGuid(), + Name = "TestUser", + Department = department, + Roles = new List + { + new TestRole { Id = Guid.NewGuid(), Name = "Admin" }, + new TestRole { Id = Guid.NewGuid(), Name = "User" } + } + }; + + _dbContext.Users.Add(user); + await _dbContext.SaveChangesAsync(); + + // Act + user.Name = "UpdatedUser"; + user.Department.Name = "HR"; + user.Roles.Add(new TestRole { Id = Guid.NewGuid(), Name = "Manager" }); + await _dbContext.SaveChangesAsync(); + + // Assert + var auditLogs = await _dbContext.AuditLogs + .Include(x => x.Details) + .OrderByDescending(x => x.EventTime) + .ToListAsync(); + + auditLogs.Should().HaveCount(4); // 创建Department + 创建User + 更新User + 创建Role + var userUpdateLog = auditLogs.First(l => l.EntityTypeName == nameof(TestUser)); + userUpdateLog.Details.Should().Contain(d => d.FieldName == "Name" && d.NewValue == "UpdatedUser"); + } + + [Fact] + public async Task AuditLog_ShouldHandleNullNavigationProperties() + { + // Arrange + var user = new TestUser + { + Id = Guid.NewGuid(), + Name = "TestUser", + Department = null, + Roles = new List() + }; + + _dbContext.Users.Add(user); + await _dbContext.SaveChangesAsync(); + + // Act + user.Department = new TestDepartment { Id = Guid.NewGuid(), Name = "IT" }; + await _dbContext.SaveChangesAsync(); + + // Assert + var auditLogs = await _dbContext.AuditLogs + .Include(x => x.Details) + .OrderByDescending(x => x.EventTime) + .ToListAsync(); + + auditLogs.Should().HaveCount(3); // 创建User + 创建Department + 更新User + var userUpdateLog = auditLogs.First(l => l.EntityTypeName == nameof(TestUser)); + userUpdateLog.Details.Should().Contain(d => d.FieldName == "DepartmentId"); + } + + private class TestDbContext : DbContext + { + public DbSet Users { get; set; } = null!; + public DbSet Departments { get; set; } = null!; + public DbSet Roles { get; set; } = null!; + public DbSet> AuditLogs { get; set; } = null!; + + public TestDbContext(DbContextOptions options) : base(options) + { + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity().HasKey(u => u.Id); + modelBuilder.Entity().HasKey(d => d.Id); + modelBuilder.Entity().HasKey(r => r.Id); + modelBuilder.Entity>().HasKey(a => a.Id); + modelBuilder.Entity().HasKey(a => a.Id); + + modelBuilder.Entity() + .HasOne(u => u.Department) + .WithMany() + .HasForeignKey(u => u.DepartmentId); + + modelBuilder.Entity() + .HasMany(u => u.Roles) + .WithMany(r => r.Users) + .UsingEntity(j => j.ToTable("UserRoles")); + } + } + + private class TestUser + { + public Guid Id { get; set; } + public string Name { get; set; } = null!; + public int Age { get; set; } + public Guid? DepartmentId { get; set; } + public TestDepartment? Department { get; set; } + public ICollection Roles { get; set; } = new List(); + } + + private class TestDepartment + { + public Guid Id { get; set; } + public string Name { get; set; } = null!; + } + + private class TestRole + { + public Guid Id { get; set; } + public string Name { get; set; } = null!; + public ICollection Users { get; set; } = new List(); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditFieldChangeLogTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditFieldChangeLogTests.cs new file mode 100644 index 0000000..aed7367 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditFieldChangeLogTests.cs @@ -0,0 +1,72 @@ +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class AuditFieldChangeLogTests +{ + [Fact] + public void AuditFieldChangeLog_ShouldInitializeWithDefaultValues() + { + // Act + var log = new AuditFieldChangeLog(); + + // Assert + log.FieldName.Should().BeNull(); + log.ValueType.Should().BeNull(); + log.OriginalValue.Should().BeNull(); + log.NewValue.Should().BeNull(); + log.EntityLogId.Should().Be(0); + } + + [Fact] + public void AuditFieldChangeLog_ShouldTrackPropertyChanges() + { + // Arrange + var log = new AuditFieldChangeLog + { + FieldName = "Name", + ValueType = "string", + OriginalValue = "OldName", + NewValue = "NewName" + }; + + // Assert + log.FieldName.Should().Be("Name"); + log.ValueType.Should().Be("string"); + log.OriginalValue.Should().Be("OldName"); + log.NewValue.Should().Be("NewName"); + } + + [Fact] + public void AuditFieldChangeLog_ShouldHandleNullValues() + { + // Arrange + var log = new AuditFieldChangeLog + { + FieldName = "Name", + ValueType = "string", + OriginalValue = null, + NewValue = null + }; + + // Assert + log.OriginalValue.Should().BeNull(); + log.NewValue.Should().BeNull(); + } + + [Fact] + public void AuditFieldChangeLog_ShouldHandleDifferentValueTypes() + { + // Arrange + var log = new AuditFieldChangeLog + { + FieldName = "Age", + ValueType = "int", + OriginalValue = "20", + NewValue = "21" + }; + + // Assert + log.ValueType.Should().Be("int"); + log.OriginalValue.Should().Be("20"); + log.NewValue.Should().Be("21"); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditOptionsTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditOptionsTests.cs new file mode 100644 index 0000000..02f39ec --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditOptionsTests.cs @@ -0,0 +1,111 @@ +using Microsoft.EntityFrameworkCore; + +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class AuditOptionsTests +{ + [Fact] + public void AuditOptions_ShouldInitializeWithDefaultValues() + { + // Act + var options = new AuditOptions(); + + // Assert + options.Enabled.Should().BeTrue(); + options.IncludeEntityObjects.Should().BeFalse(); + options.SaveTempProperties.Should().BeFalse(); + options.AuditEventType.Should().Be(AuditEventType.All); + options.IncludeIndirectChanges.Should().BeFalse(); + } + + [Fact] + public void AuditOptions_ShouldAllowCustomConfiguration() + { + // Arrange + var options = new AuditOptions + { + Enabled = false, + IncludeEntityObjects = true, + SaveTempProperties = true, + AuditEventType = AuditEventType.Created | AuditEventType.Deleted, + IncludeIndirectChanges = true + }; + + // Assert + options.Enabled.Should().BeFalse(); + options.IncludeEntityObjects.Should().BeTrue(); + options.SaveTempProperties.Should().BeTrue(); + options.AuditEventType.Should().Be(AuditEventType.Created | AuditEventType.Deleted); + options.IncludeIndirectChanges.Should().BeTrue(); + } + + [Fact] + public async Task AuditOptions_ShouldRespectEnabledSetting() + { + // Arrange + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "AuditTestDb") + .Options; + var dbContext = new TestDbContext(options, new AuditOptions { Enabled = false }); + + var user = new TestUser { Id = Guid.NewGuid(), Name = "TestUser" }; + dbContext.Users.Add(user); + + // Act + await dbContext.SaveChangesAsync(); + + // Assert + var auditLogs = await dbContext.AuditLogs.ToListAsync(); + auditLogs.Should().BeEmpty(); + } + + [Fact] + public async Task AuditOptions_ShouldRespectAuditEventTypeSetting() + { + // Arrange + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "AuditTestDb") + .Options; + var dbContext = new TestDbContext(options, new AuditOptions { AuditEventType = AuditEventType.Created }); + + var user = new TestUser { Id = Guid.NewGuid(), Name = "TestUser" }; + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + + // Act + user.Name = "UpdatedName"; + await dbContext.SaveChangesAsync(); + + // Assert + var auditLogs = await dbContext.AuditLogs.ToListAsync(); + auditLogs.Should().HaveCount(1); + auditLogs[0].EventType.Should().Be(AuditEventType.Created); + } + + private class TestDbContext : DbContext + { + private readonly AuditOptions _auditOptions; + + public DbSet Users { get; set; } = null!; + public DbSet> AuditLogs { get; set; } = null!; + + public TestDbContext(DbContextOptions options, AuditOptions auditOptions) + : base(options) + { + _auditOptions = auditOptions; + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity().HasKey(u => u.Id); + modelBuilder.Entity>().HasKey(a => a.Id); + modelBuilder.Entity().HasKey(a => a.Id); + } + } + + private class TestUser + { + public Guid Id { get; set; } + public string Name { get; set; } = null!; + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/AuditTestsBase.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/AuditTestsBase.cs new file mode 100644 index 0000000..cb887fd --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/AuditTestsBase.cs @@ -0,0 +1,66 @@ +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace Ling.Audit.EntityFrameworkCore.Tests.Core; + +public abstract class AuditTestsBase : IDisposable +{ + private readonly SqliteConnection _connection; + protected ServiceProvider ServiceProvider { get; } + + protected AuditTestsBase() + { + _connection = new SqliteConnection("DataSource=:memory:"); + _connection.Open(); + + var services = new ServiceCollection(); + + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + { "Audit:AllowAnonymousCreate", "false" }, + { "Audit:AllowAnonymousModify", "false" }, + { "Audit:AllowAnonymousDelete", "false" }, + { "Audit:AuditNoFieldChangeEntity", "true" }, + { "Audit:Comments:CreatedBy", "Created By" }, + { "Audit:Comments:CreatedAt", "Created At" }, + { "Audit:Comments:ModifiedBy", "Modified By" }, + { "Audit:Comments:ModifiedAt", "Modified At" }, + { "Audit:Comments:DeletedBy", "Deleted By" }, + { "Audit:Comments:DeletedAt", "Deleted At" } + }) + .Build(); + + services.AddSingleton(configuration); + + services.AddDbContext(options => + ConfigureDbContext(options.UseInMemoryDatabase("TestDb"))); + + ConfigureServices(services); + + ServiceProvider = services.BuildServiceProvider(); + } + + protected virtual DbContextOptionsBuilder ConfigureDbContext(DbContextOptionsBuilder options) + { + options.UseAudit(); + + return options; + } + + protected virtual void ConfigureServices(IServiceCollection services) + { + // Override this method to configure additional services if needed + } + + void IDisposable.Dispose() + { + _connection.Close(); + _connection.Dispose(); + ServiceProvider.Dispose(); + + GC.SuppressFinalize(this); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/CategoryEntity.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/CategoryEntity.cs new file mode 100644 index 0000000..accbf91 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/CategoryEntity.cs @@ -0,0 +1,12 @@ +namespace Ling.Audit.EntityFrameworkCore.Tests.Core; + +[AuditInclude(EntityOperationType.Create)] +internal sealed partial class CategoryEntity : ICreationAudited +{ + public int Id { get; set; } + public string Name { get; set; } = null!; + [AuditIgnore] + public int Sort { get; set; } + + public ICollection Posts { get; set; } = new List(); +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/PostEntity.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/PostEntity.cs new file mode 100644 index 0000000..51f4b66 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/PostEntity.cs @@ -0,0 +1,10 @@ +namespace Ling.Audit.EntityFrameworkCore.Tests.Core; + +internal sealed partial class PostEntity : IFullAudited +{ + public int Id { get; set; } + public int CategoryId { get; set; } + public CategoryEntity Category { get; set; } = null!; + public string Title { get; set; } = null!; + public string Content { get; set; } = null!; +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/UserEntity.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/UserEntity.cs new file mode 100644 index 0000000..7e77a2a --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/UserEntity.cs @@ -0,0 +1,7 @@ +namespace Ling.Audit.EntityFrameworkCore.Tests.Core.Entities; + +internal sealed class UserEntity +{ + public int Id { get; set; } + public string Name { get; set; } = null!; +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/EquivalencyOptionsExtensions.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/EquivalencyOptionsExtensions.cs new file mode 100644 index 0000000..4d62bf1 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/EquivalencyOptionsExtensions.cs @@ -0,0 +1,91 @@ +using FluentAssertions.Equivalency; +using System.Linq.Expressions; + +namespace Ling.Audit.EntityFrameworkCore.Tests.Core; + +internal static class EquivalencyOptionsExtensions +{ + public static EquivalencyOptions ExcludingAuditProperties( + this EquivalencyOptions options) + { + if (typeof(TExpectation).GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IHasCreator<>))) + { + var exp = Expression.Lambda>( + Expression.Convert( + Expression.Property( + Expression.Parameter(typeof(TExpectation), "x"), + nameof(IHasCreator.CreatedBy)), + typeof(object)), + Expression.Parameter(typeof(TExpectation), "x")); + options = options.Excluding(exp); + } + + if (typeof(TExpectation).GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IHasModifier<>))) + { + var exp = Expression.Lambda>( + Expression.Convert( + Expression.Property( + Expression.Parameter(typeof(TExpectation), "x"), + nameof(IHasModifier.LastModifiedBy)), + typeof(object)), + Expression.Parameter(typeof(TExpectation), "x")); + options = options.Excluding(exp); + } + + if (typeof(TExpectation).GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IHasDeleter<>))) + { + var exp = Expression.Lambda>( + Expression.Convert( + Expression.Property( + Expression.Parameter(typeof(TExpectation), "x"), + nameof(IHasDeleter.DeletedBy)), + typeof(object)), + Expression.Parameter(typeof(TExpectation), "x")); + options = options.Excluding(exp); + } + + return options.ExcludingAuditTimes(); + } + + public static EquivalencyOptions ExcludingAuditTimes( + this EquivalencyOptions options) + { + if (typeof(TExpectation).GetInterfaces().Contains(typeof(IHasCreationTime))) + { + var exp = Expression.Lambda>( + Expression.Convert( + Expression.Property( + Expression.Parameter(typeof(TExpectation), "x"), + nameof(IHasCreationTime.CreatedAt)), + typeof(object)), + Expression.Parameter(typeof(TExpectation), "x")); + options = options.Excluding(exp); + } + + if (typeof(TExpectation).GetInterfaces().Contains(typeof(IHasModificationTime))) + { + var exp = Expression.Lambda>( + Expression.Convert( + Expression.Property( + Expression.Parameter(typeof(TExpectation), "x"), + nameof(IHasModificationTime.LastModifiedAt)), + typeof(object)), + Expression.Parameter(typeof(TExpectation), "x")); + options = options.Excluding(exp); + } + + if (typeof(TExpectation).GetInterfaces().Contains(typeof(IHasDeletionTime))) + { + var exp = Expression.Lambda>( + Expression.Convert( + Expression.Property( + Expression.Parameter(typeof(TExpectation), "x"), + nameof(IHasDeletionTime.DeletedAt)), + typeof(object)), + Expression.Parameter(typeof(TExpectation), "x")); + options = options.Excluding(exp); + } + + return options; + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/TestAuditContextProvider.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/TestAuditContextProvider.cs new file mode 100644 index 0000000..e84e51a --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/TestAuditContextProvider.cs @@ -0,0 +1,27 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; + +namespace Ling.Audit.EntityFrameworkCore.Tests.Core; + +internal sealed class TestAuditContextProvider : AuditContextProviderBase +{ + public TestAuditContextProvider(ICurrentDbContext current) : base(current) + { + } + + protected override AuditContext? GetAuditContext() + { + return new(1, "Tom", "192.168.1.10", "test client"); + } +} + +internal sealed class AnonymousAuditContextProvider : AuditContextProviderBase +{ + public AnonymousAuditContextProvider(ICurrentDbContext current) : base(current) + { + } + + protected override AuditContext? GetAuditContext() + { + return null; + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/TestDbContext.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/TestDbContext.cs new file mode 100644 index 0000000..2ba60fc --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/TestDbContext.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore; + +namespace Ling.Audit.EntityFrameworkCore.Tests.Core; + +internal sealed class TestDbContext : DbContext +{ + public TestDbContext(DbContextOptions options) : base(options) + { + } + + public DbSet Categories { get; set; } = default!; + public DbSet Posts { get; set; } = default!; + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity(b => + { + b.ToTable("Categories"); + b.HasKey(e => e.Id); + }); + modelBuilder.Entity(b => + { + b.ToTable("Posts"); + b.HasKey(e => e.Id); + b.IsAuditable(EntityOperationType.Delete); + b.Property(e => e.CategoryId).IsAuditable(); + }); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/EntityOperationTypeTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/EntityOperationTypeTests.cs new file mode 100644 index 0000000..2cb2654 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/EntityOperationTypeTests.cs @@ -0,0 +1,45 @@ +using FluentAssertions; +using Ling.Audit.EntityFrameworkCore; +using Xunit; + +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class EntityOperationTypeTests +{ + [Theory] + [InlineData(EntityOperationType.None, false, false, false)] + [InlineData(EntityOperationType.Create, true, false, false)] + [InlineData(EntityOperationType.Update, false, true, false)] + [InlineData(EntityOperationType.Delete, false, false, true)] + [InlineData(EntityOperationType.All, true, true, true)] + public void EntityOperationType_ShouldHaveCorrectFlags( + EntityOperationType operationType, + bool isCreate, + bool isUpdate, + bool isDelete) + { + // Assert + operationType.HasFlag(EntityOperationType.Create).Should().Be(isCreate); + operationType.HasFlag(EntityOperationType.Update).Should().Be(isUpdate); + operationType.HasFlag(EntityOperationType.Delete).Should().Be(isDelete); + } + + [Fact] + public void EntityOperationType_ShouldSupportCombinedOperations() + { + // Arrange + var createAndUpdate = EntityOperationType.Create | EntityOperationType.Update; + + // Assert + createAndUpdate.HasFlag(EntityOperationType.Create).Should().BeTrue(); + createAndUpdate.HasFlag(EntityOperationType.Update).Should().BeTrue(); + createAndUpdate.HasFlag(EntityOperationType.Delete).Should().BeFalse(); + } + + [Fact] + public void EntityOperationType_All_ShouldIncludeAllOperations() + { + // Assert + EntityOperationType.All.Should().Be(EntityOperationType.Create | EntityOperationType.Update | EntityOperationType.Delete); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Ling.Audit.EntityFrameworkCore.Tests.csproj b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Ling.Audit.EntityFrameworkCore.Tests.csproj new file mode 100644 index 0000000..7ce3f81 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Ling.Audit.EntityFrameworkCore.Tests.csproj @@ -0,0 +1,55 @@ + + + + net6.0;net7.0;net8.0;net9.0 + enable + enable + false + false + Ling.Audit.EntityFrameworkCore.Tests + Ling.Audit.EntityFrameworkCore.Tests + latest + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/PropertySerializerTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/PropertySerializerTests.cs new file mode 100644 index 0000000..2cbfc94 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/PropertySerializerTests.cs @@ -0,0 +1,119 @@ +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class PropertySerializerTests +{ + private readonly IPropertySerializer _serializer; + + public PropertySerializerTests() + { + _serializer = new DefaultPropertySerializer(); + } + + [Fact] + public void Serialize_ShouldHandlePrimitiveTypes() + { + // Arrange + var value = 42; + + // Act + var result = _serializer.Serialize(value); + + // Assert + result.Should().Be("42"); + } + + [Fact] + public void Serialize_ShouldHandleStrings() + { + // Arrange + var value = "Test String"; + + // Act + var result = _serializer.Serialize(value); + + // Assert + result.Should().Be("Test String"); + } + + [Fact] + public void Serialize_ShouldHandleNullValues() + { + // Arrange + string? value = null; + + // Act + var result = _serializer.Serialize(value); + + // Assert + result.Should().BeNull(); + } + + [Fact] + public void Serialize_ShouldHandleComplexObjects() + { + // Arrange + var value = new TestComplexObject + { + Id = 1, + Name = "Test", + Nested = new TestNestedObject { Value = "Nested" } + }; + + // Act + var result = _serializer.Serialize(value); + + // Assert + result.Should().NotBeNull(); + result.Should().Contain("Id"); + result.Should().Contain("Name"); + result.Should().Contain("Nested"); + } + + [Fact] + public void Serialize_ShouldHandleCollections() + { + // Arrange + var value = new List { 1, 2, 3 }; + + // Act + var result = _serializer.Serialize(value); + + // Assert + result.Should().NotBeNull(); + result.Should().Contain("1"); + result.Should().Contain("2"); + result.Should().Contain("3"); + } + + [Fact] + public void Serialize_ShouldHandleEnums() + { + // Arrange + var value = TestEnum.Value2; + + // Act + var result = _serializer.Serialize(value); + + // Assert + result.Should().Be("Value2"); + } + + private class TestComplexObject + { + public int Id { get; set; } + public string Name { get; set; } = null!; + public TestNestedObject Nested { get; set; } = null!; + } + + private class TestNestedObject + { + public string Value { get; set; } = null!; + } + + private enum TestEnum + { + Value1, + Value2, + Value3 + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/TestClass.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/TestClass.cs new file mode 100644 index 0000000..6b5d6a6 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/TestClass.cs @@ -0,0 +1,176 @@ +using Ling.Audit.EntityFrameworkCore.Tests.Core; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public class TestClass : AuditTestsBase +{ + public TestClass() + { + using var scope = ServiceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); + context.Database.EnsureCreated(); + + var category = new CategoryEntity + { + Name = "Test Category", + Sort = 1, + }; + + context.Posts.AddRange(new[] + { + new PostEntity + { + Title = "Test Post 1", + Content = "Content 1", + Category = category, + }, + new PostEntity + { + Title = "Test Post 2", + Content = "Content 2", + Category = category, + }, + }); + + context.SaveChanges(); + } + + [Fact] + public async Task RunAsync() + { + using var scope = ServiceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); + + var categories = await context.Categories + .Include(e => e.Posts) + .ToListAsync(); + + categories + .Should().ContainSingle().Which + .Should().BeEquivalentTo(new + { + Name = "Test Category", + Sort = 1, + CreatedBy = 1, + Posts = new object[] + { + new + { + Title = "Test Post 1", + Content = "Content 1", + CreatedBy = 1, + }, + new + { + Title = "Test Post 2", + Content = "Content 2", + CreatedBy = 1, + } + } + }); + + var auditLogs = await context.Set>() + .Include(e => e.Details) + .ToListAsync(); + + const string? @null = null; + auditLogs.Should().BeEquivalentTo(new object[] + { + new + { + DatabaseSchema = @null, + TableName = "Categories", + EntityKey = $"{nameof(CategoryEntity.Id)}={1}", + EntityTypeName = nameof(CategoryEntity), + EventType = AuditEventType.Create, + UserId = 1, + UserName = "Tom", + IPAddress = "192.168.1.10", + ClientName = "test client", + Details = new object[] + { + new + { + FieldName = nameof(CategoryEntity) + "." + nameof(CategoryEntity.Id), + OriginalValue = @null, + NewValue = "1", + }, + new + { + FieldName = nameof(CategoryEntity) + "." + nameof(CategoryEntity.Name), + OriginalValue = (string?)null, + NewValue = "Test Category", + }, + }, + }, + new + { + DatabaseSchema = @null, + TableName = "Posts", + EntityKey = $"{nameof(PostEntity.Id)}={1}", + EntityTypeName = nameof(PostEntity), + EventType = AuditEventType.Create, + UserId = 1, + UserName = "Tom", + IPAddress = "192.168.1.10", + ClientName = "test client", + Details = new List + { + new() + { + FieldName = nameof(PostEntity) + "." + nameof(PostEntity.Id), + OriginalValue = @null, + NewValue = "1", + }, + new() + { + FieldName = nameof(PostEntity) + "." + nameof(PostEntity.Title), + OriginalValue = null, + NewValue = "Test Post 1", + }, + new() + { + FieldName = nameof(PostEntity) + "." + nameof(PostEntity.Content), + OriginalValue = @null, + NewValue = "Content 1", + }, + }, + }, + new + { + DatabaseSchema = @null, + TableName = "Posts", + EntityKey = $"{nameof(PostEntity.Id)}={2}", + EntityTypeName = nameof(PostEntity), + EventType = AuditEventType.Create, + UserId = 1, + UserName = "Tom", + IPAddress = "192.168.1.10", + ClientName = "test client", + Details = new List + { + new() + { + FieldName = nameof(PostEntity) + "." + nameof(PostEntity.Id), + OriginalValue = @null, + NewValue = "2", + }, + new() + { + FieldName = nameof(PostEntity) + "." + nameof(PostEntity.Title), + OriginalValue = @null, + NewValue = "Test Post 2", + }, + new() + { + FieldName = nameof(PostEntity) + "." + nameof(PostEntity.Content), + OriginalValue = @null, + NewValue = "Content 2", + }, + }, + } + }, options => options.WithoutStrictOrdering()); + } +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/V2/AuditIntegrationTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/V2/AuditIntegrationTests.cs new file mode 100644 index 0000000..72f1535 --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/V2/AuditIntegrationTests.cs @@ -0,0 +1,216 @@ +using Ling.Audit; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using System.Text.Json; + +namespace Ling.Audit.EntityFrameworkCore.Tests; + +public sealed class AuditIntegrationTests +{ + [Fact] + public async Task SaveChanges_WritesAuditLogAndUsesSingleUtcTimestamp() + { + await using var fixture = await AuditFixture.CreateAsync(); + var entity = new TestEntity { Name = "created", TenantId = 1 }; + fixture.Context.Entities.Add(entity); + + await fixture.Context.SaveChangesAsync(); + + var log = await fixture.Context.Set>() + .Include(x => x.Details) + .SingleAsync(); + + entity.CreatedBy.Should().Be(42); + entity.CreatedAt.Offset.Should().Be(TimeSpan.Zero); + log.EventTime.Should().Be(entity.CreatedAt); + log.UserId.Should().Be(42); + log.Details.Should().Contain(x => x.FieldName.EndsWith(".Name")); + } + + [Fact] + public async Task QueryFilter_CombinesTenantAndSoftDeleteFilters() + { + await using var fixture = await AuditFixture.CreateAsync(); + fixture.Context.Entities.AddRange( + new TestEntity { Name = "visible", TenantId = 1 }, + new TestEntity { Name = "other tenant", TenantId = 2 }, + new TestEntity { Name = "deleted", TenantId = 1, IsDeleted = true }); + await fixture.Context.SaveChangesAsync(); + + var entities = await fixture.Context.Entities.ToListAsync(); + + entities.Should().ContainSingle(x => x.Name == "visible"); + } + + [Fact] + public async Task RequireExplicitTransaction_RejectsSaveWithoutTransaction() + { + await using var fixture = await AuditFixture.CreateAsync(AuditTransactionMode.RequireExplicitTransaction); + fixture.Context.Entities.Add(new TestEntity { Name = "requires transaction", TenantId = 1 }); + + var action = () => fixture.Context.SaveChangesAsync(); + + await action.Should().ThrowAsync() + .WithMessage("*explicit database transaction*"); + } + + [Fact] + public async Task RequireExplicitTransaction_RollsBackEntityAndAuditLogTogether() + { + await using var fixture = await AuditFixture.CreateAsync(AuditTransactionMode.RequireExplicitTransaction); + await using (var transaction = await fixture.Context.Database.BeginTransactionAsync()) + { + fixture.Context.Entities.Add(new TestEntity { Name = "rollback", TenantId = 1 }); + await fixture.Context.SaveChangesAsync(); + await transaction.RollbackAsync(); + } + + fixture.Context.ChangeTracker.Clear(); + (await fixture.Context.Entities.IgnoreQueryFilters().CountAsync()).Should().Be(0); + (await fixture.Context.Set>().CountAsync()).Should().Be(0); + } + + [Fact] + public async Task AuditableAttribute_AllowsConfiguredAnonymousOperation() + { + await using var fixture = await AuditFixture.CreateAsync(anonymous: true); + fixture.Context.AnonymousEntities.Add(new AnonymousEntity { Name = "allowed" }); + + await fixture.Context.SaveChangesAsync(); + + (await fixture.Context.Set>().CountAsync()).Should().Be(1); + } + + [Fact] + public async Task DefaultAnonymousHandler_RejectsOperation() + { + await using var fixture = await AuditFixture.CreateAsync(anonymous: true); + fixture.Context.Entities.Add(new TestEntity { Name = "rejected", TenantId = 1 }); + + var action = () => fixture.Context.SaveChangesAsync(); + + await action.Should().ThrowAsync() + .WithMessage("Anonymous Create operation is not allowed*"); + } + + [Fact] + public async Task SerializerOptions_AreAppliedToDefaultSerializer() + { + await using var fixture = await AuditFixture.CreateAsync(configure: options => + options.PropertySerializerOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + }); + var serializer = fixture.Context.GetService(); + + var value = serializer.Serialize(new ComplexValue { DisplayName = "value" }, typeof(ComplexValue)); + + value.Should().Contain("\"displayName\""); + } + + private sealed class AuditFixture : IAsyncDisposable + { + private readonly SqliteConnection _connection; + public TestDbContext Context { get; } + + private AuditFixture(SqliteConnection connection, TestDbContext context) + { + _connection = connection; + Context = context; + } + + public static async Task CreateAsync( + AuditTransactionMode transactionMode = AuditTransactionMode.BestEffort, + bool anonymous = false, + Action? configure = null) + { + var connection = new SqliteConnection("Data Source=:memory:"); + await connection.OpenAsync(); + var builder = new DbContextOptionsBuilder() + .UseSqlite(connection); + + if (anonymous) + { + builder.UseAudit(o => + { + o.TransactionMode = transactionMode; + configure?.Invoke(o); + }); + } + else + { + builder.UseAudit(o => + { + o.TransactionMode = transactionMode; + configure?.Invoke(o); + }); + } + + var context = new TestDbContext(builder.Options); + await context.Database.EnsureCreatedAsync(); + return new AuditFixture(connection, context); + } + + public async ValueTask DisposeAsync() + { + await Context.DisposeAsync(); + await _connection.DisposeAsync(); + } + } + + private sealed class TestDbContext(DbContextOptions options) : DbContext(options) + { + public DbSet Entities => Set(); + public DbSet AnonymousEntities => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity(builder => + { + builder.HasKey(x => x.Id); + builder.HasQueryFilter(x => x.TenantId == 1); + }); + modelBuilder.Entity().HasKey(x => x.Id); + } + } + + [Auditable] + private sealed class TestEntity : IFullAudited + { + public int Id { get; set; } + public string Name { get; set; } = string.Empty; + public int TenantId { get; set; } + public int? CreatedBy { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public int? LastModifiedBy { get; set; } + public DateTimeOffset? LastModifiedAt { get; set; } + public bool IsDeleted { get; set; } + public int? DeletedBy { get; set; } + public DateTimeOffset? DeletedAt { get; set; } + } + + [Auditable(AllowedAnonymous = DataOperation.Create)] + private sealed class AnonymousEntity : ICreationAudited + { + public int Id { get; set; } + public string Name { get; set; } = string.Empty; + public int? CreatedBy { get; set; } + public DateTimeOffset CreatedAt { get; set; } + } + + private sealed class TestUserProvider(ICurrentDbContext current) : AuditContextProviderBase(current) + { + protected override AuditContext GetAuditContext() => new(42, "Tester", "127.0.0.1", "Tests"); + } + + private sealed class AnonymousUserProvider(ICurrentDbContext current) : AuditContextProviderBase(current) + { + protected override AuditContext? GetAuditContext() => null; + } + + private sealed class ComplexValue + { + public string DisplayName { get; set; } = string.Empty; + } +} diff --git a/tests/Ling.Audit.PackageConsumer/Ling.Audit.PackageConsumer.csproj b/tests/Ling.Audit.PackageConsumer/Ling.Audit.PackageConsumer.csproj new file mode 100644 index 0000000..dbe3d98 --- /dev/null +++ b/tests/Ling.Audit.PackageConsumer/Ling.Audit.PackageConsumer.csproj @@ -0,0 +1,15 @@ + + + + Exe + net9.0 + enable + enable + ..\..\artifacts\package-consumer-final + + + + + + + diff --git a/tests/Ling.Audit.PackageConsumer/NuGet.config b/tests/Ling.Audit.PackageConsumer/NuGet.config new file mode 100644 index 0000000..5f22d45 --- /dev/null +++ b/tests/Ling.Audit.PackageConsumer/NuGet.config @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/tests/Ling.Audit.PackageConsumer/Program.cs b/tests/Ling.Audit.PackageConsumer/Program.cs new file mode 100644 index 0000000..8d7785c --- /dev/null +++ b/tests/Ling.Audit.PackageConsumer/Program.cs @@ -0,0 +1,8 @@ +using Ling.Audit; + +var entity = new ConsumerEntity(); +Console.WriteLine(entity.CreatedAt); + +public partial class ConsumerEntity : ICreationAudited +{ +} diff --git a/tests/Ling.Audit.SourceGenerators.Tests/Analyzers/AuditTypeAnalyzerTests.cs b/tests/Ling.Audit.SourceGenerators.Tests/Analyzers/AuditTypeAnalyzerTests.cs index d7b1d12..c0d1ade 100644 --- a/tests/Ling.Audit.SourceGenerators.Tests/Analyzers/AuditTypeAnalyzerTests.cs +++ b/tests/Ling.Audit.SourceGenerators.Tests/Analyzers/AuditTypeAnalyzerTests.cs @@ -99,6 +99,27 @@ public partial class MyEntity : IHasCreator, IHasCreationTime await VerifyCS.VerifyAnalyzerAsync(test); } + [Fact] + public async Task NestedPartialClass_WithNonPartialContainer_ReportsDiagnosticForContainer() + { + const string test = """ + using Ling.Audit; + + public class Container + { + public partial class MyEntity : IHasCreator + { + } + } + """; + + var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.PartialType) + .WithLocation(3, 14) + .WithArguments("Container"); + + await VerifyCS.VerifyAnalyzerAsync(test, expected); + } + [Fact] public async Task Record_WithoutPartialKeyword_ReportsDiagnostic() { diff --git a/tests/Ling.Audit.SourceGenerators.Tests/Analyzers/MustNullAttributeAnalyzerTests.cs b/tests/Ling.Audit.SourceGenerators.Tests/Analyzers/MustNullAttributeAnalyzerTests.cs index 472d834..1023d3c 100644 --- a/tests/Ling.Audit.SourceGenerators.Tests/Analyzers/MustNullAttributeAnalyzerTests.cs +++ b/tests/Ling.Audit.SourceGenerators.Tests/Analyzers/MustNullAttributeAnalyzerTests.cs @@ -189,6 +189,102 @@ public class Usage await VerifyCS.VerifyAnalyzerAsync(test, expected); } + [Fact] + public async Task GenericMethod_WithMustNullParameter_ValueType_ReportsDiagnostic() + { + const string test = """ + using Ling.Audit; + + public class Usage + { + public void Method<[MustNull] T>(T value) + { + } + + public void Test() + { + Method(42); + } + } + """; + + var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.TypeParameterMustBeNullable) + .WithLocation(11, 16) + .WithArguments("int"); + + await VerifyCS.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task GenericMethod_WithMustNullParameter_NullableType_NoDiagnostic() + { + const string test = """ + using Ling.Audit; + + public class Usage + { + public void Method<[MustNull] T>(T value) + { + } + + public void Test() + { + Method(null); + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task Method_ParameterType_ReportsDiagnostic() + { + const string test = """ + using Ling.Audit; + + public class Container<[MustNull] T> + { + } + + public class Usage + { + public void Method(Container param) + { + } + } + """; + + var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.TypeParameterMustBeNullable) + .WithLocation(9, 34) + .WithArguments("int"); + + await VerifyCS.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task Method_ReturnType_ReportsDiagnostic() + { + const string test = """ + using Ling.Audit; + + public class Container<[MustNull] T> + { + } + + public class Usage + { + public Container Method() => null; + } + """; + + var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.TypeParameterMustBeNullable) + .WithLocation(9, 22) + .WithArguments("int"); + + await VerifyCS.VerifyAnalyzerAsync(test, expected); + } + #endregion Member Declarations #region Nested Generic Types @@ -429,12 +525,13 @@ public class Usage : Dictionary, Container2> #endregion Complex Nested Types - #region Method Parameters and Return Types + #region Lambda Expressions [Fact] - public async Task Method_ParameterType_ReportsDiagnostic() + public async Task Lambda_AsMethodArgument_ReportsDiagnostic() { const string test = """ + using System; using Ling.Audit; public class Container<[MustNull] T> @@ -443,23 +540,29 @@ public class Container<[MustNull] T> public class Usage { - public void Method(Container param) + public void Process(Action> action) { } + + public void Method() + { + Process(x => { }); + } } """; var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.TypeParameterMustBeNullable) - .WithLocation(9, 34) + .WithLocation(10, 42) .WithArguments("int"); await VerifyCS.VerifyAnalyzerAsync(test, expected); } [Fact] - public async Task Method_ReturnType_ReportsDiagnostic() + public async Task Lambda_AsPropertyInitializer_ReportsDiagnostic() { const string test = """ + using System; using Ling.Audit; public class Container<[MustNull] T> @@ -468,23 +571,19 @@ public class Container<[MustNull] T> public class Usage { - public Container Method() => null; + public Action> Handler { get; } = x => { }; } """; var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.TypeParameterMustBeNullable) - .WithLocation(9, 22) + .WithLocation(10, 29) .WithArguments("int"); await VerifyCS.VerifyAnalyzerAsync(test, expected); } - #endregion Method Parameters and Return Types - - #region Lambda Expressions - [Fact] - public async Task Lambda_AsMethodArgument_ReportsDiagnostic() + public async Task Lambda_WithExplicitParameterType_ReportsDiagnostic() { const string test = """ using System; @@ -496,74 +595,339 @@ public class Container<[MustNull] T> public class Usage { - public void Process(Action> action) - { - } - public void Method() { - Process(x => { }); + var func = (Container x) => x; } } """; var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.TypeParameterMustBeNullable) - .WithLocation(10, 42) + .WithLocation(12, 31) .WithArguments("int"); await VerifyCS.VerifyAnalyzerAsync(test, expected); } + #endregion Lambda Expressions + + #region Method Calls + [Fact] - public async Task Lambda_AsPropertyInitializer_ReportsDiagnostic() + public async Task GenericMethod_ChainedCall_ReportsDiagnostic() { const string test = """ - using System; - using Ling.Audit; + using Ling.Audit; - public class Container<[MustNull] T> + public class Usage + { + public T Create<[MustNull] T>() => default!; + + public void Test() { + Create().ToString(); } + } + """; - public class Usage + var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.TypeParameterMustBeNullable) + .WithLocation(9, 16) + .WithArguments("int"); + + await VerifyCS.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task GenericMethod_MemberAccess_ReportsDiagnostic() + { + const string test = """ + using Ling.Audit; + + public static class Helper + { + public static T Create<[MustNull] T>() => default!; + } + + public class Usage + { + public void Test() { - public Action> Handler { get; } = x => { }; + Helper.Create(); } - """; + } + """; var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.TypeParameterMustBeNullable) - .WithLocation(10, 29) + .WithLocation(12, 23) .WithArguments("int"); await VerifyCS.VerifyAnalyzerAsync(test, expected); } [Fact] - public async Task Lambda_WithExplicitParameterType_ReportsDiagnostic() + public async Task GenericMethod_MultipleTypeParameters_ReportsDiagnostic() { const string test = """ - using System; - using Ling.Audit; + using Ling.Audit; - public class Container<[MustNull] T> + public class Usage + { + public void Method(T1 value1, T2 value2) { } - public class Usage + public void Test() { - public void Method() - { - var func = (Container x) => x; - } + Method("test", 42); } - """; + } + """; var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.TypeParameterMustBeNullable) - .WithLocation(12, 31) + .WithLocation(11, 24) .WithArguments("int"); await VerifyCS.VerifyAnalyzerAsync(test, expected); } - #endregion Lambda Expressions + [Fact] + public async Task GenericMethod_NestedGenericCall_ReportsDiagnostic() + { + const string test = """ + using System.Collections.Generic; + using Ling.Audit; + + public class Usage + { + public List WrapInList<[MustNull] T>(T item) => new List { item }; + + public void Test() + { + WrapInList(42); + } + } + """; + + var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.TypeParameterMustBeNullable) + .WithLocation(10, 20) + .WithArguments("int"); + + await VerifyCS.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task GenericMethod_ImplicitCall_NonNullableStruct_ReportsDiagnostic() + { + const string test = """ + using Ling.Audit; + + public class Usage + { + public T Method<[MustNull] T>(T item) => item; + + public void Test() + { + Method(42); // int is non-nullable struct + } + } + """; + + var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.ParameterTypeMustBeNullable) + .WithLocation(9, 16) + .WithArguments("42"); + + await VerifyCS.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task GenericMethod_ImplicitCall_ReferenceType_NoDiagnostic() + { + const string test = """ + using Ling.Audit; + + public class Usage + { + public T Method<[MustNull] T>(T item) => item; + + public void Test() + { + Method("test"); // string is reference type, always nullable + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task GenericMethod_ImplicitCall_NullableStruct_NoDiagnostic() + { + const string test = """ + using Ling.Audit; + + public class Usage + { + public T Method<[MustNull] T>(T item) => item; + + public void Test() + { + int? nullableInt = 42; + Method(nullableInt); // int? is nullable struct + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task GenericMethod_ImplicitCall_Variable_Struct_ReportsDiagnostic() + { + const string test = """ + using Ling.Audit; + + public class Usage + { + public T Method<[MustNull] T>(T item) => item; + + public void Test() + { + var value = 42; + Method(value); // var inferred as int + } + } + """; + + var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.ParameterTypeMustBeNullable) + .WithLocation(10, 16) + .WithArguments("value"); + + await VerifyCS.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task GenericMethod_ImplicitCall_Variable_Class_NoDiagnostic() + { + const string test = """ + using Ling.Audit; + + public class Usage + { + public T Method<[MustNull] T>(T item) => item; + + public void Test() + { + var text = "test"; + Method(text); // var inferred as string (reference type) + } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(test); + } + + [Fact] + public async Task GenericStaticMethod_ImplicitCall_NonNullableStruct_ReportsDiagnostic() + { + const string test = """ + using Ling.Audit; + + public class Usage + { + public static T StaticMethod<[MustNull] T>(T item) => item; + + public void Test() + { + StaticMethod(42); // int is non-nullable struct + } + } + """; + + var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.ParameterTypeMustBeNullable) + .WithLocation(9, 22) + .WithArguments("42"); + + await VerifyCS.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task GenericStaticMethod_ImplicitCall_FromStaticContext_ReportsDiagnostic() + { + const string test = """ + using Ling.Audit; + + public static class Usage + { + public static T StaticMethod<[MustNull] T>(T item) => item; + + public static void Test() + { + StaticMethod(42); // Called from static context + } + } + """; + + var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.ParameterTypeMustBeNullable) + .WithLocation(9, 22) + .WithArguments("42"); + + await VerifyCS.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task GenericStaticMethod_ImplicitCall_FromAnotherClass_ReportsDiagnostic() + { + const string test = """ + using Ling.Audit; + + public static class Helper + { + public static T Create<[MustNull] T>(T item) => item; + } + + public class Usage + { + public void Test() + { + Helper.Create(42); // Called from another class + } + } + """; + + var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.ParameterTypeMustBeNullable) + .WithLocation(12, 23) + .WithArguments("42"); + + await VerifyCS.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task GenericStaticMethod_ImplicitCall_ChainedMethods_ReportsDiagnostic() + { + const string test = """ + using Ling.Audit; + + public static class Helper + { + public static T Create<[MustNull] T>(T item) => item; + public static string ToString(T item) => item?.ToString() ?? ""; + } + + public class Usage + { + public void Test() + { + var result = Helper.Create(42).ToString(); // Method chaining + } + } + """; + + var expected = VerifyCS.Diagnostic(DiagnosticDescriptors.ParameterTypeMustBeNullable) + .WithLocation(13, 36) + .WithArguments("42"); + + await VerifyCS.VerifyAnalyzerAsync(test, expected); + } + + #endregion Method Calls } diff --git a/tests/Ling.Audit.SourceGenerators.Tests/AuditPropertyGeneratorTests.cs b/tests/Ling.Audit.SourceGenerators.Tests/AuditPropertyGeneratorTests.cs index 9f99a3d..e020100 100644 --- a/tests/Ling.Audit.SourceGenerators.Tests/AuditPropertyGeneratorTests.cs +++ b/tests/Ling.Audit.SourceGenerators.Tests/AuditPropertyGeneratorTests.cs @@ -6,6 +6,97 @@ namespace Ling.Audit.SourceGenerators.Tests; public class AuditPropertyGeneratorTests { + [Fact] + public async Task GeneratesAuditProperties_InGlobalNamespace() + { + const string source = """ + #nullable enable + using Ling.Audit; + + public partial class GlobalEntity : IHasCreator, IHasCreationTime + { + } + """; + + const string generatedCode = """ + // + + #pragma warning disable + #nullable enable annotations + + [global::System.CodeDom.Compiler.GeneratedCode("Ling.Audit.SourceGenerators", "2.0.1")] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + partial class GlobalEntity + { + /// + public virtual global::System.String? CreatedBy { get; set; } + + /// + public virtual global::System.DateTimeOffset CreatedAt { get; set; } + } + + """; + + await VerifyCS.VerifySourceGeneratorAsync(source, ("GlobalEntity.g.cs", generatedCode)); + } + + [Fact] + public async Task GeneratesAuditProperties_ForMultipleTypesInSameFile() + { + const string source = """ + using Ling.Audit; + + namespace Test + { + public partial class FirstEntity : IHasCreationTime { } + public partial class SecondEntity : ISoftDelete { } + } + """; + + const string firstGeneratedCode = """ + // + + #pragma warning disable + #nullable enable annotations + + namespace Test + { + [global::System.CodeDom.Compiler.GeneratedCode("Ling.Audit.SourceGenerators", "2.0.1")] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + partial class FirstEntity + { + /// + public virtual global::System.DateTimeOffset CreatedAt { get; set; } + } + } + + """; + + const string secondGeneratedCode = """ + // + + #pragma warning disable + #nullable enable annotations + + namespace Test + { + [global::System.CodeDom.Compiler.GeneratedCode("Ling.Audit.SourceGenerators", "2.0.1")] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + partial class SecondEntity + { + /// + public virtual global::System.Boolean IsDeleted { get; set; } + } + } + + """; + + await VerifyCS.VerifySourceGeneratorAsync( + source, + ("Test.FirstEntity.g.cs", firstGeneratedCode), + ("Test.SecondEntity.g.cs", secondGeneratedCode)); + } + [Fact] public async Task GeneratesAuditProperties_ForPartialClass() { @@ -32,7 +123,7 @@ namespace Test [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] partial class MyEntity { - /// + /// public virtual global::System.String? CreatedBy { get; set; } /// @@ -71,7 +162,7 @@ namespace Test [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] partial class MyEntity { - /// + /// public global::System.String? CreatedBy { get; set; } } } @@ -112,7 +203,7 @@ partial class Container [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] partial class MyEntity { - /// + /// public virtual global::System.String? CreatedBy { get; set; } } } @@ -186,7 +277,7 @@ namespace Test [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] partial class MyEntity { - /// + /// public virtual global::System.String? CreatedBy { get; set; } /// @@ -227,7 +318,7 @@ namespace Test [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] partial class MyEntity { - /// + /// public virtual global::System.String? CreatedBy { get; set; } } } @@ -264,7 +355,7 @@ namespace Test [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] partial class MyEntity { - /// + /// public virtual global::System.Nullable CreatedBy { get; set; } } } @@ -305,7 +396,7 @@ partial record Container [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] partial class MyEntity { - /// + /// public virtual global::System.String? CreatedBy { get; set; } } } diff --git a/tests/Ling.Audit.SourceGenerators.Tests/Ling.Audit.SourceGenerators.Tests.csproj b/tests/Ling.Audit.SourceGenerators.Tests/Ling.Audit.SourceGenerators.Tests.csproj index e1360b6..2f77ca7 100644 --- a/tests/Ling.Audit.SourceGenerators.Tests/Ling.Audit.SourceGenerators.Tests.csproj +++ b/tests/Ling.Audit.SourceGenerators.Tests/Ling.Audit.SourceGenerators.Tests.csproj @@ -31,4 +31,4 @@ - \ No newline at end of file + diff --git a/tests/Ling.Audit.SourceGenerators.Tests/Verifiers/CSharpAnalyzerVerifier.cs b/tests/Ling.Audit.SourceGenerators.Tests/Verifiers/CSharpAnalyzerVerifier.cs index 9a3e0a5..cb4d6f3 100644 --- a/tests/Ling.Audit.SourceGenerators.Tests/Verifiers/CSharpAnalyzerVerifier.cs +++ b/tests/Ling.Audit.SourceGenerators.Tests/Verifiers/CSharpAnalyzerVerifier.cs @@ -27,9 +27,11 @@ public static async Task VerifyAnalyzerAsync(string source, params DiagnosticRes private class Test : CSharpAnalyzerTest { + protected override string DefaultTestProjectName => "Ling.Audit.Tests"; + public Test() { - TestState.AdditionalReferences.Add(typeof(MustNullAttribute).Assembly); + TestState.AdditionalReferences.Add(typeof(ISoftDelete).Assembly); TestState.ReferenceAssemblies = ReferenceAssemblies.Net.Net80; } diff --git a/tests/Ling.Audit.SourceGenerators.Tests/Verifiers/CSharpCodeFixVerifier.cs b/tests/Ling.Audit.SourceGenerators.Tests/Verifiers/CSharpCodeFixVerifier.cs index c9c699a..95bc313 100644 --- a/tests/Ling.Audit.SourceGenerators.Tests/Verifiers/CSharpCodeFixVerifier.cs +++ b/tests/Ling.Audit.SourceGenerators.Tests/Verifiers/CSharpCodeFixVerifier.cs @@ -47,9 +47,11 @@ public static async Task VerifyCodeFixAsync(string source, string fixedSource, i private class Test : CSharpCodeFixTest { + protected override string DefaultTestProjectName => "Ling.Audit.Tests"; + public Test() { - TestState.AdditionalReferences.Add(typeof(MustNullAttribute).Assembly); + TestState.AdditionalReferences.Add(typeof(ISoftDelete).Assembly); TestState.ReferenceAssemblies = ReferenceAssemblies.Net.Net80; } diff --git a/tests/Ling.Audit.SourceGenerators.Tests/Verifiers/CSharpSourceGeneratorVerifier.cs b/tests/Ling.Audit.SourceGenerators.Tests/Verifiers/CSharpSourceGeneratorVerifier.cs index 3e6d5e1..3f808d7 100644 --- a/tests/Ling.Audit.SourceGenerators.Tests/Verifiers/CSharpSourceGeneratorVerifier.cs +++ b/tests/Ling.Audit.SourceGenerators.Tests/Verifiers/CSharpSourceGeneratorVerifier.cs @@ -4,12 +4,16 @@ using Microsoft.CodeAnalysis.Text; using System.Collections.Immutable; using System.Text; +using System.Text.RegularExpressions; namespace Ling.Audit.SourceGenerators.Tests.Verifiers; -internal static class CSharpSourceGeneratorVerifier +internal static partial class CSharpSourceGeneratorVerifier where TSourceGenerator : new() { + [GeneratedRegex(@"\r?\n")] + private static partial Regex NewLineRegex(); + public static async Task VerifySourceGeneratorAsync(string source, params (string FileName, string GeneratedCode)[] generatedSources) { var test = new Test @@ -22,9 +26,7 @@ public static async Task VerifySourceGeneratorAsync(string source, params (strin foreach (var (fileName, generatedCode) in generatedSources) { - var sourceText = generatedCode - .Replace("\r\n", Environment.NewLine) - .Replace("\n", Environment.NewLine); + var sourceText = NewLineRegex().Replace(generatedCode, Environment.NewLine); test.TestState.GeneratedSources.Add((typeof(TSourceGenerator), fileName, SourceText.From(sourceText, Encoding.UTF8))); } @@ -34,9 +36,11 @@ public static async Task VerifySourceGeneratorAsync(string source, params (strin private class Test : CSharpSourceGeneratorTest { + protected override string DefaultTestProjectName => "Ling.Audit.Tests"; + public Test() { - TestState.AdditionalReferences.Add(typeof(MustNullAttribute).Assembly); + TestState.AdditionalReferences.Add(typeof(ISoftDelete).Assembly); TestState.ReferenceAssemblies = ReferenceAssemblies.Net.Net80; }