From a7c90d40b0c892f2779dbe767bcaa803f70272a9 Mon Sep 17 00:00:00 2001 From: Jing Ling Date: Mon, 30 Dec 2024 00:39:42 +0800 Subject: [PATCH 1/9] Add comprehensive auditing system for EF Core The changes introduce a robust auditing system for Entity Framework Core, enabling detailed tracking and logging of entity changes. Key additions include: - New projects: `Ling.Audit.EntityFrameworkCore` and `Ling.Audit.AspNetCore`. - Extension methods in `DbContextOptionsBuilderExtensions.cs` for auditing configurations. - `HttpAuditContextProvider` class for user context information. - `AuditDefaults` and `AuditOptions` classes for default configurations and options. - `EntityOperationType` enum for different entity operations. - `IAuditContextProvider` interface for audit user information. - `AuditIgnoreAttribute` and `AuditIncludeAttribute` for property auditing control. - `ModelBuilderExtensions` for global query filters and entity configurations. - `AuditConventionSetPlugin` and related classes for custom conventions. - `AuditInterceptor` for intercepting save operations. - `AuditModelCustomizer` for model customizations. - Various utility classes and extensions for type conversions and primary key retrieval. - Classes for representing audit entries, metadata, and change logs. --- Ling.Audit.sln | 14 + .../DbContextOptionsBuilderExtensions.cs | 32 ++ .../DefaultAuditUserProvider.cs | 70 ++++ .../Ling.Audit.AspNetCore.csproj | 18 + .../Assembly.cs | 3 + .../Attributes/AuditIgnoreAttribute.cs | 7 + .../Attributes/AuditIncludeAttribute.cs | 13 + .../AuditDefaults.cs | 32 ++ .../AuditOptions.cs | 107 ++++++ .../EntityOperationType.cs | 33 ++ .../DbContextOptionsBuilderExtensions.cs | 89 +++++ .../Extensions/ModelBuilderExtensions.cs | 317 ++++++++++++++++++ .../IAuditContextProvider.cs | 27 ++ .../Internal/AuditConventionSetPlugin.cs | 21 ++ .../AuditIgnoreAttributeConvention.cs | 22 ++ .../AuditIncludeAttributeConvention.cs | 25 ++ .../Internal/AuditInterceptor.cs | 313 +++++++++++++++++ .../Internal/AuditModelCustomizer.cs | 36 ++ .../Internal/Constants.cs | 28 ++ .../Extensions/AuditConventionExtension.cs | 41 +++ .../Extensions/AuditOptionsExtension.cs | 51 +++ .../Internal/Extensions/ConvertExtensions.cs | 46 +++ .../Extensions/DbContextExtensions.cs | 23 ++ .../Extensions/EntityEntryExtensions.cs | 14 + .../Extensions/ReflectionExtensions.cs | 32 ++ .../Extensions/UserProviderExtension.cs | 41 +++ .../Internal/Models/AuditEntry.cs | 48 +++ .../Internal/Models/AuditMetadata.cs | 35 ++ .../Internal/Models/AuditPropertyEntry.cs | 24 ++ .../Ling.Audit.EntityFrameworkCore.csproj | 33 ++ .../Models/AuditEntityChangeLog.cs | 63 ++++ .../Models/AuditEventType.cs | 37 ++ .../Models/AuditFieldChangeLog.cs | 34 ++ .../AuditEntityLogTypeConfiguration.cs | 68 ++++ .../AuditFieldLogTypeConfiguration.cs | 40 +++ 35 files changed, 1837 insertions(+) create mode 100644 src/Ling.Audit.AspNetCore/DbContextOptionsBuilderExtensions.cs create mode 100644 src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs create mode 100644 src/Ling.Audit.AspNetCore/Ling.Audit.AspNetCore.csproj create mode 100644 src/Ling.Audit.EntityFrameworkCore/Assembly.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIgnoreAttribute.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIncludeAttribute.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/EntityOperationType.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/IAuditContextProvider.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/AuditIgnoreAttributeConvention.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/AuditIncludeAttributeConvention.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditConventionExtension.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ConvertExtensions.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/EntityEntryExtensions.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ReflectionExtensions.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/UserProviderExtension.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditEntry.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditMetadata.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditPropertyEntry.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj create mode 100644 src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Models/AuditEventType.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Models/AuditFieldChangeLog.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditEntityLogTypeConfiguration.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditFieldLogTypeConfiguration.cs diff --git a/Ling.Audit.sln b/Ling.Audit.sln index 8f48dca..6045c97 100644 --- a/Ling.Audit.sln +++ b/Ling.Audit.sln @@ -16,6 +16,10 @@ 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 Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -34,6 +38,14 @@ 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 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -42,5 +54,7 @@ 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} EndGlobalSection EndGlobal diff --git a/src/Ling.Audit.AspNetCore/DbContextOptionsBuilderExtensions.cs b/src/Ling.Audit.AspNetCore/DbContextOptionsBuilderExtensions.cs new file mode 100644 index 0000000..3afe170 --- /dev/null +++ b/src/Ling.Audit.AspNetCore/DbContextOptionsBuilderExtensions.cs @@ -0,0 +1,32 @@ +using Ling.Audit.AspNetCore; +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) + { + ArgumentNullException.ThrowIfNull(builder); + + builder.AddAuditOptions(setupAction); + + builder.AddAuditUserProvider(); + builder.AddAuditConvention(); + builder.AddAuditInterceptor(); + builder.AddModelCustomizer(); + + return builder; + } +} diff --git a/src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs b/src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs new file mode 100644 index 0000000..a4592e0 --- /dev/null +++ b/src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs @@ -0,0 +1,70 @@ +using Ling.Audit.EntityFrameworkCore; +using Ling.Audit.EntityFrameworkCore.Internal.Extensions; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System.Security.Claims; +using UAParser; + +namespace Ling.Audit.AspNetCore; + +/// +/// Default implementation of interface . +/// +internal sealed class HttpAuditContextProvider : IAuditContextProvider +{ + private readonly Lazy _lazyContext; + + /// + public string? Id => _lazyContext.Value.Id; + + /// + public string? Name => _lazyContext.Value.Name; + + /// + public string? IPAddress => _lazyContext.Value.IPAddress; + + /// + public string? ClientName => _lazyContext.Value.ClientName; + + public HttpAuditContextProvider(ICurrentDbContext current) + { + _lazyContext = new Lazy(() => new AuditContext( + current.Context.GetService>(), + current.Context.GetService(), + current.Context.GetAuditOptions())); + } + + private class AuditContext : IAuditContextProvider + { + public string? Id { get; } + public string? Name { get; } + public string? IPAddress { get; } + public string? ClientName { get; } + + public AuditContext(ILogger logger, IHttpContextAccessor httpContextAccessor, AuditOptions options) + { + var context = httpContextAccessor.HttpContext; + if (context is null) + { + logger.LogWarning("HttpContext is null for the current request."); + return; + } + + Id = context.User.FindFirstValue(options.UserIdClaimType); + Name = context.User.FindFirstValue(options.UserNameClaimType); + IPAddress = context.Connection.RemoteIpAddress?.ToString(); + + var userAgent = context.Request.Headers.UserAgent; + if (!string.IsNullOrEmpty(userAgent)) + { + ClientName = Parser.GetDefault().Parse(userAgent).ToString(); + } + else + { + logger.LogWarning("User-Agent header is missing."); + } + } + } +} 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..4f92b50 --- /dev/null +++ b/src/Ling.Audit.AspNetCore/Ling.Audit.AspNetCore.csproj @@ -0,0 +1,18 @@ + + + + net6.0;net7.0;net8.0;net9.0 + true + $(NoWarn);IDE0130 + + + + + + + + + + + + diff --git a/src/Ling.Audit.EntityFrameworkCore/Assembly.cs b/src/Ling.Audit.EntityFrameworkCore/Assembly.cs new file mode 100644 index 0000000..a7f5efa --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Assembly.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Ling.Audit.AspNetCore")] diff --git a/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIgnoreAttribute.cs b/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIgnoreAttribute.cs new file mode 100644 index 0000000..568e7f2 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIgnoreAttribute.cs @@ -0,0 +1,7 @@ +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Indicates that the property or field will not be audited. +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] +public class AuditIgnoreAttribute : Attribute; diff --git a/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIncludeAttribute.cs b/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIncludeAttribute.cs new file mode 100644 index 0000000..c39d70b --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIncludeAttribute.cs @@ -0,0 +1,13 @@ +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Indicates that the entity is automatically audited. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] +public class AuditIncludeAttribute : Attribute +{ + /// + /// Gets or sets the operation type that allows anonymous. + /// + public EntityOperationType AllowAnonymousOperate { get; init; } = EntityOperationType.None; +} diff --git a/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs b/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs new file mode 100644 index 0000000..5bafc59 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs @@ -0,0 +1,32 @@ +using Microsoft.Extensions.Configuration; + +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Define the audit configuration items. +/// +public static class AuditDefaults +{ + /// + /// The key of the for disable auditing. Setting this value to will disable. + /// + public const string DisabledSwitchKey = "Ling.DisableAudit"; + + /// + /// The key for the configuration. + /// It will be used to get the from 's section. + /// + public const string ConfigurationKey = "Audit"; + + /// + /// Table name that records entity change audit logs. + /// DO NOT change this value if migrations are added. + /// + public static string EntityChangeAuditLogTableName { get; set; } = "AuditEntityLog"; + + /// + /// The table name that records entity's fields change audit logs. + /// DO NOT change this value if migrations are added. + /// + public static string EntityFieldChangeAuditLogTableName { get; set; } = "AuditFieldLog"; +} diff --git a/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs b/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs new file mode 100644 index 0000000..2ed304f --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs @@ -0,0 +1,107 @@ +using System.Security.Claims; + +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Option to configure the behavior of audited entities. +/// +public class AuditOptions +{ + internal Type? UserIdType { get; set; } + + /// + /// Whether to allow anonymous creation of audit entities, default to . + /// + /// An will be thrown when anonymous creation, you can + /// use to specify anonymous operations that entities can perform. + /// + /// If , it will allow anonymous creation for all audit entities. + /// + public bool AllowAnonymousCreate { get; set; } + + /// + /// Whether to allow anonymous modification of audit entities, default to . + /// + /// An will be thrown when anonymous modification, you + /// can use to specify anonymous operations that entities can perform. + /// + /// If , it will allow anonymous modification for all audit entities. + /// + public bool AllowAnonymousModify { get; set; } + + /// + /// Whether to allow anonymous deletion of audit entities, default to . + /// + /// An will be thrown when anonymous deletion, you can + /// use to specify anonymous operations that entities can perform. + /// + /// If , it will allow anonymous deletion for all audit entities. + /// + public bool AllowAnonymousDelete { get; set; } + + /// + /// Claim type of user identity. + /// + public string UserIdClaimType { get; set; } = ClaimTypes.NameIdentifier; + + /// + /// Claim type of user name. + /// + public string UserNameClaimType { get; set; } = ClaimTypes.Name; + + /// + /// Comments. + /// + public AuditEntityComments Comments { get; set; } = new(); + + /// + /// Whether to audit entities that has no field changes, default to . + /// + public bool AuditNoFieldChangeEntity { get; set; } +} + +/// +/// Comments to the audited entities. +/// +public class AuditEntityComments +{ + /// + /// Comment to Id property. + /// + public string Id { get; set; } = "Unique identifier, primary key."; + + /// + /// 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 primary key of the user who modified this entity."; + + /// + /// Comment to ModifiedBy property. + /// + public string ModifiedBy { get; set; } = "The date and time when 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/EntityOperationType.cs b/src/Ling.Audit.EntityFrameworkCore/EntityOperationType.cs new file mode 100644 index 0000000..4f564e8 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/EntityOperationType.cs @@ -0,0 +1,33 @@ +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Enum that specifies the type of operation performed on an entity. +/// +[Flags] +public enum EntityOperationType : byte +{ + /// + /// No operation. + /// + None = 0, + + /// + /// Entity creation operation. + /// + Create = 1 << 1, + + /// + /// Entity update operation. + /// + Update = 1 << 2, + + /// + /// Entity deletion operation. + /// + Delete = 1 << 3, + + /// + /// Combination of Create, Update, and Delete operations. + /// + All = Create | Update | 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..bd8fcd9 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs @@ -0,0 +1,89 @@ +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 : class, IAuditContextProvider + { + ArgumentNullException.ThrowIfNull(builder); + + builder.AddAuditOptions(setupAction, o => o.UserIdType = typeof(TUserId)); + + builder.AddAuditUserProvider(); + builder.AddAuditConvention(); + builder.AddAuditInterceptor(); + builder.AddModelCustomizer(); + + return builder; + } + + internal static DbContextOptionsBuilder AddAuditOptions( + this DbContextOptionsBuilder builder, + Action? setupAction, + Action? additional = null) + { + var extension = builder.Options.FindExtension(); + if (extension is null) + { + var combine = (setupAction ?? delegate { }) + (additional ?? delegate { }); + extension = new AuditOptionsExtension(combine); + } + + ((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(extension); + + return builder; + } + + internal static DbContextOptionsBuilder AddAuditUserProvider(this DbContextOptionsBuilder builder) + where TUserProvider : class, IAuditContextProvider + { + var extension = builder.Options.FindExtension>() + ?? new UserProviderExtension(); + + ((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(extension); + + return builder; + } + + internal static DbContextOptionsBuilder AddAuditConvention(this DbContextOptionsBuilder builder) + { + var extension = builder.Options.FindExtension() ?? new AuditConventionExtension(); + + ((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(extension); + + return builder; + } + + internal static DbContextOptionsBuilder AddAuditInterceptor(this DbContextOptionsBuilder builder) + { + builder.AddInterceptors(new AuditInterceptor()); + builder.ReplaceService>(); + + return builder; + } + + internal static DbContextOptionsBuilder AddModelCustomizer(this DbContextOptionsBuilder builder) + { + builder.AddInterceptors(new AuditInterceptor()); + 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..aca52e5 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs @@ -0,0 +1,317 @@ +using Ling.Audit.EntityFrameworkCore.Extensions; +using Ling.Audit.EntityFrameworkCore.Internal; +using Ling.Audit.EntityFrameworkCore.Internal.Models; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System.Diagnostics; +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); + var lambda = Expression.Lambda(Expression.Not(propertyParameter), 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, EntityOperationType allowAnonymousOperate = EntityOperationType.None) + { + ArgumentNullException.ThrowIfNull(entityTypeBuilder); + + entityTypeBuilder.Metadata.SetAnnotation(Constants.IncludeAnnotationName, true); + entityTypeBuilder.Metadata.SetAuditMetadata(new AuditMetadata { AllowAnonymousOperate = allowAnonymousOperate }); + + return entityTypeBuilder; + } + + /// + /// The entity type being configured. + public static EntityTypeBuilder IsAuditable(this EntityTypeBuilder entityTypeBuilder, EntityOperationType allowAnonymousOperate = EntityOperationType.None) + where TEntity : class + => (EntityTypeBuilder)((EntityTypeBuilder)entityTypeBuilder).IsAuditable(allowAnonymousOperate); + + /// + /// Configures whether to apply auditing to the column. + /// + /// The builder for the property being configured. + /// Whether to audit the column, defaults to . + /// The same builder instance so that multiple calls can be chained. + public static PropertyBuilder IsAuditable(this PropertyBuilder propertyBuilder, bool enabled = false) + { + ArgumentNullException.ThrowIfNull(propertyBuilder); + + propertyBuilder.Metadata.SetAnnotation(Constants.IncludeAnnotationName, enabled); + return propertyBuilder; + } + + /// + /// The type of the property being configured. + public static PropertyBuilder IsAuditable(this PropertyBuilder propertyBuilder, bool enabled = false) + => (PropertyBuilder)((PropertyBuilder)propertyBuilder).IsAuditable(enabled); + + #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. + /// + /// The identity type of user for current . + internal static Type? ConfigureAuditableEntities(this ModelBuilder builder, AuditOptions options) + { + Type? userIdType = options.UserIdType; + Type? entityClrType = null; + foreach (var entityType in builder.Model.GetEntityTypes()) + { + var type = entityType.ClrType; + var auditMetadata = entityType.GetAuditMetadata(); + + if (entityType.HasProperty(Constants.Id, out var propertyType)) + { + builder.Entity(type) + .Property(propertyType, Constants.Id) + .HasColumnOrder(0) + .HasComment(options.Comments.Id); + } + + if (entityType.HasProperty(Constants.CreatedAt, out propertyType)) + { + builder.Entity(type) + .Property(propertyType, Constants.CreatedAt) + .HasColumnOrder(991) + .HasComment(options.Comments.CreatedAt); + + CheckDateTimeOffset(type, Constants.CreatedAt, propertyType); + auditMetadata.HasCreatedAt = true; + } + if (entityType.HasProperty(Constants.CreatedBy, out var cUserIdType)) + { + builder.Entity(type) + .Property(cUserIdType, Constants.CreatedBy) + .HasColumnOrder(992) + .HasComment(options.Comments.CreatedBy); + + CheckAndAssign(ref entityClrType, ref userIdType, type, cUserIdType); + auditMetadata.UserIdType = cUserIdType; + auditMetadata.HasCreatedBy = true; + } + + if (entityType.HasProperty(Constants.ModifiedAt, out propertyType)) + { + builder.Entity(type) + .Property(propertyType, Constants.ModifiedAt) + .HasColumnOrder(994) + .HasComment(options.Comments.ModifiedAt); + + CheckDateTimeOffset(type, Constants.ModifiedAt, propertyType); + auditMetadata.HasModifiedAt = true; + } + if (entityType.HasProperty(Constants.ModifiedBy, out var mUserIdType)) + { + builder.Entity(type) + .Property(mUserIdType, Constants.ModifiedBy) + .HasColumnOrder(995) + .HasComment(options.Comments.ModifiedBy); + + CheckAndAssign(ref entityClrType, ref userIdType, type, mUserIdType); + auditMetadata.UserIdType = mUserIdType; + auditMetadata.HasModifiedBy = true; + } + + if (entityType.HasProperty(Constants.IsDeleted, out propertyType)) + { + builder.Entity(type) + .Property(propertyType, Constants.IsDeleted) + .HasColumnOrder(997) + .HasComment(options.Comments.IsDeleted); + + CheckBoolean(type, Constants.IsDeleted, propertyType); + auditMetadata.HasIsDeleted = true; + } + if (entityType.HasProperty(Constants.DeletedAt, out propertyType)) + { + builder.Entity(type) + .Property(propertyType, Constants.DeletedAt) + .HasColumnOrder(998) + .HasComment(options.Comments.DeletedAt); + + CheckDateTimeOffset(type, Constants.DeletedAt, propertyType); + auditMetadata.HasDeletedAt = true; + } + if (entityType.HasProperty(Constants.DeletedBy, out var dUserIdType)) + { + builder.Entity(type) + .Property(dUserIdType, Constants.DeletedBy) + .HasColumnOrder(999) + .HasComment(options.Comments.DeletedBy); + + CheckAndAssign(ref entityClrType, ref userIdType, type, dUserIdType); + auditMetadata.UserIdType = dUserIdType; + auditMetadata.HasDeletedBy = true; + } + + entityType.SetAuditMetadata(auditMetadata); + +#if NET6_0 + if (IsDesignTime) +#else + if (EF.IsDesignTime) +#endif + { + Debug.WriteLine("Currently running in design time."); + entityType.RemoveAnnotation(Constants.MetadataAnnotationName); + } + } + + return userIdType; + } + + internal static bool GetAuditInclude(this IReadOnlyAnnotatable annotatable) + { + ArgumentNullException.ThrowIfNull(annotatable); + + var value = annotatable.FindAnnotation(Constants.IncludeAnnotationName)?.Value; + return annotatable switch + { + IEntityType => value is not null && (bool)value, // Entity auditable defaults to false + IProperty => value is null || (bool)value, // Entity property or field auditable defaults to true + _ => throw new InvalidOperationException() + }; + } + + internal static void SetAuditMetadata(this IMutableEntityType entityType, AuditMetadata metadata) + { + ArgumentNullException.ThrowIfNull(entityType); + ArgumentNullException.ThrowIfNull(metadata); + + if (entityType.FindAnnotation(Constants.MetadataAnnotationName)?.Value is AuditMetadata original) + { + original.Append(metadata); + entityType.SetAnnotation(Constants.MetadataAnnotationName, original); + } + else + { + entityType.SetAnnotation(Constants.MetadataAnnotationName, metadata); + } + } + + internal static AuditMetadata GetAuditMetadata(this IReadOnlyAnnotatable entityType) + { + ArgumentNullException.ThrowIfNull(entityType); + + return entityType.FindAnnotation(Constants.MetadataAnnotationName)?.Value is AuditMetadata metadata + ? metadata + : new AuditMetadata(); + } + + #endregion Internal Methods + + #region Private Methods + + private static void CheckAndAssign(ref Type? entityType, ref Type? userIdType, Type currentEntityType, Type currenTUserIdtype) + { + if (userIdType is null) + { + entityType = currentEntityType; + userIdType = currenTUserIdtype; + } + else if (userIdType != currenTUserIdtype) + { + const string msg = "All audit entities in the same 'DbContext' cannot have different user's identity types."; + var desc = entityType == currentEntityType + ? string.Format( + "Entity type '{0}' has both type '{1}' and type '{2}' as user's identity type.", + currentEntityType.GetFriendlyName(), + userIdType.GetFriendlyName(), + currenTUserIdtype.GetFriendlyName()) + : string.Format( + "Entity type '{0}' has type '{1}' as user key type but entity '{2}' has type '{3}' as user's identity type.", + entityType!.GetFriendlyName(), + userIdType.GetFriendlyName(), + currentEntityType.GetFriendlyName(), + currenTUserIdtype.GetFriendlyName()); + throw new InvalidOperationException($"{msg} {desc}"); + } + } + + private static void CheckDateTimeOffset(Type currentEntityType, string propertyName, Type propertyType) + { + if (!propertyType.IsAssignableFrom(typeof(DateTimeOffset))) + { + throw new InvalidOperationException(string.Format( + "Type '{2}' of member '{1}' in entity type '{0}' is neither 'DateTimeOffset' nor 'DateTimeOffset?'.", + currentEntityType.GetFriendlyName(), + propertyName, + propertyType.GetFriendlyName())); + } + } + + private static void CheckBoolean(Type currentEntityType, string propertyName, Type propertyType) + { + if (!propertyType.IsAssignableFrom(typeof(bool))) + { + throw new InvalidOperationException(string.Format( + "Type '{2}' of member '{1}' in entity type '{0}' is not 'bool'.", + currentEntityType.GetFriendlyName(), + propertyName, + propertyType.GetFriendlyName())); + } + } + + private static bool HasProperty(this IMutableEntityType entityType, string propertyName) + { + return entityType.FindProperty(propertyName) is not null; + } + + private static bool HasProperty(this IMutableEntityType entityType, string propertyName, [NotNullWhen(true)] out Type? type) + { + type = entityType.FindProperty(propertyName)?.ClrType; + return type is not null; + } + + #endregion Private Methods +} diff --git a/src/Ling.Audit.EntityFrameworkCore/IAuditContextProvider.cs b/src/Ling.Audit.EntityFrameworkCore/IAuditContextProvider.cs new file mode 100644 index 0000000..d7ade27 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/IAuditContextProvider.cs @@ -0,0 +1,27 @@ +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Interface for audit user information. +/// +public interface IAuditContextProvider +{ + /// + /// 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; } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs new file mode 100644 index 0000000..6d439b8 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs @@ -0,0 +1,21 @@ +using Microsoft.EntityFrameworkCore.Metadata.Conventions; +using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; + +namespace Ling.Audit.EntityFrameworkCore.Internal; + +internal class AuditConventionSetPlugin : IConventionSetPlugin +{ + private readonly ProviderConventionSetBuilderDependencies _dependencies; + + 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; + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIgnoreAttributeConvention.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIgnoreAttributeConvention.cs new file mode 100644 index 0000000..2f5d7c4 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIgnoreAttributeConvention.cs @@ -0,0 +1,22 @@ +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Microsoft.EntityFrameworkCore.Metadata.Conventions; +using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; +using System.Reflection; + +namespace Ling.Audit.EntityFrameworkCore.Internal; + +internal sealed class AuditIgnoreAttributeConvention : PropertyAttributeConventionBase +{ + public AuditIgnoreAttributeConvention(ProviderConventionSetBuilderDependencies dependencies) : base(dependencies) + { + } + + protected override void ProcessPropertyAdded( + IConventionPropertyBuilder propertyBuilder, + AuditIgnoreAttribute attribute, + MemberInfo clrMember, + IConventionContext context) + { + propertyBuilder.Metadata.SetAnnotation(Constants.IncludeAnnotationName, false); + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIncludeAttributeConvention.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIncludeAttributeConvention.cs new file mode 100644 index 0000000..e95dc72 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIncludeAttributeConvention.cs @@ -0,0 +1,25 @@ +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Microsoft.EntityFrameworkCore.Metadata.Conventions; +using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; + +namespace Ling.Audit.EntityFrameworkCore.Internal; + +internal class AuditIncludeAttributeConvention : +#if NET8_0_OR_GREATER + TypeAttributeConventionBase +#else + EntityTypeAttributeConventionBase +#endif +{ + public AuditIncludeAttributeConvention(ProviderConventionSetBuilderDependencies dependencies) : base(dependencies) + { + } + + protected override void ProcessEntityTypeAdded( + IConventionEntityTypeBuilder entityTypeBuilder, + AuditIncludeAttribute attribute, + IConventionContext context) + { + entityTypeBuilder.Metadata.SetAnnotation(Constants.IncludeAnnotationName, true); + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs new file mode 100644 index 0000000..4f553f8 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs @@ -0,0 +1,313 @@ +using Ling.Audit.EntityFrameworkCore.Extensions; +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.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; + +namespace Ling.Audit.EntityFrameworkCore.Internal; + +internal sealed class AuditInterceptor : SaveChangesInterceptor, IDisposable +{ + private IReadOnlyList? _entries; + + /// + public override InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) + { + InternalSavingChanges(eventData); + return base.SavingChanges(eventData, result); + } + + /// + public override int SavedChanges(SaveChangesCompletedEventData eventData, int result) + { + var count = InternalSavedChanges(eventData); + if (count > 0) + { + eventData.Context!.SaveChanges(); + } + return result; + } + + /// + public override ValueTask> SavingChangesAsync( + DbContextEventData eventData, + InterceptionResult result, + CancellationToken cancellationToken = default) + { + InternalSavingChanges(eventData); + return base.SavingChangesAsync(eventData, result, cancellationToken); + } + + /// + public override async ValueTask SavedChangesAsync( + SaveChangesCompletedEventData eventData, + int result, CancellationToken + cancellationToken = default) + { + var count = InternalSavedChanges(eventData); + if (count > 0) + { + await eventData.Context!.SaveChangesAsync(cancellationToken); + } + return result; + } + + internal void InternalSavingChanges(DbContextEventData eventData) + { + var context = eventData.Context; + + if (context is null) return; + + var userProvider = context.GetService>(); + var logger = context.GetService().CreateLogger(GetType()); + var options = context.GetAuditOptions(); + var entries = new List(); + var now = DateTimeOffset.Now; + var isUserIdDefaultValue = EqualityComparer.Default.Equals(userProvider.Id, default); + + foreach (var entityEntry in context.ChangeTracker.Entries()) + { + var entityType = entityEntry.Metadata.ClrType; + var metadata = entityEntry.Metadata.GetAuditMetadata(); + var eventType = AuditEventType.None; + var userId = isUserIdDefaultValue ? null : userProvider.Id.ConvertToTargetType(metadata.UserIdType); + + if (typeof(TUserId).IsSameTypeIgnoreNullableTo(metadata.UserIdType)) + { + logger.LogError( + "The type of 'TUserId' configured is '{UserIdType}', but entity's user key type is '{entityType}'.", + typeof(TUserId), + metadata.UserIdType); + throw new InvalidOperationException($"The type of 'TUserId' configured is not match entity [{entityType}]."); + } + + switch (entityEntry.State) + { + case EntityState.Deleted: + if (metadata.HasDeletedAt) + { + entityEntry.Property(Constants.DeletedAt).CurrentValue = now; + } + + if (metadata.HasDeletedBy) + { + if (!options.AllowAnonymousDelete && + !metadata.IsAllowedAnonymousOperate(EntityOperationType.Delete) && + isUserIdDefaultValue) + { + logger.LogError("Not allowed to delete entity '{entityType}' with anonymous user.", entityType); + throw new InvalidOperationException($"Anonymous deletion of '{entityType.GetFriendlyName()}' is not allowed."); + } + 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) + { + if (!options.AllowAnonymousModify && + !metadata.IsAllowedAnonymousOperate(EntityOperationType.Update) && + isUserIdDefaultValue) + { + logger.LogError("Not allowed to modify entity '{entityType}' with anonymous user.", entityType); + throw new InvalidOperationException($"Anonymous modification of {entityType.GetFriendlyName()} is not allowed."); + } + + 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) + { + if (!options.AllowAnonymousCreate && + !metadata.IsAllowedAnonymousOperate(EntityOperationType.Create) && + isUserIdDefaultValue) + { + logger.LogError("Not allowed to create entity '{entityType}' with anonymous user.", entityType); + throw new InvalidOperationException($"Anonymous creation of {entityType.GetFriendlyName()} is not allowed."); + } + entityEntry.Property(Constants.CreatedBy).CurrentValue = userId; + } + eventType = AuditEventType.Create; + break; + + case EntityState.Detached: + case EntityState.Unchanged: + default: + break; + } + + if (eventType is not AuditEventType.None && TryGetAuditEntry(entityEntry, out var auditEntry)) + { + auditEntry.EventType = eventType; + entries.Add(auditEntry); + } + } + + if (!AppContext.TryGetSwitch(AuditDefaults.DisabledSwitchKey, out var disabled) || !disabled) + { + _entries = entries; + } + } + + internal int InternalSavedChanges(SaveChangesCompletedEventData eventData) + { + var context = eventData.Context; + + if (context is null || (AppContext.TryGetSwitch(AuditDefaults.DisabledSwitchKey, out var disabled) && disabled)) return 0; + + var options = context.GetAuditOptions(); + var logger = context.GetService().CreateLogger(GetType()); + if (_entries is null) + { + logger.LogWarning("Unable to get entry information when saved changes."); + throw new InvalidOperationException("Unable to get entry information before saving changes."); + } + + var userProvider = context.GetService>(); + var logs = _entries + .Select(i => new AuditEntityChangeLog + { + DatabaseSchema = i.Schema, + TableName = i.Table, + EntityKey = i.PrimaryKey, + EntityTypeName = i.EntityType, + EventType = i.EventType, + EventTime = DateTimeOffset.Now, + UserId = userProvider.Id, + UserName = userProvider.Name, + Details = i.Properties.ConvertAll(j => new AuditFieldChangeLog + { + FieldName = i.EntityType + '.' + j.PropertyName, + OriginalValue = GetStringValue(j.OriginalValue), + NewValue = GetStringValue(j.NewValue), + }), + }) + .ToList(); + + int entityChangedCount = 0, fieldChangedCount = 0; + foreach (var log in logs) + { + if (log.Details.Count > 0 || options.AuditNoFieldChangeEntity) + { + context.Add(log); + entityChangedCount++; + fieldChangedCount += log.Details.Count; + } + } + + logger.LogInformation( + "Add {EntityCount} entity changed and {FieldCount} field changed audit logs to {DbContextType}[{ContextId}].", + entityChangedCount, + fieldChangedCount, + context.GetType().GetFriendlyName(), + context.ContextId); + return entityChangedCount + fieldChangedCount; + } + + private static bool TryGetAuditEntry(EntityEntry entityEntry, [NotNullWhen(true)] out AuditEntry? auditEntry) + { + var entityInclude = entityEntry.Metadata.GetAuditInclude(); + if (!entityInclude) + { + auditEntry = null; + return false; + } + + auditEntry = new AuditEntry(entityEntry); + + foreach (var propertyEntry in entityEntry.Properties) + { + var propertyInclude = propertyEntry.Metadata.GetAuditInclude(); + if (propertyInclude && !Constants.PropertyNames.Contains(propertyEntry.Metadata.Name)) + { + if (entityEntry.State is not EntityState.Added && Equals(propertyEntry.OriginalValue, propertyEntry.CurrentValue)) + { + continue; + } + + auditEntry.Properties.Add(new AuditPropertyEntry + { + PropertyName = propertyEntry.Metadata.Name, + OriginalValue = entityEntry.State == EntityState.Added ? null : propertyEntry.OriginalValue, + NewValue = 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 static string? GetStringValue(object? value) + { + if (value == null) return null; + + try + { + if (value is DateTime dt) + { + return dt.ToString("yyyy-MM-dd HH:mm:ss"); + } + else if (value is DateTimeOffset dto) + { + return dto.ToString("yyyy-MM-dd HH:mm:ss zzz"); + } + + var converter = TypeDescriptor.GetConverter(value.GetType()); + if (converter.CanConvertTo(typeof(string))) + { + return converter.ConvertToString(value); + } + } + catch { } + + return JsonSerializer.Serialize(value); + } + + /// + public void Dispose() + { + _entries = null; + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs new file mode 100644 index 0000000..74dacbf --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs @@ -0,0 +1,36 @@ +using Ling.Audit.EntityFrameworkCore.Internal.Extensions; +using Ling.Audit.EntityFrameworkCore.TypeConfigurations; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.Logging; + +namespace Ling.Audit.EntityFrameworkCore.Internal; + +internal sealed class AuditModelCustomizer : ModelCustomizer +{ + private readonly ILogger _logger; + + public AuditModelCustomizer( + ModelCustomizerDependencies dependencies, + ILoggerFactory loggerFactory) : base(dependencies) + { + _logger = loggerFactory.CreateLogger>(); + } + + /// + public override void Customize(ModelBuilder modelBuilder, DbContext context) + { + base.Customize(modelBuilder, context); + + var auditOptions = context.GetAuditOptions(); + + modelBuilder.ApplyConfiguration(new AuditEntityLogTypeConfiguration()); + modelBuilder.ApplyConfiguration(new AuditFieldLogTypeConfiguration()); + + modelBuilder.ConfigureAuditableEntities(auditOptions); + + modelBuilder.SetupSoftDeleteQueryFilter(); + + _logger.LogInformation("Complete the audit entity model configuration."); + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs new file mode 100644 index 0000000..996e060 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs @@ -0,0 +1,28 @@ +namespace Ling.Audit.EntityFrameworkCore.Internal; + +internal static class Constants +{ + internal const string IncludeAnnotationName = "Ling:Audit:Include"; + internal const string MetadataAnnotationName = "Ling:Audit:Metadata"; + + internal const string Id = "Id"; + internal const string CreatedAt = "CreatedAt"; + internal const string CreatedBy = "CreatedBy"; + internal const string ModifiedAt = "ModifiedAt"; + internal const string ModifiedBy = "ModifiedBy"; + internal const string IsDeleted = "IsDeleted"; + internal const string DeletedAt = "DeletedAt"; + internal const string DeletedBy = "DeletedBy"; + + internal static readonly IReadOnlyCollection PropertyNames = new[] + { + Id, + CreatedAt, + CreatedBy, + ModifiedAt, + ModifiedBy, + IsDeleted, + DeletedAt, + DeletedBy, + }; +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditConventionExtension.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditConventionExtension.cs new file mode 100644 index 0000000..90ef611 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditConventionExtension.cs @@ -0,0 +1,41 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; + +internal class AuditConventionExtension : IDbContextOptionsExtension +{ + /// + public DbContextOptionsExtensionInfo Info => new AuditConventionExtensionInfo(this); + + /// + public void ApplyServices(IServiceCollection services) + { + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + } + + /// + public void Validate(IDbContextOptions options) + { + } + + private class AuditConventionExtensionInfo : DbContextOptionsExtensionInfo + { + public override bool IsDatabaseProvider { get; } + public override string LogFragment { get; } = string.Empty; + + public AuditConventionExtensionInfo(IDbContextOptionsExtension extension) : base(extension) + { + } + + public override int GetServiceProviderHashCode() => 0; + + public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => other is AuditConventionExtensionInfo; + + public override void PopulateDebugInfo(IDictionary debugInfo) + { + } + } +} 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..22174fa --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs @@ -0,0 +1,51 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; + +namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; + +internal sealed class AuditOptionsExtension : IDbContextOptionsExtension +{ + public Action? Action { get; } + + /// + public DbContextOptionsExtensionInfo Info => new AuditOptionsExtensionInfo(this); + + public AuditOptionsExtension(Action? setupAction) + { + Action = setupAction; + } + + public AuditOptionsExtension([NotNull] AuditOptionsExtension copyFrom) + { + Action = copyFrom.Action; + } + + /// + public void ApplyServices(IServiceCollection services) + { + } + + /// + public void Validate(IDbContextOptions options) + { + } + + private class AuditOptionsExtensionInfo : DbContextOptionsExtensionInfo + { + public override bool IsDatabaseProvider { get; } + public override string LogFragment { get; } = string.Empty; + + public AuditOptionsExtensionInfo(IDbContextOptionsExtension extension) : base(extension) + { + } + + public override int GetServiceProviderHashCode() => 0; + + public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => other is AuditOptionsExtensionInfo; + + public override void PopulateDebugInfo(IDictionary debugInfo) + { + } + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ConvertExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ConvertExtensions.cs new file mode 100644 index 0000000..7c5b795 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ConvertExtensions.cs @@ -0,0 +1,46 @@ +using System.ComponentModel; + +namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; + +internal static class ConvertExtensions +{ + internal static object? ConvertToTargetType(this object? value, Type? targetType) + { + if (targetType is null || value is null) + { + return value; + } + + var underlyingType = Nullable.GetUnderlyingType(targetType) ?? targetType; + var valueType = value.GetType(); + if (valueType == targetType || valueType == underlyingType) + { + return value; + } + + try + { + if (targetType.IsPrimitive) + { + return Convert.ChangeType(value, underlyingType); + } + + var method = underlyingType.GetMethod("Parse", new Type[] { typeof(string) }); + if (method is not null) + { + return method.Invoke(null, new object?[] { value?.ToString() }); + } + + var converter = TypeDescriptor.GetConverter(underlyingType); + if (converter is not null) + { + return converter.ConvertFrom(value); + } + } + catch + { + } + + return null; + } +} 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..3d97a37 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs @@ -0,0 +1,23 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.Configuration; + +namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; + +internal static class DbContextExtensions +{ + internal static AuditOptions GetAuditOptions(this DbContext context) + { + var configuration = context.GetService(); + var options = configuration.GetSection(AuditDefaults.ConfigurationKey).Get() ?? new(); + + var extension = context.GetService() + .Extensions + .OfType() + .FirstOrDefault(); + + extension?.Action?.Invoke(options); + + return options; + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/EntityEntryExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/EntityEntryExtensions.cs new file mode 100644 index 0000000..fb2985d --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/EntityEntryExtensions.cs @@ -0,0 +1,14 @@ +using Microsoft.EntityFrameworkCore.ChangeTracking; + +namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; + +internal static class EntityEntryExtensions +{ + internal static string GetPrimaryKey(this EntityEntry entityEntry) + { + var key = entityEntry.Metadata.FindPrimaryKey(); + return key is null + ? string.Empty + : string.Join(",", key.Properties.ToDictionary(x => x.Name, x => x.PropertyInfo?.GetValue(entityEntry.Entity)).Select(x => $"{x.Key}={x.Value}")); + } +} 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..efd240c --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ReflectionExtensions.cs @@ -0,0 +1,32 @@ +namespace Ling.Audit.EntityFrameworkCore.Extensions; + +internal static class ReflectionExtensions +{ + internal static string GetFriendlyName(this Type type) + { + var friendlyName = type.Name; + if (type.IsGenericType) + { + var iBacktick = friendlyName.IndexOf('`'); + if (iBacktick > 0) + { + friendlyName = friendlyName.Remove(iBacktick); + } + friendlyName += "<"; + var typeParameters = type.GetGenericArguments(); + for (var i = 0; i < typeParameters.Length; ++i) + { + var typeParamName = typeParameters[i].GetFriendlyName(); + friendlyName += i == 0 ? typeParamName : "," + typeParamName; + } + friendlyName += ">"; + } + + return friendlyName; + } + + internal static bool IsSameTypeIgnoreNullableTo(this Type? a, Type? b) + => a is not null + && b is not null + && (Nullable.GetUnderlyingType(a) ?? a) == (Nullable.GetUnderlyingType(b) ?? b); +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/UserProviderExtension.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/UserProviderExtension.cs new file mode 100644 index 0000000..e9fa8e5 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/UserProviderExtension.cs @@ -0,0 +1,41 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; + +internal sealed class UserProviderExtension : IDbContextOptionsExtension + where TUserProvider : class, IAuditContextProvider +{ + /// + public DbContextOptionsExtensionInfo Info => new UserProviderExtensionInfo(this); + + /// + public void ApplyServices(IServiceCollection services) + { + services.TryAddScoped, TUserProvider>(); + } + + /// + public void Validate(IDbContextOptions options) + { + } + + private class UserProviderExtensionInfo : DbContextOptionsExtensionInfo + { + public override bool IsDatabaseProvider { get; } + public override string LogFragment { get; } = string.Empty; + + public UserProviderExtensionInfo(IDbContextOptionsExtension extension) : base(extension) + { + } + + public override int GetServiceProviderHashCode() => 0; + + public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => other is UserProviderExtensionInfo; + + public override void PopulateDebugInfo(IDictionary debugInfo) + { + } + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditEntry.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditEntry.cs new file mode 100644 index 0000000..15ddecc --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditEntry.cs @@ -0,0 +1,48 @@ +using Ling.Audit.EntityFrameworkCore.Internal.Extensions; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; + +namespace Ling.Audit.EntityFrameworkCore.Internal.Models; + +/// +/// Represents audit change information for an . +/// +internal sealed class AuditEntry +{ + /// + /// Gets the original . + /// + public EntityEntry EntityEntry { get; } + + public string? Schema { get; } + + public string? Table { get; } + + /// + /// Gets or sets the primary key of the . + /// + public string PrimaryKey => EntityEntry.GetPrimaryKey(); + + /// + /// Gets or sets the type of the . + /// + public string EntityType { get; set; } = default!; + + /// + /// Gets or sets the changed type of the . + /// + public AuditEventType EventType { get; set; } + + /// + /// Gets or sets all changed properties information for the . + /// + public List Properties { get; set; } = new(); + + public AuditEntry(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..58572a9 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditMetadata.cs @@ -0,0 +1,35 @@ +namespace Ling.Audit.EntityFrameworkCore.Internal.Models; + +internal sealed class AuditMetadata +{ + public EntityOperationType AllowAnonymousOperate { get; set; } + public Type? UserIdType { get; set; } + public bool HasCreatedAt { get; set; } + public bool HasCreatedBy { get; set; } + public bool HasModifiedAt { get; set; } + public bool HasModifiedBy { get; set; } + public bool HasIsDeleted { get; set; } + public bool HasDeletedAt { get; set; } + public bool HasDeletedBy { get; set; } + + public void Append(AuditMetadata other) + { + if (!ReferenceEquals(this, other)) + { + AllowAnonymousOperate |= other.AllowAnonymousOperate; + UserIdType ??= other.UserIdType; + HasCreatedAt = HasCreatedAt || other.HasCreatedAt; + HasCreatedBy = HasCreatedBy || other.HasCreatedBy; + HasModifiedAt = HasModifiedAt || other.HasModifiedAt; + HasModifiedBy = HasModifiedBy || other.HasModifiedBy; + HasIsDeleted = HasIsDeleted || other.HasIsDeleted; + HasDeletedAt = HasDeletedAt || other.HasDeletedAt; + HasDeletedBy = HasDeletedBy || other.HasDeletedBy; + } + } + + public bool IsAllowedAnonymousOperate(EntityOperationType operate) + { + return AllowAnonymousOperate.HasFlag(operate); + } +} 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..383f3a9 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditPropertyEntry.cs @@ -0,0 +1,24 @@ +using Microsoft.EntityFrameworkCore.ChangeTracking; + +namespace Ling.Audit.EntityFrameworkCore.Internal.Models; + +/// +/// Represents the property change information of the . +/// +internal sealed class AuditPropertyEntry +{ + /// + /// The property name. + /// + public string PropertyName { get; set; } = default!; + + /// + /// The original value of the property. + /// + public object? OriginalValue { get; set; } + + /// + /// The new value of the property. + /// + public object? NewValue { get; set; } +} 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..662ea3f --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj @@ -0,0 +1,33 @@ + + + + net6.0;net7.0;net8.0;net9.0 + true + $(NoWarn);IDE0130 + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs b/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs new file mode 100644 index 0000000..a81d64a --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs @@ -0,0 +1,63 @@ +using Microsoft.EntityFrameworkCore.ChangeTracking; + +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Represents the audit log for entities. +/// +public class AuditEntityChangeLog +{ + /// + /// Gets or sets the primary key. + /// + public long Id { get; set; } + + /// + /// Gets or sets the schema of database. + /// + public string? DatabaseSchema { get; set; } + + /// + /// Gets or sets the table of 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 of changed entity. + /// + public string EntityTypeName { get; set; } = default!; + + /// + /// Gets or sets the type of 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 user who change entity. + /// + public TUserId? UserId { get; set; } + + /// + /// Gets or sets the name of user who change entity. + /// + public string? UserName { get; set; } + + public string? IPAddress { get; set; } + + public string? ClientName { get; set; } + + /// + /// Gets or sets the details of this audit log. + /// + public virtual ICollection Details { get; set; } = new List(); +} 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..ac580cf --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Models/AuditFieldChangeLog.cs @@ -0,0 +1,34 @@ +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Represents the detail of . +/// +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!; + + 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.EntityFrameworkCore/TypeConfigurations/AuditEntityLogTypeConfiguration.cs b/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditEntityLogTypeConfiguration.cs new file mode 100644 index 0000000..82bd905 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditEntityLogTypeConfiguration.cs @@ -0,0 +1,68 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Ling.Audit.EntityFrameworkCore.TypeConfigurations; + +internal sealed class AuditEntityLogTypeConfiguration : IEntityTypeConfiguration> +{ + public void Configure(EntityTypeBuilder> builder) + { +#if NET7_0_OR_GREATER + builder.ToTable(AuditDefaults.EntityChangeAuditLogTableName, t => t.HasComment("A table to record entities changes.")) + .HasKey(al => al.Id); +#else + builder.ToTable(AuditDefaults.EntityChangeAuditLogTableName) + .HasComment("A table to record entities changes."); + + builder.HasKey(al => al.Id); +#endif + + builder.Property(al => al.Id) + .ValueGeneratedOnAdd() + .HasComment("The primary key."); + + builder.Property(al => al.DatabaseSchema) + .IsUnicode(false) + .HasMaxLength(64) + .HasComment("The database schema name."); + + builder.Property(al => al.TableName) + .IsUnicode(false) + .HasMaxLength(128) + .HasComment("The table name."); + + builder.Property(al => al.EntityKey) + .IsUnicode(false) + .HasMaxLength(128) + .HasComment("The primary key of changed entity."); + + builder.Property(al => al.EntityTypeName) + .IsUnicode(false) + .HasMaxLength(64) + .HasComment("The type of changed entity."); + + builder.Property(al => al.EventType) + .IsUnicode(false) + .HasMaxLength(16) + .HasConversion() + .HasComment("The type of audit event."); + + builder.Property(al => al.EventTime) + .HasComment("The time the audit event occurred."); + + builder.Property(al => al.UserId) + .IsRequired(false) + .HasComment("The identity of the user who change entity."); + + builder.Property(al => al.UserName) + .IsUnicode(true) + .HasMaxLength(512) + .IsRequired(false) + .HasComment("The name of the user who change entity."); + + builder.HasMany(al => al.Details) + .WithOne() + .HasForeignKey(ald => ald.EntityLogId) + .OnDelete(DeleteBehavior.Cascade); + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditFieldLogTypeConfiguration.cs b/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditFieldLogTypeConfiguration.cs new file mode 100644 index 0000000..db5c950 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditFieldLogTypeConfiguration.cs @@ -0,0 +1,40 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Ling.Audit.EntityFrameworkCore.TypeConfigurations; + +internal sealed class AuditFieldLogTypeConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { +#if NET7_0_OR_GREATER + builder.ToTable(AuditDefaults.EntityFieldChangeAuditLogTableName, t => t.HasComment("A table to record entity's fields changes.")) + .HasKey(al => al.Id); +#else + builder.ToTable(AuditDefaults.EntityFieldChangeAuditLogTableName) + .HasComment("A table to record entity's fields changes."); + + builder.HasKey(al => al.Id); +#endif + + builder.Property(al => al.Id) + .ValueGeneratedOnAdd() + .HasComment("The primary key."); + + builder.Property(al => al.EntityLogId) + .HasComment("The entity-change-log primary key."); + + builder.Property(al => al.FieldName) + .IsUnicode(false) + .HasMaxLength(64) + .HasComment("The property name (format: entity class name + '.' + property name)."); + + builder.Property(al => al.OriginalValue) + .IsUnicode(true) + .HasComment("The original value."); + + builder.Property(al => al.NewValue) + .IsUnicode(true) + .HasComment("The new value."); + } +} From 1ccfeceb9bb106648e25cccef40c3c2598941fc0 Mon Sep 17 00:00:00 2001 From: Jing Ling Date: Fri, 3 Jan 2025 02:01:52 +0800 Subject: [PATCH 2/9] Enhance audit functionality and improve code clarity - Updated documentation and removed `Inherited = true` in `AuditIgnoreAttribute`. - Added constructor and `AnonymousOperations` property in `AuditIncludeAttribute`. - Renamed `DisabledSwitchKey` to `DisableAuditingSwitch` in `AuditDefaults`. - Updated method parameters and added `ConfigureAuditLogTableNames` in `ModelBuilderExtensions`. - Changed audit entry type from `AuditEntry` to `AuditEntityEntry` in `AuditInterceptor`. - Introduced `AnonymousOperations` in `AuditMetadata` for better configuration. - Added `ValueType` property in `AuditEntityChangeLog` and `AuditFieldChangeLog`. - Updated table names and comments in configuration classes for clarity. - Added helper methods in `ThrowHelper` for parameter validation. - Introduced `AuditEntityEntry` class for better tracking of audit information. - Updated conventions to use new annotation names in `AuditIgnoreAttributeConvention` and `AuditIncludeAttributeConvention`. These changes aim to enhance the flexibility and configurability of the auditing features while improving code readability and maintainability. --- .../Attributes/AuditIgnoreAttribute.cs | 7 +- .../Attributes/AuditIncludeAttribute.cs | 15 +- .../AuditDefaults.cs | 24 +- .../AuditOptions.cs | 5 - .../Extensions/ModelBuilderExtensions.cs | 369 +++++++++++------- .../Internal/AuditConventionSetPlugin.cs | 10 +- .../AuditIgnoreAttributeConvention.cs | 13 +- .../AuditIncludeAttributeConvention.cs | 15 +- .../Internal/AuditInterceptor.cs | 37 +- .../Internal/AuditModelCustomizer.cs | 17 +- .../Internal/Constants.cs | 22 +- .../Extensions/AuditConventionExtension.cs | 2 +- .../Extensions/DbContextExtensions.cs | 2 +- .../Extensions/EntityEntryExtensions.cs | 13 +- .../Extensions/ReflectionExtensions.cs | 51 +-- .../{AuditEntry.cs => AuditEntityEntry.cs} | 27 +- .../Internal/Models/AuditMetadata.cs | 80 +++- .../Internal/Models/AuditPropertyEntry.cs | 19 +- .../Internal/ThrowHelper.cs | 31 ++ .../Models/AuditEntityChangeLog.cs | 19 +- .../Models/AuditFieldChangeLog.cs | 3 + .../AuditEntityLogTypeConfiguration.cs | 36 +- .../AuditFieldLogTypeConfiguration.cs | 30 +- 23 files changed, 545 insertions(+), 302 deletions(-) rename src/Ling.Audit.EntityFrameworkCore/Internal/Models/{AuditEntry.cs => AuditEntityEntry.cs} (54%) create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/ThrowHelper.cs diff --git a/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIgnoreAttribute.cs b/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIgnoreAttribute.cs index 568e7f2..64d6752 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIgnoreAttribute.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIgnoreAttribute.cs @@ -1,7 +1,10 @@ namespace Ling.Audit.EntityFrameworkCore; /// -/// Indicates that the property or field will not be audited. +/// Specifies that a property or field should be excluded from auditing in an audited entity. +/// +/// This attribute is only effective when the containing entity is marked with . +/// /// -[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class AuditIgnoreAttribute : Attribute; diff --git a/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIncludeAttribute.cs b/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIncludeAttribute.cs index c39d70b..7a8f8b3 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIncludeAttribute.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIncludeAttribute.cs @@ -1,13 +1,22 @@ namespace Ling.Audit.EntityFrameworkCore; /// -/// Indicates that the entity is automatically audited. +/// Specifies that an entity class should be included in automatic auditing. /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class AuditIncludeAttribute : Attribute { /// - /// Gets or sets the operation type that allows anonymous. + /// Initializes a new instance of the class with specified anonymous operations. /// - public EntityOperationType AllowAnonymousOperate { get; init; } = EntityOperationType.None; + /// The operations that can be performed without authentication. + public AuditIncludeAttribute(EntityOperationType anonymousOperations = EntityOperationType.None) + { + AnonymousOperations = anonymousOperations; + } + + /// + /// Gets the operations that can be performed without authentication. + /// + public EntityOperationType AnonymousOperations { get; } } diff --git a/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs b/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs index 5bafc59..f74a3a8 100644 --- a/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs +++ b/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs @@ -8,25 +8,19 @@ namespace Ling.Audit.EntityFrameworkCore; public static class AuditDefaults { /// - /// The key of the for disable auditing. Setting this value to will disable. + /// The switch to control whether auditing is disabled. + /// + /// To disable auditing: + /// + /// AppContext.SetSwitch("Ling.Audit.EntityFrameworkCore.DisableAuditing", true); + /// + /// /// - public const string DisabledSwitchKey = "Ling.DisableAudit"; + public const string DisableAuditingSwitch = "Ling.Audit.EntityFrameworkCore.DisableAuditing"; /// /// The key for the configuration. /// It will be used to get the from 's section. /// - public const string ConfigurationKey = "Audit"; - - /// - /// Table name that records entity change audit logs. - /// DO NOT change this value if migrations are added. - /// - public static string EntityChangeAuditLogTableName { get; set; } = "AuditEntityLog"; - - /// - /// The table name that records entity's fields change audit logs. - /// DO NOT change this value if migrations are added. - /// - public static string EntityFieldChangeAuditLogTableName { get; set; } = "AuditFieldLog"; + public const string ConfigurationSection = "Audit"; } diff --git a/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs b/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs index 2ed304f..ecc7286 100644 --- a/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs @@ -65,11 +65,6 @@ public class AuditOptions /// public class AuditEntityComments { - /// - /// Comment to Id property. - /// - public string Id { get; set; } = "Unique identifier, primary key."; - /// /// Comment to CreatedAt property. /// diff --git a/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs index aca52e5..1e415cf 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs @@ -1,11 +1,11 @@ -using Ling.Audit.EntityFrameworkCore.Extensions; -using Ling.Audit.EntityFrameworkCore.Internal; +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 System.Diagnostics; +using Microsoft.Extensions.Logging; using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; @@ -43,25 +43,31 @@ public static void SetupSoftDeleteQueryFilter(this ModelBuilder builder) /// 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, EntityOperationType allowAnonymousOperate = EntityOperationType.None) + public static EntityTypeBuilder IsAuditable(this EntityTypeBuilder entityTypeBuilder, EntityOperationType anonymousOperations = EntityOperationType.None) { ArgumentNullException.ThrowIfNull(entityTypeBuilder); - entityTypeBuilder.Metadata.SetAnnotation(Constants.IncludeAnnotationName, true); - entityTypeBuilder.Metadata.SetAuditMetadata(new AuditMetadata { AllowAnonymousOperate = allowAnonymousOperate }); + 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, EntityOperationType allowAnonymousOperate = EntityOperationType.None) + public static EntityTypeBuilder IsAuditable(this EntityTypeBuilder entityTypeBuilder, EntityOperationType anonymousOperations = EntityOperationType.None) where TEntity : class - => (EntityTypeBuilder)((EntityTypeBuilder)entityTypeBuilder).IsAuditable(allowAnonymousOperate); + { + EntityTypeBuilder builder = entityTypeBuilder; + + builder.IsAuditable(anonymousOperations); + + return entityTypeBuilder; + } /// /// Configures whether to apply auditing to the column. @@ -73,14 +79,58 @@ public static PropertyBuilder IsAuditable(this PropertyBuilder propertyBuilder, { ArgumentNullException.ThrowIfNull(propertyBuilder); - propertyBuilder.Metadata.SetAnnotation(Constants.IncludeAnnotationName, enabled); + propertyBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, enabled); return propertyBuilder; } /// /// The type of the property being configured. public static PropertyBuilder IsAuditable(this PropertyBuilder propertyBuilder, bool enabled = false) - => (PropertyBuilder)((PropertyBuilder)propertyBuilder).IsAuditable(enabled); + { + PropertyBuilder builder = propertyBuilder; + + builder.IsAuditable(enabled); + + 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 @@ -99,102 +149,92 @@ public static PropertyBuilder IsAuditable(this PropertyBui /// 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 Type? ConfigureAuditableEntities(this ModelBuilder builder, AuditOptions options) + internal static Type? ConfigureAuditableEntities(this ModelBuilder builder, AuditOptions options, ILogger logger) { + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(options); + Type? userIdType = options.UserIdType; - Type? entityClrType = null; + logger.LogInformation("Starting to configure auditable entities. Initial user ID type: {UserIdType}", + userIdType?.GetFriendlyName() ?? "null"); + foreach (var entityType in builder.Model.GetEntityTypes()) { - var type = entityType.ClrType; - var auditMetadata = entityType.GetAuditMetadata(); + var metadata = new AuditMetadata(); + var entityClrType = entityType.ClrType; + var entityName = entityClrType.GetFriendlyName(); - if (entityType.HasProperty(Constants.Id, out var propertyType)) + logger.LogDebug("Configuring audit properties for entity: {EntityName}", entityName); + + // Configure creation audit properties + if (entityType.HasProperty(Constants.CreatedAt, out var createdAtType)) { - builder.Entity(type) - .Property(propertyType, Constants.Id) - .HasColumnOrder(0) - .HasComment(options.Comments.Id); + ValidatePropertyType(entityClrType, Constants.CreatedAt, createdAtType, typeof(DateTimeOffset)); + ConfigureProperty(builder, entityClrType, createdAtType, Constants.CreatedAt, 991, options.Comments.CreatedAt); + metadata.HasCreatedAt = true; } - if (entityType.HasProperty(Constants.CreatedAt, out propertyType)) + if (entityType.HasProperty(Constants.CreatedBy, out var createdByType)) { - builder.Entity(type) - .Property(propertyType, Constants.CreatedAt) - .HasColumnOrder(991) - .HasComment(options.Comments.CreatedAt); - - CheckDateTimeOffset(type, Constants.CreatedAt, propertyType); - auditMetadata.HasCreatedAt = true; + ValidateAndUpdateUserIdType(entityClrType, Constants.CreatedBy, createdByType, ref userIdType); + ConfigureProperty(builder, entityClrType, createdByType, Constants.CreatedBy, 992, options.Comments.CreatedBy); + metadata.HasCreatedBy = true; + metadata.UserIdType = createdByType; } - if (entityType.HasProperty(Constants.CreatedBy, out var cUserIdType)) + + // Configure modification audit properties + if (entityType.HasProperty(Constants.ModifiedAt, out var modifiedAtType)) { - builder.Entity(type) - .Property(cUserIdType, Constants.CreatedBy) - .HasColumnOrder(992) - .HasComment(options.Comments.CreatedBy); - - CheckAndAssign(ref entityClrType, ref userIdType, type, cUserIdType); - auditMetadata.UserIdType = cUserIdType; - auditMetadata.HasCreatedBy = true; + ValidatePropertyType(entityClrType, Constants.ModifiedAt, modifiedAtType, typeof(DateTimeOffset?)); + ConfigureProperty(builder, entityClrType, modifiedAtType, Constants.ModifiedAt, 994, options.Comments.ModifiedAt); + metadata.HasModifiedAt = true; } - if (entityType.HasProperty(Constants.ModifiedAt, out propertyType)) + if (entityType.HasProperty(Constants.ModifiedBy, out var modifiedByType)) { - builder.Entity(type) - .Property(propertyType, Constants.ModifiedAt) - .HasColumnOrder(994) - .HasComment(options.Comments.ModifiedAt); - - CheckDateTimeOffset(type, Constants.ModifiedAt, propertyType); - auditMetadata.HasModifiedAt = true; + ValidateAndUpdateUserIdType(entityClrType, Constants.ModifiedBy, modifiedByType, ref userIdType); + ConfigureProperty(builder, entityClrType, modifiedByType, Constants.ModifiedBy, 995, options.Comments.ModifiedBy); + metadata.HasModifiedBy = true; + metadata.UserIdType = modifiedByType; } - if (entityType.HasProperty(Constants.ModifiedBy, out var mUserIdType)) + + // Configure deletion audit properties + if (entityType.HasProperty(Constants.IsDeleted, out var isDeletedType)) { - builder.Entity(type) - .Property(mUserIdType, Constants.ModifiedBy) - .HasColumnOrder(995) - .HasComment(options.Comments.ModifiedBy); - - CheckAndAssign(ref entityClrType, ref userIdType, type, mUserIdType); - auditMetadata.UserIdType = mUserIdType; - auditMetadata.HasModifiedBy = true; + ValidatePropertyType(entityClrType, Constants.IsDeleted, isDeletedType, typeof(bool)); + ConfigureProperty(builder, entityClrType, isDeletedType, Constants.IsDeleted, 997, options.Comments.IsDeleted); + metadata.HasIsDeleted = true; } - if (entityType.HasProperty(Constants.IsDeleted, out propertyType)) + if (entityType.HasProperty(Constants.DeletedAt, out var deletedAtType)) { - builder.Entity(type) - .Property(propertyType, Constants.IsDeleted) - .HasColumnOrder(997) - .HasComment(options.Comments.IsDeleted); - - CheckBoolean(type, Constants.IsDeleted, propertyType); - auditMetadata.HasIsDeleted = true; + ValidatePropertyType(entityClrType, Constants.DeletedAt, deletedAtType, typeof(DateTimeOffset?)); + ConfigureProperty(builder, entityClrType, deletedAtType, Constants.DeletedAt, 998, options.Comments.DeletedAt); + metadata.HasDeletedAt = true; } - if (entityType.HasProperty(Constants.DeletedAt, out propertyType)) - { - builder.Entity(type) - .Property(propertyType, Constants.DeletedAt) - .HasColumnOrder(998) - .HasComment(options.Comments.DeletedAt); - CheckDateTimeOffset(type, Constants.DeletedAt, propertyType); - auditMetadata.HasDeletedAt = true; - } - if (entityType.HasProperty(Constants.DeletedBy, out var dUserIdType)) + if (entityType.HasProperty(Constants.DeletedBy, out var deletedByType)) { - builder.Entity(type) - .Property(dUserIdType, Constants.DeletedBy) - .HasColumnOrder(999) - .HasComment(options.Comments.DeletedBy); - - CheckAndAssign(ref entityClrType, ref userIdType, type, dUserIdType); - auditMetadata.UserIdType = dUserIdType; - auditMetadata.HasDeletedBy = true; + ValidateAndUpdateUserIdType(entityClrType, Constants.DeletedBy, deletedByType, ref userIdType); + ConfigureProperty(builder, entityClrType, deletedByType, Constants.DeletedBy, 999, options.Comments.DeletedBy); + metadata.HasDeletedBy = true; + metadata.UserIdType = deletedByType; } - entityType.SetAuditMetadata(auditMetadata); + 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) @@ -202,27 +242,22 @@ public static PropertyBuilder IsAuditable(this PropertyBui if (EF.IsDesignTime) #endif { - Debug.WriteLine("Currently running in design time."); + logger.LogDebug("Running in design time, removing audit metadata for entity {EntityName}", entityName); entityType.RemoveAnnotation(Constants.MetadataAnnotationName); } } - return userIdType; - } - - internal static bool GetAuditInclude(this IReadOnlyAnnotatable annotatable) - { - ArgumentNullException.ThrowIfNull(annotatable); + logger.LogInformation("Completed configuring auditable entities. Final user ID type: {UserIdType}", + userIdType?.GetFriendlyName() ?? "null"); - var value = annotatable.FindAnnotation(Constants.IncludeAnnotationName)?.Value; - return annotatable switch - { - IEntityType => value is not null && (bool)value, // Entity auditable defaults to false - IProperty => value is null || (bool)value, // Entity property or field auditable defaults to true - _ => throw new InvalidOperationException() - }; + return userIdType; } + /// + /// 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); @@ -230,8 +265,7 @@ internal static void SetAuditMetadata(this IMutableEntityType entityType, AuditM if (entityType.FindAnnotation(Constants.MetadataAnnotationName)?.Value is AuditMetadata original) { - original.Append(metadata); - entityType.SetAnnotation(Constants.MetadataAnnotationName, original); + entityType.SetAnnotation(Constants.MetadataAnnotationName, original | metadata); } else { @@ -239,6 +273,11 @@ internal static void SetAuditMetadata(this IMutableEntityType entityType, AuditM } } + /// + /// 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); @@ -248,69 +287,111 @@ internal static AuditMetadata GetAuditMetadata(this IReadOnlyAnnotatable entityT : new AuditMetadata(); } + /// + /// Gets whether auditing is included for the specified annotatable. + /// + /// The annotatable to check. + /// if auditing is included; otherwise, . + internal static bool GetAuditInclude(this IReadOnlyAnnotatable annotatable) + { + ArgumentNullException.ThrowIfNull(annotatable); + + var value = annotatable.FindAnnotation(Constants.AuditableAnnotationName)?.Value; + return annotatable switch + { + IEntityType => value is true, // Entity auditable defaults to false + IProperty => value is false, // Entity property or field auditable defaults to true + _ => throw new InvalidOperationException() + }; + } + #endregion Internal Methods #region Private Methods - private static void CheckAndAssign(ref Type? entityType, ref Type? userIdType, Type currentEntityType, Type currenTUserIdtype) + /// + /// 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) { - if (userIdType is null) - { - entityType = currentEntityType; - userIdType = currenTUserIdtype; - } - else if (userIdType != currenTUserIdtype) - { - const string msg = "All audit entities in the same 'DbContext' cannot have different user's identity types."; - var desc = entityType == currentEntityType - ? string.Format( - "Entity type '{0}' has both type '{1}' and type '{2}' as user's identity type.", - currentEntityType.GetFriendlyName(), - userIdType.GetFriendlyName(), - currenTUserIdtype.GetFriendlyName()) - : string.Format( - "Entity type '{0}' has type '{1}' as user key type but entity '{2}' has type '{3}' as user's identity type.", - entityType!.GetFriendlyName(), - userIdType.GetFriendlyName(), - currentEntityType.GetFriendlyName(), - currenTUserIdtype.GetFriendlyName()); - throw new InvalidOperationException($"{msg} {desc}"); - } + return entityType.FindProperty(propertyName) is not null; } - private static void CheckDateTimeOffset(Type currentEntityType, string propertyName, Type propertyType) + /// + /// 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) { - if (!propertyType.IsAssignableFrom(typeof(DateTimeOffset))) - { - throw new InvalidOperationException(string.Format( - "Type '{2}' of member '{1}' in entity type '{0}' is neither 'DateTimeOffset' nor 'DateTimeOffset?'.", - currentEntityType.GetFriendlyName(), - propertyName, - propertyType.GetFriendlyName())); - } + type = entityType.FindProperty(propertyName)?.ClrType; + return type is not null; } - private static void CheckBoolean(Type currentEntityType, string propertyName, Type propertyType) + /// + /// 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) { - if (!propertyType.IsAssignableFrom(typeof(bool))) - { - throw new InvalidOperationException(string.Format( - "Type '{2}' of member '{1}' in entity type '{0}' is not 'bool'.", - currentEntityType.GetFriendlyName(), - propertyName, - propertyType.GetFriendlyName())); - } + builder.Entity(entityType) + .Property(propertyType, propertyName) + .HasColumnOrder(columnOrder) + .HasComment(comment); } - private static bool HasProperty(this IMutableEntityType entityType, string propertyName) + /// + /// 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) { - return entityType.FindProperty(propertyName) is not null; + if (!propertyType.IsAssignableTo(targetType)) + { + throw new InvalidOperationException( + $"Property '{propertyName}' in entity '{entityClrType.GetFriendlyName()}' must be of type {targetType.Name}"); + } } - private static bool HasProperty(this IMutableEntityType entityType, string propertyName, [NotNullWhen(true)] out Type? type) + /// + /// 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, ref Type? userIdType) { - type = entityType.FindProperty(propertyName)?.ClrType; - return type is not null; + if (userIdType is null) + { + userIdType = propertyType; + } + else 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/Internal/AuditConventionSetPlugin.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs index 6d439b8..f3f5ee9 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs @@ -3,15 +3,23 @@ namespace Ling.Audit.EntityFrameworkCore.Internal; -internal class AuditConventionSetPlugin : IConventionSetPlugin +/// +/// 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)); diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIgnoreAttributeConvention.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIgnoreAttributeConvention.cs index 2f5d7c4..f500523 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIgnoreAttributeConvention.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIgnoreAttributeConvention.cs @@ -5,18 +5,27 @@ namespace Ling.Audit.EntityFrameworkCore.Internal; +/// +/// Convention to process on properties and fields. +/// internal sealed class AuditIgnoreAttributeConvention : PropertyAttributeConventionBase { - public AuditIgnoreAttributeConvention(ProviderConventionSetBuilderDependencies dependencies) : base(dependencies) + /// + /// 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, AuditIgnoreAttribute attribute, MemberInfo clrMember, IConventionContext context) { - propertyBuilder.Metadata.SetAnnotation(Constants.IncludeAnnotationName, false); + propertyBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, false); } } diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIncludeAttributeConvention.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIncludeAttributeConvention.cs index e95dc72..fc67f97 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIncludeAttributeConvention.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIncludeAttributeConvention.cs @@ -4,22 +4,31 @@ namespace Ling.Audit.EntityFrameworkCore.Internal; -internal class AuditIncludeAttributeConvention : +/// +/// Convention to process on entity types. +/// +internal sealed class AuditIncludeAttributeConvention : #if NET8_0_OR_GREATER TypeAttributeConventionBase #else EntityTypeAttributeConventionBase #endif { - public AuditIncludeAttributeConvention(ProviderConventionSetBuilderDependencies dependencies) : base(dependencies) + /// + /// 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, AuditIncludeAttribute attribute, IConventionContext context) { - entityTypeBuilder.Metadata.SetAnnotation(Constants.IncludeAnnotationName, true); + entityTypeBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, true); } } diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs index 4f553f8..8fafb1c 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs @@ -1,5 +1,4 @@ -using Ling.Audit.EntityFrameworkCore.Extensions; -using Ling.Audit.EntityFrameworkCore.Internal.Extensions; +using Ling.Audit.EntityFrameworkCore.Internal.Extensions; using Ling.Audit.EntityFrameworkCore.Internal.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -14,7 +13,7 @@ namespace Ling.Audit.EntityFrameworkCore.Internal; internal sealed class AuditInterceptor : SaveChangesInterceptor, IDisposable { - private IReadOnlyList? _entries; + private IReadOnlyList? _entries; /// public override InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) @@ -67,7 +66,7 @@ internal void InternalSavingChanges(DbContextEventData eventData) var userProvider = context.GetService>(); var logger = context.GetService().CreateLogger(GetType()); var options = context.GetAuditOptions(); - var entries = new List(); + var entries = new List(); var now = DateTimeOffset.Now; var isUserIdDefaultValue = EqualityComparer.Default.Equals(userProvider.Id, default); @@ -78,15 +77,6 @@ internal void InternalSavingChanges(DbContextEventData eventData) var eventType = AuditEventType.None; var userId = isUserIdDefaultValue ? null : userProvider.Id.ConvertToTargetType(metadata.UserIdType); - if (typeof(TUserId).IsSameTypeIgnoreNullableTo(metadata.UserIdType)) - { - logger.LogError( - "The type of 'TUserId' configured is '{UserIdType}', but entity's user key type is '{entityType}'.", - typeof(TUserId), - metadata.UserIdType); - throw new InvalidOperationException($"The type of 'TUserId' configured is not match entity [{entityType}]."); - } - switch (entityEntry.State) { case EntityState.Deleted: @@ -98,7 +88,7 @@ internal void InternalSavingChanges(DbContextEventData eventData) if (metadata.HasDeletedBy) { if (!options.AllowAnonymousDelete && - !metadata.IsAllowedAnonymousOperate(EntityOperationType.Delete) && + !metadata.AllowsAnonymousOperation(EntityOperationType.Delete) && isUserIdDefaultValue) { logger.LogError("Not allowed to delete entity '{entityType}' with anonymous user.", entityType); @@ -127,7 +117,7 @@ internal void InternalSavingChanges(DbContextEventData eventData) if (metadata.HasModifiedBy) { if (!options.AllowAnonymousModify && - !metadata.IsAllowedAnonymousOperate(EntityOperationType.Update) && + !metadata.AllowsAnonymousOperation(EntityOperationType.Update) && isUserIdDefaultValue) { logger.LogError("Not allowed to modify entity '{entityType}' with anonymous user.", entityType); @@ -147,7 +137,7 @@ internal void InternalSavingChanges(DbContextEventData eventData) if (metadata.HasCreatedBy) { if (!options.AllowAnonymousCreate && - !metadata.IsAllowedAnonymousOperate(EntityOperationType.Create) && + !metadata.AllowsAnonymousOperation(EntityOperationType.Create) && isUserIdDefaultValue) { logger.LogError("Not allowed to create entity '{entityType}' with anonymous user.", entityType); @@ -171,7 +161,7 @@ internal void InternalSavingChanges(DbContextEventData eventData) } } - if (!AppContext.TryGetSwitch(AuditDefaults.DisabledSwitchKey, out var disabled) || !disabled) + if (!AppContext.TryGetSwitch(AuditDefaults.DisableAuditingSwitch, out var disabled) || !disabled) { _entries = entries; } @@ -181,7 +171,7 @@ internal int InternalSavedChanges(SaveChangesCompletedEventData eventData) { var context = eventData.Context; - if (context is null || (AppContext.TryGetSwitch(AuditDefaults.DisabledSwitchKey, out var disabled) && disabled)) return 0; + if (context is null || (AppContext.TryGetSwitch(AuditDefaults.DisableAuditingSwitch, out var disabled) && disabled)) return 0; var options = context.GetAuditOptions(); var logger = context.GetService().CreateLogger(GetType()); @@ -203,11 +193,14 @@ internal int InternalSavedChanges(SaveChangesCompletedEventData eventData) EventTime = DateTimeOffset.Now, UserId = userProvider.Id, UserName = userProvider.Name, + IPAddress = userProvider.IPAddress, + ClientName = userProvider.ClientName, Details = i.Properties.ConvertAll(j => new AuditFieldChangeLog { - FieldName = i.EntityType + '.' + j.PropertyName, + FieldName = i.EntityType + '.' + j.Name, OriginalValue = GetStringValue(j.OriginalValue), NewValue = GetStringValue(j.NewValue), + ValueType = j.ValueType, }), }) .ToList(); @@ -232,7 +225,7 @@ internal int InternalSavedChanges(SaveChangesCompletedEventData eventData) return entityChangedCount + fieldChangedCount; } - private static bool TryGetAuditEntry(EntityEntry entityEntry, [NotNullWhen(true)] out AuditEntry? auditEntry) + private static bool TryGetAuditEntry(EntityEntry entityEntry, [NotNullWhen(true)] out AuditEntityEntry? auditEntry) { var entityInclude = entityEntry.Metadata.GetAuditInclude(); if (!entityInclude) @@ -241,7 +234,7 @@ private static bool TryGetAuditEntry(EntityEntry entityEntry, [NotNullWhen(true) return false; } - auditEntry = new AuditEntry(entityEntry); + auditEntry = new AuditEntityEntry(entityEntry); foreach (var propertyEntry in entityEntry.Properties) { @@ -255,7 +248,7 @@ private static bool TryGetAuditEntry(EntityEntry entityEntry, [NotNullWhen(true) auditEntry.Properties.Add(new AuditPropertyEntry { - PropertyName = propertyEntry.Metadata.Name, + Name = propertyEntry.Metadata.Name, OriginalValue = entityEntry.State == EntityState.Added ? null : propertyEntry.OriginalValue, NewValue = propertyEntry.CurrentValue }); diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs index 74dacbf..8de1fdc 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs @@ -6,10 +6,19 @@ 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) @@ -20,14 +29,14 @@ public AuditModelCustomizer( /// 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.ApplyConfiguration(new AuditEntityLogTypeConfiguration()); - modelBuilder.ApplyConfiguration(new AuditFieldLogTypeConfiguration()); - - modelBuilder.ConfigureAuditableEntities(auditOptions); + modelBuilder.ConfigureAuditableEntities(auditOptions, _logger); modelBuilder.SetupSoftDeleteQueryFilter(); diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs index 996e060..0db1291 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs @@ -2,20 +2,20 @@ internal static class Constants { - internal const string IncludeAnnotationName = "Ling:Audit:Include"; + internal const string AuditableAnnotationName = "Ling:Audit:Auditable"; internal const string MetadataAnnotationName = "Ling:Audit:Metadata"; internal const string Id = "Id"; - internal const string CreatedAt = "CreatedAt"; - internal const string CreatedBy = "CreatedBy"; - internal const string ModifiedAt = "ModifiedAt"; - internal const string ModifiedBy = "ModifiedBy"; - internal const string IsDeleted = "IsDeleted"; - internal const string DeletedAt = "DeletedAt"; - internal const string DeletedBy = "DeletedBy"; + internal const string CreatedAt = nameof(IHasCreationTime.CreatedAt); + internal const string CreatedBy = nameof(IHasCreator.CreatedBy); + internal const string ModifiedAt = nameof(IHasModificationTime.LastModifiedAt); + internal const string ModifiedBy = nameof(IHasModifier.LastModifiedBy); + internal const string IsDeleted = nameof(ISoftDelete.IsDeleted); + internal const string DeletedAt = nameof(IHasDeletionTime.DeletedAt); + internal const string DeletedBy = nameof(IHasDeleter.DeletedBy); - internal static readonly IReadOnlyCollection PropertyNames = new[] - { + internal static readonly IReadOnlyCollection PropertyNames = + [ Id, CreatedAt, CreatedBy, @@ -24,5 +24,5 @@ internal static class Constants IsDeleted, DeletedAt, DeletedBy, - }; + ]; } diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditConventionExtension.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditConventionExtension.cs index 90ef611..75ed0c9 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditConventionExtension.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditConventionExtension.cs @@ -5,7 +5,7 @@ namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; -internal class AuditConventionExtension : IDbContextOptionsExtension +internal sealed class AuditConventionExtension : IDbContextOptionsExtension { /// public DbContextOptionsExtensionInfo Info => new AuditConventionExtensionInfo(this); diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs index 3d97a37..792adde 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs @@ -9,7 +9,7 @@ internal static class DbContextExtensions internal static AuditOptions GetAuditOptions(this DbContext context) { var configuration = context.GetService(); - var options = configuration.GetSection(AuditDefaults.ConfigurationKey).Get() ?? new(); + var options = configuration.GetSection(AuditDefaults.ConfigurationSection).Get() ?? new(); var extension = context.GetService() .Extensions diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/EntityEntryExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/EntityEntryExtensions.cs index fb2985d..9c81a09 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/EntityEntryExtensions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/EntityEntryExtensions.cs @@ -2,13 +2,24 @@ namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; +/// +/// Extension methods for . +/// internal static class EntityEntryExtensions { + /// + /// 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) { + ArgumentNullException.ThrowIfNull(entityEntry); + var key = entityEntry.Metadata.FindPrimaryKey(); return key is null ? string.Empty - : string.Join(",", key.Properties.ToDictionary(x => x.Name, x => x.PropertyInfo?.GetValue(entityEntry.Entity)).Select(x => $"{x.Key}={x.Value}")); + : string.Join(",", key.Properties.Select(p => $"{p.Name}={p.PropertyInfo?.GetValue(entityEntry.Entity)}")); } } diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ReflectionExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ReflectionExtensions.cs index efd240c..69fffbf 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ReflectionExtensions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ReflectionExtensions.cs @@ -1,32 +1,39 @@ -namespace Ling.Audit.EntityFrameworkCore.Extensions; +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) { - var friendlyName = type.Name; - if (type.IsGenericType) + ArgumentNullException.ThrowIfNull(type); + + if (!type.IsGenericType) { - var iBacktick = friendlyName.IndexOf('`'); - if (iBacktick > 0) - { - friendlyName = friendlyName.Remove(iBacktick); - } - friendlyName += "<"; - var typeParameters = type.GetGenericArguments(); - for (var i = 0; i < typeParameters.Length; ++i) - { - var typeParamName = typeParameters[i].GetFriendlyName(); - friendlyName += i == 0 ? typeParamName : "," + typeParamName; - } - friendlyName += ">"; + return type.Name; } - return friendlyName; - } + var builder = new StringBuilder(); + var nameParts = type.Name.Split('`'); + builder.Append(nameParts[0]); - internal static bool IsSameTypeIgnoreNullableTo(this Type? a, Type? b) - => a is not null - && b is not null - && (Nullable.GetUnderlyingType(a) ?? a) == (Nullable.GetUnderlyingType(b) ?? b); + 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/AuditEntry.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditEntityEntry.cs similarity index 54% rename from src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditEntry.cs rename to src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditEntityEntry.cs index 15ddecc..99d1c53 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditEntry.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditEntityEntry.cs @@ -5,40 +5,51 @@ namespace Ling.Audit.EntityFrameworkCore.Internal.Models; /// -/// Represents audit change information for an . +/// Represents an entity entry for auditing purposes, containing temporary tracking information +/// before and during the save operation. /// -internal sealed class AuditEntry +internal sealed class AuditEntityEntry { /// - /// Gets the original . + /// 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 or sets the primary key of the . + /// Gets the primary key value of the entity. /// public string PrimaryKey => EntityEntry.GetPrimaryKey(); /// - /// Gets or sets the type of the . + /// Gets or sets the entity type name. /// public string EntityType { get; set; } = default!; /// - /// Gets or sets the changed type of the . + /// Gets or sets the type of change event. /// public AuditEventType EventType { get; set; } /// - /// Gets or sets all changed properties information for the . + /// Gets or sets the collection of property changes. /// public List Properties { get; set; } = new(); - public AuditEntry(EntityEntry entry) + /// + /// Initializes a new instance of the class. + /// + /// The entity entry being audited. + public AuditEntityEntry(EntityEntry entry) { EntityEntry = entry; Schema = entry.Metadata.GetSchema(); diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditMetadata.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditMetadata.cs index 58572a9..2e91ac3 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditMetadata.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditMetadata.cs @@ -1,35 +1,75 @@ namespace Ling.Audit.EntityFrameworkCore.Internal.Models; +/// +/// Represents audit metadata for an entity type. +/// internal sealed class AuditMetadata { - public EntityOperationType AllowAnonymousOperate { get; set; } + /// + /// Gets or sets the operations that can be performed anonymously. + /// + public EntityOperationType 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; } - public void Append(AuditMetadata other) - { - if (!ReferenceEquals(this, other)) - { - AllowAnonymousOperate |= other.AllowAnonymousOperate; - UserIdType ??= other.UserIdType; - HasCreatedAt = HasCreatedAt || other.HasCreatedAt; - HasCreatedBy = HasCreatedBy || other.HasCreatedBy; - HasModifiedAt = HasModifiedAt || other.HasModifiedAt; - HasModifiedBy = HasModifiedBy || other.HasModifiedBy; - HasIsDeleted = HasIsDeleted || other.HasIsDeleted; - HasDeletedAt = HasDeletedAt || other.HasDeletedAt; - HasDeletedBy = HasDeletedBy || other.HasDeletedBy; - } - } - - public bool IsAllowedAnonymousOperate(EntityOperationType operate) + /// + /// Determines whether the specified operation can be performed anonymously. + /// + /// The operation to check. + /// if the operation can be performed anonymously; otherwise, . + public bool AllowsAnonymousOperation(EntityOperationType operate) => AnonymousOperations.HasFlag(operate); + + /// + /// Combines two instances using the bitwise OR operator. + /// + public static AuditMetadata operator |(AuditMetadata left, AuditMetadata right) => new() { - return AllowAnonymousOperate.HasFlag(operate); - } + 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 index 383f3a9..dc3ef45 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditPropertyEntry.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditPropertyEntry.cs @@ -1,24 +1,27 @@ -using Microsoft.EntityFrameworkCore.ChangeTracking; - -namespace Ling.Audit.EntityFrameworkCore.Internal.Models; +namespace Ling.Audit.EntityFrameworkCore.Internal.Models; /// -/// Represents the property change information of the . +/// Represents temporary tracking information for a property change during auditing. /// internal sealed class AuditPropertyEntry { /// - /// The property name. + /// Gets or sets the property name. /// - public string PropertyName { get; set; } = default!; + public string Name { get; set; } = default!; /// - /// The original value of the property. + /// Gets or sets the original value before change. /// public object? OriginalValue { get; set; } /// - /// The new value of the property. + /// Gets or sets the new value after change. /// public object? NewValue { get; set; } + + /// + /// Gets or sets the type of the property value. + /// + public string 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/Models/AuditEntityChangeLog.cs b/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs index a81d64a..90fa7e7 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs @@ -5,6 +5,7 @@ namespace Ling.Audit.EntityFrameworkCore; /// /// Represents the audit log for entities. /// +/// The type of the user ID. public class AuditEntityChangeLog { /// @@ -13,12 +14,12 @@ public class AuditEntityChangeLog public long Id { get; set; } /// - /// Gets or sets the schema of database. + /// Gets or sets the schema of the database. /// public string? DatabaseSchema { get; set; } /// - /// Gets or sets the table of data changed. + /// Gets or sets the table name of the data changed. /// public string? TableName { get; set; } @@ -28,12 +29,12 @@ public class AuditEntityChangeLog public string EntityKey { get; set; } = default!; /// - /// Gets or sets the type of changed entity. + /// Gets or sets the type name of the changed entity. /// public string EntityTypeName { get; set; } = default!; /// - /// Gets or sets the type of audit event. + /// Gets or sets the type of the audit event. /// public AuditEventType EventType { get; set; } @@ -43,17 +44,23 @@ public class AuditEntityChangeLog public DateTimeOffset EventTime { get; set; } /// - /// Gets or sets the identity of user who change entity. + /// Gets or sets the identity of the user who changed the entity. /// public TUserId? UserId { get; set; } /// - /// Gets or sets the name of user who change entity. + /// 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; } /// diff --git a/src/Ling.Audit.EntityFrameworkCore/Models/AuditFieldChangeLog.cs b/src/Ling.Audit.EntityFrameworkCore/Models/AuditFieldChangeLog.cs index ac580cf..c8fce38 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Models/AuditFieldChangeLog.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Models/AuditFieldChangeLog.cs @@ -20,6 +20,9 @@ public class AuditFieldChangeLog /// public string FieldName { get; set; } = default!; + /// + /// Gets or sets the type of the value. + /// public string ValueType { get; set; } = default!; /// diff --git a/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditEntityLogTypeConfiguration.cs b/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditEntityLogTypeConfiguration.cs index 82bd905..a92ef5f 100644 --- a/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditEntityLogTypeConfiguration.cs +++ b/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditEntityLogTypeConfiguration.cs @@ -3,62 +3,70 @@ namespace Ling.Audit.EntityFrameworkCore.TypeConfigurations; +/// +/// Configures the entity type. +/// +/// The type of the user ID. internal 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(AuditDefaults.EntityChangeAuditLogTableName, t => t.HasComment("A table to record entities changes.")) + builder.ToTable(nameof(AuditEntityChangeLog), t => t.HasComment("Table to record changes in entities.")) .HasKey(al => al.Id); #else - builder.ToTable(AuditDefaults.EntityChangeAuditLogTableName) - .HasComment("A table to record entities changes."); + builder.ToTable(nameof(AuditEntityChangeLog)) + .HasComment("Table to record changes in entities."); builder.HasKey(al => al.Id); #endif builder.Property(al => al.Id) .ValueGeneratedOnAdd() - .HasComment("The primary key."); + .HasComment("Primary key."); builder.Property(al => al.DatabaseSchema) .IsUnicode(false) .HasMaxLength(64) - .HasComment("The database schema name."); + .HasComment("Database schema name."); builder.Property(al => al.TableName) .IsUnicode(false) .HasMaxLength(128) - .HasComment("The table name."); + .HasComment("Table name."); builder.Property(al => al.EntityKey) .IsUnicode(false) - .HasMaxLength(128) - .HasComment("The primary key of changed entity."); + .HasMaxLength(512) + .HasComment("Primary key of the changed entity."); builder.Property(al => al.EntityTypeName) .IsUnicode(false) .HasMaxLength(64) - .HasComment("The type of changed entity."); + .HasComment("Type of the changed entity."); builder.Property(al => al.EventType) .IsUnicode(false) .HasMaxLength(16) .HasConversion() - .HasComment("The type of audit event."); + .HasComment("Type of the audit event."); builder.Property(al => al.EventTime) - .HasComment("The time the audit event occurred."); + .HasComment("Time the audit event occurred."); builder.Property(al => al.UserId) .IsRequired(false) - .HasComment("The identity of the user who change entity."); + .HasComment("Identity of the user who changed the entity."); builder.Property(al => al.UserName) .IsUnicode(true) - .HasMaxLength(512) + .HasMaxLength(256) .IsRequired(false) - .HasComment("The name of the user who change entity."); + .HasComment("Name of the user who changed the entity."); builder.HasMany(al => al.Details) .WithOne() diff --git a/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditFieldLogTypeConfiguration.cs b/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditFieldLogTypeConfiguration.cs index db5c950..99eb6c9 100644 --- a/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditFieldLogTypeConfiguration.cs +++ b/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditFieldLogTypeConfiguration.cs @@ -3,38 +3,50 @@ namespace Ling.Audit.EntityFrameworkCore.TypeConfigurations; +/// +/// Configures the entity type. +/// internal 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(AuditDefaults.EntityFieldChangeAuditLogTableName, t => t.HasComment("A table to record entity's fields changes.")) + builder.ToTable(nameof(AuditFieldChangeLog), t => t.HasComment("Table to record changes in entity fields.")) .HasKey(al => al.Id); #else - builder.ToTable(AuditDefaults.EntityFieldChangeAuditLogTableName) - .HasComment("A table to record entity's fields changes."); + 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("The primary key."); + .HasComment("Primary key."); builder.Property(al => al.EntityLogId) - .HasComment("The entity-change-log primary key."); + .HasComment("Primary key of the associated entity change log."); builder.Property(al => al.FieldName) .IsUnicode(false) - .HasMaxLength(64) - .HasComment("The property name (format: entity class name + '.' + property name)."); + .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("The original value."); + .HasComment("Original value of the field."); builder.Property(al => al.NewValue) .IsUnicode(true) - .HasComment("The new value."); + .HasComment("New value of the field."); } } From d048de0f0855bf98bb942df148436b81016e75f3 Mon Sep 17 00:00:00 2001 From: Jing Ling Date: Sun, 5 Jan 2025 01:36:02 +0800 Subject: [PATCH 3/9] Add git project and enhance MustNull attribute analysis - Enhanced `MustNullAttributeAnalyzer` to analyze `InvocationExpressionSyntax` and method type parameters. - Changed `MustNullAttribute` access modifier to `internal`. - Added multiple test cases in `MustNullAttributeAnalyzerTests` to validate `MustNull` behavior in generic methods. - Updated test project names. - Modified `CSharpSourceGeneratorVerifier` to use regex for newline handling. --- Ling.Audit.sln | 7 + .../Analyzers/MustNullAttributeAnalyzer.cs | 118 +++++++-- src/Ling.Audit/Assembly.cs | 3 - src/Ling.Audit/Ling.Audit.csproj | 6 + src/Ling.Audit/MustNullAttribute.cs | 2 +- .../MustNullAttributeAnalyzerTests.cs | 226 +++++++++++++++--- .../Verifiers/CSharpAnalyzerVerifier.cs | 4 +- .../Verifiers/CSharpCodeFixVerifier.cs | 4 +- .../CSharpSourceGeneratorVerifier.cs | 14 +- 9 files changed, 311 insertions(+), 73 deletions(-) delete mode 100644 src/Ling.Audit/Assembly.cs diff --git a/Ling.Audit.sln b/Ling.Audit.sln index 6045c97..601acaa 100644 --- a/Ling.Audit.sln +++ b/Ling.Audit.sln @@ -20,6 +20,13 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ling.Audit.EntityFrameworkC 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("{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 diff --git a/src/Ling.Audit.SourceGenerators/Analyzers/MustNullAttributeAnalyzer.cs b/src/Ling.Audit.SourceGenerators/Analyzers/MustNullAttributeAnalyzer.cs index 8f0e3d4..a7f8d00 100644 --- a/src/Ling.Audit.SourceGenerators/Analyzers/MustNullAttributeAnalyzer.cs +++ b/src/Ling.Audit.SourceGenerators/Analyzers/MustNullAttributeAnalyzer.cs @@ -29,7 +29,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 +64,10 @@ private static void AnalyzeNode(SyntaxNodeAnalysisContext context) case DelegateDeclarationSyntax delegateDeclaration: AnalyzeDelegateDeclaration(context, delegateDeclaration); break; + + case InvocationExpressionSyntax invocation: + AnalyzeInvocation(context, invocation); + break; } } @@ -119,6 +124,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,41 +150,98 @@ private static void AnalyzeDelegateDeclaration(SyntaxNodeAnalysisContext context } } - private static void CheckGenericTypeArguments(SyntaxNodeAnalysisContext context, GenericNameSyntax genericName) + private static void AnalyzeInvocation(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocation) { - if (context.SemanticModel.GetSymbolInfo(genericName).Symbol is not INamedTypeSymbol typeSymbol) + ExpressionSyntax? expression = invocation.Expression; + while (expression is not null) { - return; + if (expression is GenericNameSyntax genericName) + { + CheckGenericTypeArguments(context, genericName); + expression = null; + } + else if (expression is MemberAccessExpressionSyntax { Name: GenericNameSyntax genericName2 }) + { + CheckGenericTypeArguments(context, genericName2); + expression = null; + } + else if (expression is InvocationExpressionSyntax invocationExpression) + { + expression = invocationExpression.Expression; + } + else + { + expression = null; + } } + } - var mustNullAttribute = GetMustNullAttributeSymbol(context.Compilation); - - for (var i = 0; i < typeSymbol.TypeArguments.Length; i++) + private static void CheckGenericTypeArguments(SyntaxNodeAnalysisContext context, GenericNameSyntax genericName) + { + var symbolInfo = context.SemanticModel.GetSymbolInfo(genericName); + if (symbolInfo is { Symbol: INamedTypeSymbol typeSymbol }) { - var argument = typeSymbol.TypeArguments[i]; - var argumentSyntax = genericName.TypeArgumentList.Arguments[i]; + var mustNullAttribute = GetMustNullAttributeSymbol(context.Compilation); - // 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))) + for (var i = 0; i < typeSymbol.TypeArguments.Length; i++) { - // Check argument is nullable - if (argument is not ITypeParameterSymbol && !argument.CanAssignNull()) + 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) { - var diagnostic = Diagnostic.Create( - DiagnosticDescriptors.TypeParameterMustBeNullable, - argumentSyntax.GetLocation(), - argumentSyntax.ToFullString()); - context.ReportDiagnostic(diagnostic); + CheckGenericTypeArguments(context, nestedGenericName); } } + } + else if (symbolInfo is { Symbol: IMethodSymbol methodSymbol }) + { + var mustNullAttribute = GetMustNullAttributeSymbol(context.Compilation); - // If type argument is a generic type, check itself - if (argument is INamedTypeSymbol namedTypeArgument && - namedTypeArgument.IsGenericType && - argumentSyntax is GenericNameSyntax nestedGenericName) + for (var i = 0; i < methodSymbol.TypeArguments.Length; i++) { - CheckGenericTypeArguments(context, nestedGenericName); + var argument = methodSymbol.TypeArguments[i]; + var argumentSyntax = genericName.TypeArgumentList.Arguments[i]; + + // Check if current type parameter has MustNullAttribute or its base type has + if (HasAttributeSymbol(methodSymbol.TypeParameters[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); + } } } } 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..0fb2bce 100644 --- a/src/Ling.Audit/Ling.Audit.csproj +++ b/src/Ling.Audit/Ling.Audit.csproj @@ -43,6 +43,12 @@ + + + <_Parameter1>Ling.Audit.EntityFrameworkCore + + + 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.SourceGenerators.Tests/Analyzers/MustNullAttributeAnalyzerTests.cs b/tests/Ling.Audit.SourceGenerators.Tests/Analyzers/MustNullAttributeAnalyzerTests.cs index 472d834..fb5e494 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,125 @@ 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); + } + + #endregion Method Calls } 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; } From 220c7c1a970330da63c49ddce8031a4d6e533ad6 Mon Sep 17 00:00:00 2001 From: Jing Ling Date: Tue, 14 Jan 2025 01:06:52 +0800 Subject: [PATCH 4/9] Update MustNullAttributeAnalyzer to include new diagnostic for parameter types --- .../AnalyzerReleases.Shipped.md | 22 +- .../Analyzers/MustNullAttributeAnalyzer.cs | 78 ++++--- .../Diagnostics/DiagnosticDescriptors.cs | 18 ++ .../Resources/SR.Designer.cs | 27 +++ .../Resources/SR.resx | 13 ++ .../MustNullAttributeAnalyzerTests.cs | 214 ++++++++++++++++++ 6 files changed, 340 insertions(+), 32 deletions(-) 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/Analyzers/MustNullAttributeAnalyzer.cs b/src/Ling.Audit.SourceGenerators/Analyzers/MustNullAttributeAnalyzer.cs index a7f8d00..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) @@ -160,9 +161,25 @@ private static void AnalyzeInvocation(SyntaxNodeAnalysisContext context, Invocat CheckGenericTypeArguments(context, genericName); expression = null; } - else if (expression is MemberAccessExpressionSyntax { Name: GenericNameSyntax genericName2 }) + else if (expression is IdentifierNameSyntax identifierName) { - CheckGenericTypeArguments(context, genericName2); + 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) @@ -214,35 +231,44 @@ private static void CheckGenericTypeArguments(SyntaxNodeAnalysisContext context, } else if (symbolInfo is { Symbol: IMethodSymbol methodSymbol }) { - var mustNullAttribute = GetMustNullAttributeSymbol(context.Compilation); + CheckGenericMethodSymbol(context, methodSymbol, genericName); + } + } - for (var i = 0; i < methodSymbol.TypeArguments.Length; i++) - { - var argument = methodSymbol.TypeArguments[i]; - var argumentSyntax = genericName.TypeArgumentList.Arguments[i]; + private static void CheckGenericMethodSymbol(SyntaxNodeAnalysisContext context, IMethodSymbol methodSymbol, SimpleNameSyntax nameSyntax) + { + var mustNullAttribute = GetMustNullAttributeSymbol(context.Compilation); - // Check if current type parameter has MustNullAttribute or its base type has - if (HasAttributeSymbol(methodSymbol.TypeParameters[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); - } - } + for (var i = 0; i < methodSymbol.TypeArguments.Length; i++) + { + var argument = methodSymbol.TypeArguments[i]; + SyntaxNode argumentSyntax = nameSyntax is GenericNameSyntax genericName + ? genericName.TypeArgumentList.Arguments[i] + : nameSyntax.FirstAncestorOrSelf()!.ArgumentList.Arguments[i]; - // If type argument is a generic type, check itself - if (argument is INamedTypeSymbol namedTypeArgument && - namedTypeArgument.IsGenericType && - argumentSyntax is GenericNameSyntax nestedGenericName) + // Check if current type parameter has MustNullAttribute or its base type has + if (HasAttributeSymbol(methodSymbol.TypeParameters[i], mustNullAttribute)) + { + // Check argument is nullable + if (argument is not ITypeParameterSymbol && !argument.CanAssignNull()) { - CheckGenericTypeArguments(context, nestedGenericName); + var diagnostic = Diagnostic.Create( + argumentSyntax is TypeSyntax + ? DiagnosticDescriptors.TypeParameterMustBeNullable + : DiagnosticDescriptors.ParameterTypeMustBeNullable, + 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); + } } } 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/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..84f84c4 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 diff --git a/tests/Ling.Audit.SourceGenerators.Tests/Analyzers/MustNullAttributeAnalyzerTests.cs b/tests/Ling.Audit.SourceGenerators.Tests/Analyzers/MustNullAttributeAnalyzerTests.cs index fb5e494..1023d3c 100644 --- a/tests/Ling.Audit.SourceGenerators.Tests/Analyzers/MustNullAttributeAnalyzerTests.cs +++ b/tests/Ling.Audit.SourceGenerators.Tests/Analyzers/MustNullAttributeAnalyzerTests.cs @@ -715,5 +715,219 @@ public void Test() 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 } From 5f0f2bdd7d38e2a45723a40726d058c8a2db2a01 Mon Sep 17 00:00:00 2001 From: Jing Ling Date: Tue, 14 Jan 2025 01:07:25 +0800 Subject: [PATCH 5/9] Refactor auditing system in Ling.Audit.EntityFrameworkCore --- .github/copilot-instructions.md | 1 + .../DbContextOptionsBuilderExtensions.cs | 7 +- .../DefaultAuditUserProvider.cs | 2 +- .../Assembly.cs | 3 - .../AuditDefaults.cs | 6 - .../AuditOptions.cs | 19 +-- .../DbContextOptionsBuilderExtensions.cs | 62 +-------- .../Extensions/ModelBuilderExtensions.cs | 26 ++-- .../IAuditContextProvider.cs | 2 +- .../IAuditLogRepository.cs | 94 +++++++++++++ .../IPropertySerializer.cs | 50 +++++++ .../Internal/AuditConventionSetPlugin.cs | 58 +++++++- .../AuditIgnoreAttributeConvention.cs | 31 ----- .../AuditIncludeAttributeConvention.cs | 34 ----- .../Internal/AuditInterceptor.cs | 43 ++---- .../Internal/AuditModelCustomizer.cs | 125 +++++++++++++++++- .../Internal/AuditOptionsConfigure.cs | 7 + .../Internal/Constants.cs | 34 +++-- .../Extensions/AuditConventionExtension.cs | 41 ------ .../Extensions/AuditOptionsExtension.cs | 34 ++++- .../Internal/Extensions/ConvertExtensions.cs | 46 ------- .../Extensions/DbContextExtensions.cs | 31 +++-- .../Extensions/EntityEntryExtensions.cs | 25 ---- .../Extensions/UserProviderExtension.cs | 41 ------ .../Internal/Models/AuditPropertyEntry.cs | 2 +- .../Ling.Audit.EntityFrameworkCore.csproj | 8 +- .../Models/AuditEntityChangeLog.cs | 2 +- .../AuditEntityLogTypeConfiguration.cs | 76 ----------- .../AuditFieldLogTypeConfiguration.cs | 52 -------- 29 files changed, 444 insertions(+), 518 deletions(-) create mode 100644 .github/copilot-instructions.md delete mode 100644 src/Ling.Audit.EntityFrameworkCore/Assembly.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/IAuditLogRepository.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/IPropertySerializer.cs delete mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/AuditIgnoreAttributeConvention.cs delete mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/AuditIncludeAttributeConvention.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/AuditOptionsConfigure.cs delete mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditConventionExtension.cs delete mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ConvertExtensions.cs delete mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/EntityEntryExtensions.cs delete mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/UserProviderExtension.cs delete mode 100644 src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditEntityLogTypeConfiguration.cs delete mode 100644 src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditFieldLogTypeConfiguration.cs diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..977f8f6 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1 @@ +Always add XML documents in English. \ No newline at end of file diff --git a/src/Ling.Audit.AspNetCore/DbContextOptionsBuilderExtensions.cs b/src/Ling.Audit.AspNetCore/DbContextOptionsBuilderExtensions.cs index 3afe170..e841358 100644 --- a/src/Ling.Audit.AspNetCore/DbContextOptionsBuilderExtensions.cs +++ b/src/Ling.Audit.AspNetCore/DbContextOptionsBuilderExtensions.cs @@ -20,12 +20,7 @@ public static DbContextOptionsBuilder UseAudit(this DbContextOptionsBuilder buil { ArgumentNullException.ThrowIfNull(builder); - builder.AddAuditOptions(setupAction); - - builder.AddAuditUserProvider(); - builder.AddAuditConvention(); - builder.AddAuditInterceptor(); - builder.AddModelCustomizer(); + builder.UseAudit(setupAction); return builder; } diff --git a/src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs b/src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs index a4592e0..bfc08f6 100644 --- a/src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs +++ b/src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs @@ -12,7 +12,7 @@ namespace Ling.Audit.AspNetCore; /// /// Default implementation of interface . /// -internal sealed class HttpAuditContextProvider : IAuditContextProvider +internal sealed class HttpAuditContextProvider : IAuditContextProvider { private readonly Lazy _lazyContext; diff --git a/src/Ling.Audit.EntityFrameworkCore/Assembly.cs b/src/Ling.Audit.EntityFrameworkCore/Assembly.cs deleted file mode 100644 index a7f5efa..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/Assembly.cs +++ /dev/null @@ -1,3 +0,0 @@ -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("Ling.Audit.AspNetCore")] diff --git a/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs b/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs index f74a3a8..55699e2 100644 --- a/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs +++ b/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs @@ -17,10 +17,4 @@ public static class AuditDefaults /// /// public const string DisableAuditingSwitch = "Ling.Audit.EntityFrameworkCore.DisableAuditing"; - - /// - /// The key for the configuration. - /// It will be used to get the from 's section. - /// - public const string ConfigurationSection = "Audit"; } diff --git a/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs b/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs index ecc7286..b91b9c2 100644 --- a/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs @@ -1,4 +1,4 @@ -using System.Security.Claims; +using System.Text.Json; namespace Ling.Audit.EntityFrameworkCore; @@ -7,8 +7,6 @@ namespace Ling.Audit.EntityFrameworkCore; /// public class AuditOptions { - internal Type? UserIdType { get; set; } - /// /// Whether to allow anonymous creation of audit entities, default to . /// @@ -39,16 +37,6 @@ public class AuditOptions /// public bool AllowAnonymousDelete { get; set; } - /// - /// Claim type of user identity. - /// - public string UserIdClaimType { get; set; } = ClaimTypes.NameIdentifier; - - /// - /// Claim type of user name. - /// - public string UserNameClaimType { get; set; } = ClaimTypes.Name; - /// /// Comments. /// @@ -58,6 +46,11 @@ public class AuditOptions /// Whether to audit entities that has no field changes, default to . /// public bool AuditNoFieldChangeEntity { get; set; } + + /// + /// Gets or sets for default . + /// + public JsonSerializerOptions? PropertySerializerOptions { get; set; } } /// diff --git a/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs index bd8fcd9..5e36ddc 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs @@ -1,5 +1,4 @@ -using Ling.Audit.EntityFrameworkCore.Internal; -using Ling.Audit.EntityFrameworkCore.Internal.Extensions; +using Ling.Audit.EntityFrameworkCore.Internal.Extensions; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -17,72 +16,25 @@ public static class DbContextOptionsBuilderExtensions /// /// The . /// The action used to configure the . - public static DbContextOptionsBuilder UseAudit( + public static DbContextOptionsBuilder UseAudit( this DbContextOptionsBuilder builder, Action? setupAction = null) where TUserProvider : class, IAuditContextProvider { ArgumentNullException.ThrowIfNull(builder); - builder.AddAuditOptions(setupAction, o => o.UserIdType = typeof(TUserId)); - - builder.AddAuditUserProvider(); - builder.AddAuditConvention(); - builder.AddAuditInterceptor(); - builder.AddModelCustomizer(); - - return builder; - } - - internal static DbContextOptionsBuilder AddAuditOptions( - this DbContextOptionsBuilder builder, - Action? setupAction, - Action? additional = null) - { - var extension = builder.Options.FindExtension(); - if (extension is null) - { - var combine = (setupAction ?? delegate { }) + (additional ?? delegate { }); - extension = new AuditOptionsExtension(combine); - } - - ((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(extension); - - return builder; - } - - internal static DbContextOptionsBuilder AddAuditUserProvider(this DbContextOptionsBuilder builder) - where TUserProvider : class, IAuditContextProvider - { - var extension = builder.Options.FindExtension>() - ?? new UserProviderExtension(); + var extension = builder.Options.FindExtension>() + ?? new AuditOptionsExtension(setupAction); ((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(extension); return builder; } - internal static DbContextOptionsBuilder AddAuditConvention(this DbContextOptionsBuilder builder) - { - var extension = builder.Options.FindExtension() ?? new AuditConventionExtension(); - - ((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(extension); - - return builder; - } - - internal static DbContextOptionsBuilder AddAuditInterceptor(this DbContextOptionsBuilder builder) - { - builder.AddInterceptors(new AuditInterceptor()); - builder.ReplaceService>(); - - return builder; - } - - internal static DbContextOptionsBuilder AddModelCustomizer(this DbContextOptionsBuilder builder) + public static DbContextOptionsBuilder UseSerializer(this DbContextOptionsBuilder builder) + where TSerializer : class, IPropertySerializer { - builder.AddInterceptors(new AuditInterceptor()); - builder.ReplaceService>(); + builder.ReplaceService(); return builder; } diff --git a/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs index 1e415cf..7991cac 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs @@ -152,14 +152,13 @@ public static ModelBuilder ConfigureAuditLogTableNames( /// Audit options to configure the behavior of audited entities. /// Logger to log the configuration process. /// The identity type of user for current . - internal static Type? ConfigureAuditableEntities(this ModelBuilder builder, AuditOptions options, ILogger logger) + internal static void ConfigureAuditableEntities(this ModelBuilder builder, AuditOptions options, ILogger logger) { ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(options); - Type? userIdType = options.UserIdType; - logger.LogInformation("Starting to configure auditable entities. Initial user ID type: {UserIdType}", - userIdType?.GetFriendlyName() ?? "null"); + 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()) { @@ -179,7 +178,7 @@ public static ModelBuilder ConfigureAuditLogTableNames( if (entityType.HasProperty(Constants.CreatedBy, out var createdByType)) { - ValidateAndUpdateUserIdType(entityClrType, Constants.CreatedBy, createdByType, ref userIdType); + ValidateAndUpdateUserIdType(entityClrType, Constants.CreatedBy, createdByType, userIdType); ConfigureProperty(builder, entityClrType, createdByType, Constants.CreatedBy, 992, options.Comments.CreatedBy); metadata.HasCreatedBy = true; metadata.UserIdType = createdByType; @@ -195,7 +194,7 @@ public static ModelBuilder ConfigureAuditLogTableNames( if (entityType.HasProperty(Constants.ModifiedBy, out var modifiedByType)) { - ValidateAndUpdateUserIdType(entityClrType, Constants.ModifiedBy, modifiedByType, ref userIdType); + ValidateAndUpdateUserIdType(entityClrType, Constants.ModifiedBy, modifiedByType, userIdType); ConfigureProperty(builder, entityClrType, modifiedByType, Constants.ModifiedBy, 995, options.Comments.ModifiedBy); metadata.HasModifiedBy = true; metadata.UserIdType = modifiedByType; @@ -218,7 +217,7 @@ public static ModelBuilder ConfigureAuditLogTableNames( if (entityType.HasProperty(Constants.DeletedBy, out var deletedByType)) { - ValidateAndUpdateUserIdType(entityClrType, Constants.DeletedBy, deletedByType, ref userIdType); + ValidateAndUpdateUserIdType(entityClrType, Constants.DeletedBy, deletedByType, userIdType); ConfigureProperty(builder, entityClrType, deletedByType, Constants.DeletedBy, 999, options.Comments.DeletedBy); metadata.HasDeletedBy = true; metadata.UserIdType = deletedByType; @@ -247,10 +246,7 @@ public static ModelBuilder ConfigureAuditLogTableNames( } } - logger.LogInformation("Completed configuring auditable entities. Final user ID type: {UserIdType}", - userIdType?.GetFriendlyName() ?? "null"); - - return userIdType; + logger.LogInformation("Completed configuring auditable entities."); } /// @@ -381,13 +377,9 @@ private static void ValidatePropertyType(Type entityClrType, string propertyName /// 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, ref Type? userIdType) + private static void ValidateAndUpdateUserIdType(Type entityClrType, string propertyName, Type propertyType, Type userIdType) { - if (userIdType is null) - { - userIdType = propertyType; - } - else if (userIdType != propertyType) + if (userIdType != propertyType) { throw new InvalidOperationException( $"User ID type mismatch in entity '{entityClrType.GetFriendlyName()}.{propertyName}'. Expected '{userIdType.GetFriendlyName()}' but found '{propertyType.GetFriendlyName()}'."); diff --git a/src/Ling.Audit.EntityFrameworkCore/IAuditContextProvider.cs b/src/Ling.Audit.EntityFrameworkCore/IAuditContextProvider.cs index d7ade27..7736004 100644 --- a/src/Ling.Audit.EntityFrameworkCore/IAuditContextProvider.cs +++ b/src/Ling.Audit.EntityFrameworkCore/IAuditContextProvider.cs @@ -3,7 +3,7 @@ /// /// Interface for audit user information. /// -public interface IAuditContextProvider +public interface IAuditContextProvider<[MustNull] TUserId> { /// /// Gets the identity of user. diff --git a/src/Ling.Audit.EntityFrameworkCore/IAuditLogRepository.cs b/src/Ling.Audit.EntityFrameworkCore/IAuditLogRepository.cs new file mode 100644 index 0000000..97e0009 --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/IAuditLogRepository.cs @@ -0,0 +1,94 @@ +using Ling.Audit.EntityFrameworkCore.Internal.Extensions; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; + +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// +/// +public interface IAuditLogRepository<[MustNull] TUserId> +{ + Task?> GetByIdAsync(long auditEntityChangeLogId, CancellationToken cancellationToken = default); + + Task>> GetHistoryAsync(TEntity entity, CancellationToken cancellationToken = default) + where TEntity : class; +} + +internal class AuditLogRepository : IAuditLogRepository +{ + private readonly DbContext _dbContext; + + public AuditLogRepository(ICurrentDbContext currentDbContext) + { + _dbContext = currentDbContext.Context; + } + + public async Task?> GetByIdAsync(long auditEntityChangeLogId, CancellationToken cancellationToken = default) + { + return await _dbContext.Set>() + .AsNoTracking() + .Include(x => x.Details) + .FirstOrDefaultAsync(x => x.Id == auditEntityChangeLogId, cancellationToken); + } + + public async Task>> GetHistoryAsync(TEntity entity, CancellationToken cancellationToken = default) + where TEntity : class + { + var entry = _dbContext.Attach(entity); + + //var entityType = entity.GetType(); + var entityType = _dbContext.Model.FindEntityType(typeof(TEntity)); + if (entityType is null) + { + throw new InvalidOperationException($"The entity type {typeof(TEntity).Name} is not found in the model."); + } + + var xxx = entityType.GetProperties(); + var yyy = entityType.GetDeclaredProperties(); + var zzz = entityType.GetDerivedProperties(); + var entityName = entityType.DisplayName(); + var key = entityType.FindPrimaryKey(); + if (key is null) + { + throw new InvalidOperationException($"The entity type {typeof(TEntity).Name} does not have a primary key."); + } + + var entityKey = key.GetPrimaryKey(entity); + + var auditEntityChangeLogs = await _dbContext.Set>() + .AsNoTracking() + .Where(x => x.EntityTypeName == entityName && x.EntityKey == entityKey) + .OrderByDescending(x => x.EventTime) + .ToListAsync(cancellationToken); + return auditEntityChangeLogs.Select(x => new EntityHistory( + x, + entity, + entity)).ToList(); + } +} + +public sealed record EntityHistory( + TEntity? Original, + TEntity? New, + AuditEventType EventType, + DateTimeOffset EventTime, + TUserId? UserId, + string? UserName, + string? IPAddress, + string? ClientName) + where TEntity : class +{ + public EntityHistory(AuditEntityChangeLog changeLog, TEntity? Original, TEntity? New) + : this( + Original, + New, + changeLog.EventType, + changeLog.EventTime, + changeLog.UserId, + changeLog.UserName, + changeLog.IPAddress, + changeLog.ClientName) + { + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/IPropertySerializer.cs b/src/Ling.Audit.EntityFrameworkCore/IPropertySerializer.cs new file mode 100644 index 0000000..6d3825d --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/IPropertySerializer.cs @@ -0,0 +1,50 @@ +using System.Text.Json; + +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// +/// +public interface IPropertySerializer +{ + string? Serialize(object? value, Type valueType); + + object? Deserialize(string? value, Type valueType); +} + +internal sealed class DefaultPropertySerializer : IPropertySerializer +{ + private readonly JsonSerializerOptions _options; + + public DefaultPropertySerializer(JsonSerializerOptions jsonSerializerOptions) + { +#if NET9_0_OR_GREATER + _options = JsonSerializerOptions.Web; +#else + _options = new JsonSerializerOptions(JsonSerializerDefaults.Web); +#if NET8_0 + _options.MakeReadOnly(); +#endif +#endif + _options = jsonSerializerOptions; + } + + public string? Serialize(object? value, Type valueType) + { + return value is null ? null : JsonSerializer.Serialize(value, valueType, _options); + } + + public object? Deserialize(string? value, Type valueType) + { + if (value is null) + { + return valueType.IsValueType && Nullable.GetUnderlyingType(valueType) is null + ? Activator.CreateInstance(valueType) + : null; + } + else + { + return JsonSerializer.Deserialize(value, valueType, _options); + } + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs index f3f5ee9..341ebfe 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs @@ -1,5 +1,7 @@ -using Microsoft.EntityFrameworkCore.Metadata.Conventions; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Microsoft.EntityFrameworkCore.Metadata.Conventions; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; +using System.Reflection; namespace Ling.Audit.EntityFrameworkCore.Internal; @@ -26,4 +28,58 @@ public ConventionSet ModifyConventions(ConventionSet conventionSet) 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, + AuditIncludeAttribute attribute, + IConventionContext context) + { + entityTypeBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, true); + } + } + + /// + /// 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, + AuditIgnoreAttribute attribute, + MemberInfo clrMember, + IConventionContext context) + { + propertyBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, false); + } + } } diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIgnoreAttributeConvention.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIgnoreAttributeConvention.cs deleted file mode 100644 index f500523..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIgnoreAttributeConvention.cs +++ /dev/null @@ -1,31 +0,0 @@ -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using Microsoft.EntityFrameworkCore.Metadata.Conventions; -using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; -using System.Reflection; - -namespace Ling.Audit.EntityFrameworkCore.Internal; - -/// -/// Convention to process on properties and fields. -/// -internal 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, - AuditIgnoreAttribute attribute, - MemberInfo clrMember, - IConventionContext context) - { - propertyBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, false); - } -} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIncludeAttributeConvention.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIncludeAttributeConvention.cs deleted file mode 100644 index fc67f97..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditIncludeAttributeConvention.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using Microsoft.EntityFrameworkCore.Metadata.Conventions; -using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; - -namespace Ling.Audit.EntityFrameworkCore.Internal; - -/// -/// Convention to process on entity types. -/// -internal 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, - AuditIncludeAttribute attribute, - IConventionContext context) - { - entityTypeBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, true); - } -} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs index 8fafb1c..64091f5 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs @@ -5,9 +5,7 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.Logging; -using System.ComponentModel; using System.Diagnostics.CodeAnalysis; -using System.Text.Json; namespace Ling.Audit.EntityFrameworkCore.Internal; @@ -75,7 +73,7 @@ internal void InternalSavingChanges(DbContextEventData eventData) var entityType = entityEntry.Metadata.ClrType; var metadata = entityEntry.Metadata.GetAuditMetadata(); var eventType = AuditEventType.None; - var userId = isUserIdDefaultValue ? null : userProvider.Id.ConvertToTargetType(metadata.UserIdType); + var userId = userProvider.Id; switch (entityEntry.State) { @@ -182,6 +180,8 @@ internal int InternalSavedChanges(SaveChangesCompletedEventData eventData) } var userProvider = context.GetService>(); + var serializer = context.GetService(); + var logs = _entries .Select(i => new AuditEntityChangeLog { @@ -198,9 +198,9 @@ internal int InternalSavedChanges(SaveChangesCompletedEventData eventData) Details = i.Properties.ConvertAll(j => new AuditFieldChangeLog { FieldName = i.EntityType + '.' + j.Name, - OriginalValue = GetStringValue(j.OriginalValue), - NewValue = GetStringValue(j.NewValue), - ValueType = j.ValueType, + OriginalValue = serializer.Serialize(j.OriginalValue, j.ValueType), + NewValue = serializer.Serialize(j.NewValue, j.ValueType), + ValueType = j.ValueType.Name, }), }) .ToList(); @@ -249,8 +249,9 @@ private static bool TryGetAuditEntry(EntityEntry entityEntry, [NotNullWhen(true) auditEntry.Properties.Add(new AuditPropertyEntry { Name = propertyEntry.Metadata.Name, - OriginalValue = entityEntry.State == EntityState.Added ? null : propertyEntry.OriginalValue, - NewValue = propertyEntry.CurrentValue + ValueType = propertyEntry.Metadata.ClrType, + OriginalValue = entityEntry.State is EntityState.Added ? null : propertyEntry.OriginalValue, + NewValue = entityEntry.State is EntityState.Deleted ? null : propertyEntry.CurrentValue }); } } @@ -272,32 +273,6 @@ private static AuditEventType GetModifiedType(EntityEntry entityEntry, AuditMeta return AuditEventType.Modify; } - private static string? GetStringValue(object? value) - { - if (value == null) return null; - - try - { - if (value is DateTime dt) - { - return dt.ToString("yyyy-MM-dd HH:mm:ss"); - } - else if (value is DateTimeOffset dto) - { - return dto.ToString("yyyy-MM-dd HH:mm:ss zzz"); - } - - var converter = TypeDescriptor.GetConverter(value.GetType()); - if (converter.CanConvertTo(typeof(string))) - { - return converter.ConvertToString(value); - } - } - catch { } - - return JsonSerializer.Serialize(value); - } - /// public void Dispose() { diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs index 8de1fdc..103fdc3 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs @@ -1,7 +1,7 @@ using Ling.Audit.EntityFrameworkCore.Internal.Extensions; -using Ling.Audit.EntityFrameworkCore.TypeConfigurations; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.Extensions.Logging; namespace Ling.Audit.EntityFrameworkCore.Internal; @@ -29,17 +29,136 @@ public AuditModelCustomizer( /// public override void Customize(ModelBuilder modelBuilder, DbContext context) { - modelBuilder.ApplyConfiguration(new AuditEntityLogTypeConfiguration()); + modelBuilder.ApplyConfiguration(new AuditEntityLogTypeConfiguration()); modelBuilder.ApplyConfiguration(new AuditFieldLogTypeConfiguration()); base.Customize(modelBuilder, context); var auditOptions = context.GetAuditOptions(); - modelBuilder.ConfigureAuditableEntities(auditOptions, _logger); + 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.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/AuditOptionsConfigure.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditOptionsConfigure.cs new file mode 100644 index 0000000..d59ca9e --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditOptionsConfigure.cs @@ -0,0 +1,7 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; + +namespace Ling.Audit.EntityFrameworkCore.Internal; + +internal class AuditOptionsConfigure(IConfiguration config) + : ConfigureFromConfigurationOptions(config.GetSection(Constants.ConfigurationSection)); diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs index 0db1291..e66abff 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs @@ -1,27 +1,33 @@ -namespace Ling.Audit.EntityFrameworkCore.Internal; +using Microsoft.Extensions.Configuration; + +namespace Ling.Audit.EntityFrameworkCore.Internal; internal static class Constants { - internal const string AuditableAnnotationName = "Ling:Audit:Auditable"; - internal const string MetadataAnnotationName = "Ling:Audit:Metadata"; + /// + /// 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"; - internal const string Id = "Id"; - internal const string CreatedAt = nameof(IHasCreationTime.CreatedAt); - internal const string CreatedBy = nameof(IHasCreator.CreatedBy); - internal const string ModifiedAt = nameof(IHasModificationTime.LastModifiedAt); - internal const string ModifiedBy = nameof(IHasModifier.LastModifiedBy); - internal const string IsDeleted = nameof(ISoftDelete.IsDeleted); - internal const string DeletedAt = nameof(IHasDeletionTime.DeletedAt); - internal const string DeletedBy = nameof(IHasDeleter.DeletedBy); + 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); - internal static readonly IReadOnlyCollection PropertyNames = + public static readonly IReadOnlyCollection PropertyNames = [ - Id, CreatedAt, CreatedBy, ModifiedAt, ModifiedBy, - IsDeleted, DeletedAt, DeletedBy, ]; diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditConventionExtension.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditConventionExtension.cs deleted file mode 100644 index 75ed0c9..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditConventionExtension.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; - -internal sealed class AuditConventionExtension : IDbContextOptionsExtension -{ - /// - public DbContextOptionsExtensionInfo Info => new AuditConventionExtensionInfo(this); - - /// - public void ApplyServices(IServiceCollection services) - { - services.TryAddEnumerable(ServiceDescriptor.Scoped()); - } - - /// - public void Validate(IDbContextOptions options) - { - } - - private class AuditConventionExtensionInfo : DbContextOptionsExtensionInfo - { - public override bool IsDatabaseProvider { get; } - public override string LogFragment { get; } = string.Empty; - - public AuditConventionExtensionInfo(IDbContextOptionsExtension extension) : base(extension) - { - } - - public override int GetServiceProviderHashCode() => 0; - - public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => other is AuditConventionExtensionInfo; - - public override void PopulateDebugInfo(IDictionary debugInfo) - { - } - } -} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs index 22174fa..7cfd47d 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs @@ -1,22 +1,26 @@ using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; using System.Diagnostics.CodeAnalysis; namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; -internal sealed class AuditOptionsExtension : IDbContextOptionsExtension +internal sealed class AuditOptionsExtension : IDbContextOptionsExtension + where TUserProvider : class, IAuditContextProvider { public Action? Action { get; } /// - public DbContextOptionsExtensionInfo Info => new AuditOptionsExtensionInfo(this); + public DbContextOptionsExtensionInfo Info => new ExtensionInfo(this); public AuditOptionsExtension(Action? setupAction) { Action = setupAction; } - public AuditOptionsExtension([NotNull] AuditOptionsExtension copyFrom) + public AuditOptionsExtension([NotNull] AuditOptionsExtension copyFrom) { Action = copyFrom.Action; } @@ -24,6 +28,24 @@ public AuditOptionsExtension([NotNull] AuditOptionsExtension copyFrom) /// public void ApplyServices(IServiceCollection services) { + // Configure audit options + if (Action is null) + { + services.TryAddEnumerable(ServiceDescriptor.Singleton, AuditOptionsConfigure>()); + } + else + { + services.Configure(Action); + } + + // Add serializer for property conversion + services.TryAddSingleton(); + + // Add custom plugin for audit annotations + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + + // Add audit context for user + services.TryAddScoped, TUserProvider>(); } /// @@ -31,18 +53,18 @@ public void Validate(IDbContextOptions options) { } - private class AuditOptionsExtensionInfo : DbContextOptionsExtensionInfo + private class ExtensionInfo : DbContextOptionsExtensionInfo { public override bool IsDatabaseProvider { get; } public override string LogFragment { get; } = string.Empty; - public AuditOptionsExtensionInfo(IDbContextOptionsExtension extension) : base(extension) + public ExtensionInfo(IDbContextOptionsExtension extension) : base(extension) { } public override int GetServiceProviderHashCode() => 0; - public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => other is AuditOptionsExtensionInfo; + public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => other is ExtensionInfo; public override void PopulateDebugInfo(IDictionary debugInfo) { diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ConvertExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ConvertExtensions.cs deleted file mode 100644 index 7c5b795..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/ConvertExtensions.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.ComponentModel; - -namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; - -internal static class ConvertExtensions -{ - internal static object? ConvertToTargetType(this object? value, Type? targetType) - { - if (targetType is null || value is null) - { - return value; - } - - var underlyingType = Nullable.GetUnderlyingType(targetType) ?? targetType; - var valueType = value.GetType(); - if (valueType == targetType || valueType == underlyingType) - { - return value; - } - - try - { - if (targetType.IsPrimitive) - { - return Convert.ChangeType(value, underlyingType); - } - - var method = underlyingType.GetMethod("Parse", new Type[] { typeof(string) }); - if (method is not null) - { - return method.Invoke(null, new object?[] { value?.ToString() }); - } - - var converter = TypeDescriptor.GetConverter(underlyingType); - if (converter is not null) - { - return converter.ConvertFrom(value); - } - } - catch - { - } - - return null; - } -} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs index 792adde..bdc59d7 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs @@ -1,6 +1,8 @@ using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.Extensions.Configuration; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.Extensions.Options; namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; @@ -8,16 +10,27 @@ internal static class DbContextExtensions { internal static AuditOptions GetAuditOptions(this DbContext context) { - var configuration = context.GetService(); - var options = configuration.GetSection(AuditDefaults.ConfigurationSection).Get() ?? new(); + return context.GetService>().Value; + } - var extension = context.GetService() - .Extensions - .OfType() - .FirstOrDefault(); + /// + /// 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); - extension?.Action?.Invoke(options); + return entityEntry.Metadata.FindPrimaryKey()?.GetPrimaryKey(entityEntry.Entity) ?? string.Empty; + } + + internal static string GetPrimaryKey(this IKey key, object entity) + { + ThrowHelper.ThrowIfNull(key); + ThrowHelper.ThrowIfNull(entity); - return options; + return string.Join(";", key.Properties.Select(p => $"{p.Name}={p.PropertyInfo?.GetValue(entity)}")); } } diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/EntityEntryExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/EntityEntryExtensions.cs deleted file mode 100644 index 9c81a09..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/EntityEntryExtensions.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Microsoft.EntityFrameworkCore.ChangeTracking; - -namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; - -/// -/// Extension methods for . -/// -internal static class EntityEntryExtensions -{ - /// - /// 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) - { - ArgumentNullException.ThrowIfNull(entityEntry); - - var key = entityEntry.Metadata.FindPrimaryKey(); - return key is null - ? string.Empty - : string.Join(",", key.Properties.Select(p => $"{p.Name}={p.PropertyInfo?.GetValue(entityEntry.Entity)}")); - } -} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/UserProviderExtension.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/UserProviderExtension.cs deleted file mode 100644 index e9fa8e5..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/UserProviderExtension.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; - -internal sealed class UserProviderExtension : IDbContextOptionsExtension - where TUserProvider : class, IAuditContextProvider -{ - /// - public DbContextOptionsExtensionInfo Info => new UserProviderExtensionInfo(this); - - /// - public void ApplyServices(IServiceCollection services) - { - services.TryAddScoped, TUserProvider>(); - } - - /// - public void Validate(IDbContextOptions options) - { - } - - private class UserProviderExtensionInfo : DbContextOptionsExtensionInfo - { - public override bool IsDatabaseProvider { get; } - public override string LogFragment { get; } = string.Empty; - - public UserProviderExtensionInfo(IDbContextOptionsExtension extension) : base(extension) - { - } - - public override int GetServiceProviderHashCode() => 0; - - public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => other is UserProviderExtensionInfo; - - public override void PopulateDebugInfo(IDictionary debugInfo) - { - } - } -} diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditPropertyEntry.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditPropertyEntry.cs index dc3ef45..5ab33e6 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditPropertyEntry.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditPropertyEntry.cs @@ -23,5 +23,5 @@ internal sealed class AuditPropertyEntry /// /// Gets or sets the type of the property value. /// - public string ValueType { get; set; } = default!; + public Type ValueType { get; set; } = default!; } diff --git a/src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj b/src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj index 662ea3f..041fc81 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj +++ b/src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj @@ -7,7 +7,7 @@ - + @@ -30,4 +30,10 @@ + + + <_Parameter1>Ling.Audit.AspNetCore + + + diff --git a/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs b/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs index 90fa7e7..b428d0d 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs @@ -6,7 +6,7 @@ namespace Ling.Audit.EntityFrameworkCore; /// Represents the audit log for entities. /// /// The type of the user ID. -public class AuditEntityChangeLog +public class AuditEntityChangeLog<[MustNull] TUserId> { /// /// Gets or sets the primary key. diff --git a/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditEntityLogTypeConfiguration.cs b/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditEntityLogTypeConfiguration.cs deleted file mode 100644 index a92ef5f..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditEntityLogTypeConfiguration.cs +++ /dev/null @@ -1,76 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Ling.Audit.EntityFrameworkCore.TypeConfigurations; - -/// -/// Configures the entity type. -/// -/// The type of the user ID. -internal 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.HasMany(al => al.Details) - .WithOne() - .HasForeignKey(ald => ald.EntityLogId) - .OnDelete(DeleteBehavior.Cascade); - } -} diff --git a/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditFieldLogTypeConfiguration.cs b/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditFieldLogTypeConfiguration.cs deleted file mode 100644 index 99eb6c9..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/TypeConfigurations/AuditFieldLogTypeConfiguration.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Ling.Audit.EntityFrameworkCore.TypeConfigurations; - -/// -/// Configures the entity type. -/// -internal 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."); - } -} From 33312c9e304766351db80e3e0858462f3ee650d3 Mon Sep 17 00:00:00 2001 From: Jing Ling Date: Fri, 22 Aug 2025 16:48:16 +0800 Subject: [PATCH 6/9] temp --- .../DefaultAuditUserProvider.cs | 4 +- .../Attributes/AuditIgnoreAttribute.cs | 10 - .../Attributes/AuditIncludeAttribute.cs | 22 -- .../Attributes/AuditableAttribute.cs | 15 + .../Attributes/NotAuditedAttribute.cs | 8 + .../AuditDefaults.cs | 4 +- .../AuditOptions.cs | 28 +- .../DataOperation.cs | 34 +++ .../EntityOperationType.cs | 33 --- .../DbContextOptionsBuilderExtensions.cs | 31 ++- .../Extensions/ModelBuilderExtensions.cs | 53 +++- .../IAuditAnonymousHandler.cs | 47 ++++ .../IAuditContextProvider.cs | 27 -- .../IAuditLogRepository.cs | 94 ------- .../IAuditUserProvider.cs | 91 ++++++ .../IPropertySerializer.cs | 89 +++++- .../Internal/AuditConventionSetPlugin.cs | 14 +- .../Internal/AuditOptionsConfigure.cs | 7 - ...ptor.cs => AuditSaveChangesInterceptor.cs} | 64 ++--- .../Internal/Constants.cs | 1 + .../Extensions/AuditOptionsExtension.cs | 25 +- .../Internal/Models/AuditMetadata.cs | 7 +- .../Models/AuditEntityChangeLog.cs | 4 +- .../Models/AuditFieldChangeLog.cs | 5 +- .../AttributeTests.cs | 1 + .../AuditAttributesTest.cs | 117 ++++++++ .../AuditChangeLogTests.cs | 105 +++++++ .../AuditEntityChangeLogTests.cs | 1 + .../AuditOptionsTests.cs | 160 +++++++++++ .../AuditTests.cs | 184 +++++++++++++ .../Base/TestAuditContextProvider.cs | 25 ++ .../Base/TestBase.cs | 80 ++++++ .../Base/TestDbContext.cs | 66 +++++ .../CustomPropertySerializerTests.cs | 103 +++++++ .../DisableAuditSwitchTest.cs | 81 ++++++ .../DisableAuditSwitchTests.cs | 1 + .../EntityOperationTypeTests.cs | 64 +++++ .../AuditDbContextExtensionsTests.cs | 41 +++ .../AuditSaveChangesInterceptorTests.cs | 91 ++++++ ...ing.Audit.EntityFrameworkCore.Tests.csproj | 41 +++ .../PropertySerializerTests.cs | 187 +++++++++++++ .../AuditEntityChangeLogTests.cs | 60 ++++ .../AuditEntityTests.cs | 260 ++++++++++++++++++ .../AuditFieldChangeLogTests.cs | 72 +++++ .../AuditOptionsTests.cs | 111 ++++++++ .../Core/AuditTestsBase.cs | 66 +++++ .../Core/Entities/CategoryEntity.cs | 12 + .../Core/Entities/PostEntity.cs | 10 + .../Core/Entities/UserEntity.cs | 7 + .../Core/EquivalencyOptionsExtensions.cs | 91 ++++++ .../Core/TestAuditContextProvider.cs | 27 ++ .../Core/TestDbContext.cs | 29 ++ .../EntityOperationTypeTests.cs | 45 +++ ...ing.Audit.EntityFrameworkCore.Tests.csproj | 41 +++ .../PropertySerializerTests.cs | 119 ++++++++ .../TestClass.cs | 176 ++++++++++++ 56 files changed, 2892 insertions(+), 299 deletions(-) delete mode 100644 src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIgnoreAttribute.cs delete mode 100644 src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIncludeAttribute.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Attributes/AuditableAttribute.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/Attributes/NotAuditedAttribute.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/DataOperation.cs delete mode 100644 src/Ling.Audit.EntityFrameworkCore/EntityOperationType.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/IAuditAnonymousHandler.cs delete mode 100644 src/Ling.Audit.EntityFrameworkCore/IAuditContextProvider.cs delete mode 100644 src/Ling.Audit.EntityFrameworkCore/IAuditLogRepository.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/IAuditUserProvider.cs delete mode 100644 src/Ling.Audit.EntityFrameworkCore/Internal/AuditOptionsConfigure.cs rename src/Ling.Audit.EntityFrameworkCore/Internal/{AuditInterceptor.cs => AuditSaveChangesInterceptor.cs} (78%) create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/AttributeTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/AuditAttributesTest.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/AuditChangeLogTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/AuditEntityChangeLogTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/AuditOptionsTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/AuditTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/Base/TestAuditContextProvider.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/Base/TestBase.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/Base/TestDbContext.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/CustomPropertySerializerTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/DisableAuditSwitchTest.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/DisableAuditSwitchTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/EntityOperationTypeTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/Extensions/AuditDbContextExtensionsTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/Interceptors/AuditSaveChangesInterceptorTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/Ling.Audit.EntityFrameworkCore.Tests.csproj create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests/PropertySerializerTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditEntityChangeLogTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditEntityTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditFieldChangeLogTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditOptionsTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/AuditTestsBase.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/CategoryEntity.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/PostEntity.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/UserEntity.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/EquivalencyOptionsExtensions.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/TestAuditContextProvider.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/TestDbContext.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/EntityOperationTypeTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/Ling.Audit.EntityFrameworkCore.Tests.csproj create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/PropertySerializerTests.cs create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/TestClass.cs diff --git a/src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs b/src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs index bfc08f6..15e90eb 100644 --- a/src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs +++ b/src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs @@ -30,6 +30,8 @@ internal sealed class HttpAuditContextProvider : IAuditContextProvider public HttpAuditContextProvider(ICurrentDbContext current) { + var httpContext = current.Context.GetService()?.HttpContext; + _lazyContext = new Lazy(() => new AuditContext( current.Context.GetService>(), current.Context.GetService(), @@ -52,7 +54,7 @@ public AuditContext(ILogger logger, IHttpContextAccessor httpContextAccessor, Au return; } - Id = context.User.FindFirstValue(options.UserIdClaimType); + Id = context.User.Identity.Name(options.UserIdClaimType); Name = context.User.FindFirstValue(options.UserNameClaimType); IPAddress = context.Connection.RemoteIpAddress?.ToString(); diff --git a/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIgnoreAttribute.cs b/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIgnoreAttribute.cs deleted file mode 100644 index 64d6752..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIgnoreAttribute.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Ling.Audit.EntityFrameworkCore; - -/// -/// Specifies that a property or field should be excluded from auditing in an audited entity. -/// -/// This attribute is only effective when the containing entity is marked with . -/// -/// -[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] -public class AuditIgnoreAttribute : Attribute; diff --git a/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIncludeAttribute.cs b/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIncludeAttribute.cs deleted file mode 100644 index 7a8f8b3..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/Attributes/AuditIncludeAttribute.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace Ling.Audit.EntityFrameworkCore; - -/// -/// Specifies that an entity class should be included in automatic auditing. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] -public class AuditIncludeAttribute : Attribute -{ - /// - /// Initializes a new instance of the class with specified anonymous operations. - /// - /// The operations that can be performed without authentication. - public AuditIncludeAttribute(EntityOperationType anonymousOperations = EntityOperationType.None) - { - AnonymousOperations = anonymousOperations; - } - - /// - /// Gets the operations that can be performed without authentication. - /// - public EntityOperationType AnonymousOperations { get; } -} 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 index 55699e2..887ba62 100644 --- a/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs +++ b/src/Ling.Audit.EntityFrameworkCore/AuditDefaults.cs @@ -1,6 +1,4 @@ -using Microsoft.Extensions.Configuration; - -namespace Ling.Audit.EntityFrameworkCore; +namespace Ling.Audit.EntityFrameworkCore; /// /// Define the audit configuration items. diff --git a/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs b/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs index b91b9c2..dea703f 100644 --- a/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs @@ -8,34 +8,12 @@ namespace Ling.Audit.EntityFrameworkCore; public class AuditOptions { /// - /// Whether to allow anonymous creation of audit entities, default to . + /// Whether to allow anonymous operation of audit entities, default to . /// - /// An will be thrown when anonymous creation, you can - /// use to specify anonymous operations that entities can perform. + /// will be invoke when anonymous operation occurred. /// - /// If , it will allow anonymous creation for all audit entities. /// - public bool AllowAnonymousCreate { get; set; } - - /// - /// Whether to allow anonymous modification of audit entities, default to . - /// - /// An will be thrown when anonymous modification, you - /// can use to specify anonymous operations that entities can perform. - /// - /// If , it will allow anonymous modification for all audit entities. - /// - public bool AllowAnonymousModify { get; set; } - - /// - /// Whether to allow anonymous deletion of audit entities, default to . - /// - /// An will be thrown when anonymous deletion, you can - /// use to specify anonymous operations that entities can perform. - /// - /// If , it will allow anonymous deletion for all audit entities. - /// - public bool AllowAnonymousDelete { get; set; } + public bool AllowAnonymous { get; set; } /// /// Comments. 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/EntityOperationType.cs b/src/Ling.Audit.EntityFrameworkCore/EntityOperationType.cs deleted file mode 100644 index 4f564e8..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/EntityOperationType.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace Ling.Audit.EntityFrameworkCore; - -/// -/// Enum that specifies the type of operation performed on an entity. -/// -[Flags] -public enum EntityOperationType : byte -{ - /// - /// No operation. - /// - None = 0, - - /// - /// Entity creation operation. - /// - Create = 1 << 1, - - /// - /// Entity update operation. - /// - Update = 1 << 2, - - /// - /// Entity deletion operation. - /// - Delete = 1 << 3, - - /// - /// Combination of Create, Update, and Delete operations. - /// - All = Create | Update | Delete, -} diff --git a/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs index 5e36ddc..2bcba26 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs @@ -1,4 +1,5 @@ -using Ling.Audit.EntityFrameworkCore.Internal.Extensions; +using Ling.Audit.EntityFrameworkCore.Internal; +using Ling.Audit.EntityFrameworkCore.Internal.Extensions; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -19,7 +20,7 @@ public static class DbContextOptionsBuilderExtensions public static DbContextOptionsBuilder UseAudit( this DbContextOptionsBuilder builder, Action? setupAction = null) - where TUserProvider : class, IAuditContextProvider + where TUserProvider : AuditContextProviderBase { ArgumentNullException.ThrowIfNull(builder); @@ -28,9 +29,21 @@ public static DbContextOptionsBuilder UseAudit()); + + // 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 { @@ -38,4 +51,18 @@ public static DbContextOptionsBuilder UseSerializer(this DbContextO 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; + } } diff --git a/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs index 7991cac..bf843b3 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs @@ -47,7 +47,7 @@ public static void SetupSoftDeleteQueryFilter(this ModelBuilder builder) /// 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, EntityOperationType anonymousOperations = EntityOperationType.None) + public static EntityTypeBuilder IsAuditable(this EntityTypeBuilder entityTypeBuilder, DataOperation anonymousOperations = DataOperation.None) { ArgumentNullException.ThrowIfNull(entityTypeBuilder); @@ -57,9 +57,9 @@ public static EntityTypeBuilder IsAuditable(this EntityTypeBuilder entityTypeBui return entityTypeBuilder; } - /// + /// /// The entity type being configured. - public static EntityTypeBuilder IsAuditable(this EntityTypeBuilder entityTypeBuilder, EntityOperationType anonymousOperations = EntityOperationType.None) + public static EntityTypeBuilder IsAuditable(this EntityTypeBuilder entityTypeBuilder, DataOperation anonymousOperations = DataOperation.None) where TEntity : class { EntityTypeBuilder builder = entityTypeBuilder; @@ -73,23 +73,23 @@ public static EntityTypeBuilder IsAuditable(this EntityTypeBui /// Configures whether to apply auditing to the column. /// /// The builder for the property being configured. - /// Whether to audit the column, defaults to . + /// Whether not to audit the column, defaults to . /// The same builder instance so that multiple calls can be chained. - public static PropertyBuilder IsAuditable(this PropertyBuilder propertyBuilder, bool enabled = false) + public static PropertyBuilder IsNotAudited(this PropertyBuilder propertyBuilder, bool notAudited = true) { ArgumentNullException.ThrowIfNull(propertyBuilder); - propertyBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, enabled); + propertyBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, !notAudited); return propertyBuilder; } - /// + /// /// The type of the property being configured. - public static PropertyBuilder IsAuditable(this PropertyBuilder propertyBuilder, bool enabled = false) + public static PropertyBuilder IsNotAudited(this PropertyBuilder propertyBuilder, bool notAudited = true) { PropertyBuilder builder = propertyBuilder; - builder.IsAuditable(enabled); + builder.IsNotAudited(notAudited); return propertyBuilder; } @@ -288,17 +288,40 @@ internal static AuditMetadata GetAuditMetadata(this IReadOnlyAnnotatable entityT /// /// The annotatable to check. /// if auditing is included; otherwise, . - internal static bool GetAuditInclude(this IReadOnlyAnnotatable annotatable) + internal static bool IsAuditable(this IReadOnlyAnnotatable annotatable) { ArgumentNullException.ThrowIfNull(annotatable); var value = annotatable.FindAnnotation(Constants.AuditableAnnotationName)?.Value; - return annotatable switch + + if (annotatable is IEntityType) + { + // Entity auditable is false by default + return value is true; + } + else if (annotatable is IProperty property) { - IEntityType => value is true, // Entity auditable defaults to false - IProperty => value is false, // Entity property or field auditable defaults to true - _ => throw new InvalidOperationException() - }; + 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 diff --git a/src/Ling.Audit.EntityFrameworkCore/IAuditAnonymousHandler.cs b/src/Ling.Audit.EntityFrameworkCore/IAuditAnonymousHandler.cs new file mode 100644 index 0000000..7e21bbe --- /dev/null +++ b/src/Ling.Audit.EntityFrameworkCore/IAuditAnonymousHandler.cs @@ -0,0 +1,47 @@ +using Microsoft.Extensions.Logging; + +namespace Ling.Audit.EntityFrameworkCore; + +/// +/// Interface for handling anonymous audit operations. +/// +public interface IAuditAnonymousHandler +{ + /// + /// Handles anonymous audit operation for the specified entity. + /// + /// The type of the entity being audited. + /// The data operation being performed. + /// The entity instance being audited. + /// A token to cancel the operation. + /// A task representing the asynchronous operation. + Task HandleAsync( + Type entityType, + DataOperation operation, + object? entity, + CancellationToken cancellationToken = default); +} + +/// +/// Default implementation of that logs anonymous operations. +/// +internal sealed class DefaultAuditAnonymousHandler( + ILogger logger) + : IAuditAnonymousHandler +{ + /// + public Task HandleAsync( + Type entityType, + DataOperation operation, + object? entity, + CancellationToken cancellationToken = default) + { + logger.LogWarning( + "Anonymous {Operation} operation detected on entity type {EntityType}. Entity: {@Entity}", + operation, + entityType.FullName, + entity); + + return Task.CompletedTask; + } +} diff --git a/src/Ling.Audit.EntityFrameworkCore/IAuditContextProvider.cs b/src/Ling.Audit.EntityFrameworkCore/IAuditContextProvider.cs deleted file mode 100644 index 7736004..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/IAuditContextProvider.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace Ling.Audit.EntityFrameworkCore; - -/// -/// Interface for audit user information. -/// -public interface IAuditContextProvider<[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; } -} diff --git a/src/Ling.Audit.EntityFrameworkCore/IAuditLogRepository.cs b/src/Ling.Audit.EntityFrameworkCore/IAuditLogRepository.cs deleted file mode 100644 index 97e0009..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/IAuditLogRepository.cs +++ /dev/null @@ -1,94 +0,0 @@ -using Ling.Audit.EntityFrameworkCore.Internal.Extensions; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; - -namespace Ling.Audit.EntityFrameworkCore; - -/// -/// -/// -public interface IAuditLogRepository<[MustNull] TUserId> -{ - Task?> GetByIdAsync(long auditEntityChangeLogId, CancellationToken cancellationToken = default); - - Task>> GetHistoryAsync(TEntity entity, CancellationToken cancellationToken = default) - where TEntity : class; -} - -internal class AuditLogRepository : IAuditLogRepository -{ - private readonly DbContext _dbContext; - - public AuditLogRepository(ICurrentDbContext currentDbContext) - { - _dbContext = currentDbContext.Context; - } - - public async Task?> GetByIdAsync(long auditEntityChangeLogId, CancellationToken cancellationToken = default) - { - return await _dbContext.Set>() - .AsNoTracking() - .Include(x => x.Details) - .FirstOrDefaultAsync(x => x.Id == auditEntityChangeLogId, cancellationToken); - } - - public async Task>> GetHistoryAsync(TEntity entity, CancellationToken cancellationToken = default) - where TEntity : class - { - var entry = _dbContext.Attach(entity); - - //var entityType = entity.GetType(); - var entityType = _dbContext.Model.FindEntityType(typeof(TEntity)); - if (entityType is null) - { - throw new InvalidOperationException($"The entity type {typeof(TEntity).Name} is not found in the model."); - } - - var xxx = entityType.GetProperties(); - var yyy = entityType.GetDeclaredProperties(); - var zzz = entityType.GetDerivedProperties(); - var entityName = entityType.DisplayName(); - var key = entityType.FindPrimaryKey(); - if (key is null) - { - throw new InvalidOperationException($"The entity type {typeof(TEntity).Name} does not have a primary key."); - } - - var entityKey = key.GetPrimaryKey(entity); - - var auditEntityChangeLogs = await _dbContext.Set>() - .AsNoTracking() - .Where(x => x.EntityTypeName == entityName && x.EntityKey == entityKey) - .OrderByDescending(x => x.EventTime) - .ToListAsync(cancellationToken); - return auditEntityChangeLogs.Select(x => new EntityHistory( - x, - entity, - entity)).ToList(); - } -} - -public sealed record EntityHistory( - TEntity? Original, - TEntity? New, - AuditEventType EventType, - DateTimeOffset EventTime, - TUserId? UserId, - string? UserName, - string? IPAddress, - string? ClientName) - where TEntity : class -{ - public EntityHistory(AuditEntityChangeLog changeLog, TEntity? Original, TEntity? New) - : this( - Original, - New, - changeLog.EventType, - changeLog.EventTime, - changeLog.UserId, - changeLog.UserName, - changeLog.IPAddress, - changeLog.ClientName) - { - } -} 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 index 6d3825d..1a21dd6 100644 --- a/src/Ling.Audit.EntityFrameworkCore/IPropertySerializer.cs +++ b/src/Ling.Audit.EntityFrameworkCore/IPropertySerializer.cs @@ -1,50 +1,115 @@ -using System.Text.Json; +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 jsonSerializerOptions) + public DefaultPropertySerializer(JsonSerializerOptions? options) + { + _options = options ?? DefaultOptions; + } + + private static JsonSerializerOptions CreateDefaultOptions() { #if NET9_0_OR_GREATER - _options = JsonSerializerOptions.Web; + var options = JsonSerializerOptions.Web; #else - _options = new JsonSerializerOptions(JsonSerializerDefaults.Web); + var options = new JsonSerializerOptions(JsonSerializerDefaults.Web); #if NET8_0 - _options.MakeReadOnly(); + options.MakeReadOnly(); #endif #endif - _options = jsonSerializerOptions; + return options; } + [RequiresUnreferencedCode("The type being serialized may not be preserved in the trimmed output.")] public string? Serialize(object? value, Type valueType) { - return value is null ? null : JsonSerializer.Serialize(value, valueType, _options); + 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 (value is null) + if (valueType == null) + { + throw new ArgumentNullException(nameof(valueType)); + } + + if (value == null) { - return valueType.IsValueType && Nullable.GetUnderlyingType(valueType) is null + return Nullable.GetUnderlyingType(valueType) is null ? Activator.CreateInstance(valueType) : null; } - else + + try { - return JsonSerializer.Deserialize(value, valueType, _options); + 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 index 341ebfe..1a4a668 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs @@ -30,13 +30,13 @@ public ConventionSet ModifyConventions(ConventionSet conventionSet) } /// - /// Convention to process on entity types. + /// Convention to process on entity types. /// private sealed class AuditIncludeAttributeConvention : #if NET8_0_OR_GREATER - TypeAttributeConventionBase + TypeAttributeConventionBase #else - EntityTypeAttributeConventionBase + EntityTypeAttributeConventionBase #endif { /// @@ -51,7 +51,7 @@ public AuditIncludeAttributeConvention(ProviderConventionSetBuilderDependencies /// protected override void ProcessEntityTypeAdded( IConventionEntityTypeBuilder entityTypeBuilder, - AuditIncludeAttribute attribute, + AuditableAttribute attribute, IConventionContext context) { entityTypeBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, true); @@ -59,9 +59,9 @@ protected override void ProcessEntityTypeAdded( } /// - /// Convention to process on properties and fields. + /// Convention to process on properties and fields. /// - private sealed class AuditIgnoreAttributeConvention : PropertyAttributeConventionBase + private sealed class AuditIgnoreAttributeConvention : PropertyAttributeConventionBase { /// /// Initializes a new instance of the class. @@ -75,7 +75,7 @@ public AuditIgnoreAttributeConvention(ProviderConventionSetBuilderDependencies d /// protected override void ProcessPropertyAdded( IConventionPropertyBuilder propertyBuilder, - AuditIgnoreAttribute attribute, + NotAuditedAttribute attribute, MemberInfo clrMember, IConventionContext context) { diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditOptionsConfigure.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditOptionsConfigure.cs deleted file mode 100644 index d59ca9e..0000000 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditOptionsConfigure.cs +++ /dev/null @@ -1,7 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Options; - -namespace Ling.Audit.EntityFrameworkCore.Internal; - -internal class AuditOptionsConfigure(IConfiguration config) - : ConfigureFromConfigurationOptions(config.GetSection(Constants.ConfigurationSection)); diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditSaveChangesInterceptor.cs similarity index 78% rename from src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs rename to src/Ling.Audit.EntityFrameworkCore/Internal/AuditSaveChangesInterceptor.cs index 64091f5..9422bb4 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditInterceptor.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditSaveChangesInterceptor.cs @@ -9,14 +9,17 @@ namespace Ling.Audit.EntityFrameworkCore.Internal; -internal sealed class AuditInterceptor : SaveChangesInterceptor, IDisposable +internal sealed class AuditSaveChangesInterceptor : SaveChangesInterceptor, IDisposable { private IReadOnlyList? _entries; /// public override InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) { - InternalSavingChanges(eventData); + InternalSavingChangesAsync(eventData, default) + .ConfigureAwait(false) + .GetAwaiter() + .GetResult(); return base.SavingChanges(eventData, result); } @@ -32,13 +35,13 @@ public override int SavedChanges(SaveChangesCompletedEventData eventData, int re } /// - public override ValueTask> SavingChangesAsync( + public override async ValueTask> SavingChangesAsync( DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) { - InternalSavingChanges(eventData); - return base.SavingChangesAsync(eventData, result, cancellationToken); + await InternalSavingChangesAsync(eventData, cancellationToken); + return await base.SavingChangesAsync(eventData, result, cancellationToken); } /// @@ -55,14 +58,14 @@ public override async ValueTask SavedChangesAsync( return result; } - internal void InternalSavingChanges(DbContextEventData eventData) + internal async Task InternalSavingChangesAsync(DbContextEventData eventData, CancellationToken cancellationToken) { var context = eventData.Context; if (context is null) return; - var userProvider = context.GetService>(); - var logger = context.GetService().CreateLogger(GetType()); + var userProvider = context.GetService>(); + var handler = context.GetService(); var options = context.GetAuditOptions(); var entries = new List(); var now = DateTimeOffset.Now; @@ -85,12 +88,11 @@ internal void InternalSavingChanges(DbContextEventData eventData) if (metadata.HasDeletedBy) { - if (!options.AllowAnonymousDelete && - !metadata.AllowsAnonymousOperation(EntityOperationType.Delete) && + if (!options.AllowAnonymous && + !metadata.IsAnonymousAllowed(DataOperation.Delete) && isUserIdDefaultValue) { - logger.LogError("Not allowed to delete entity '{entityType}' with anonymous user.", entityType); - throw new InvalidOperationException($"Anonymous deletion of '{entityType.GetFriendlyName()}' is not allowed."); + await handler.HandleAsync(entityType, DataOperation.Delete, entityEntry.Entity, cancellationToken); } entityEntry.Property(Constants.DeletedBy).CurrentValue = userId; } @@ -114,12 +116,11 @@ internal void InternalSavingChanges(DbContextEventData eventData) } if (metadata.HasModifiedBy) { - if (!options.AllowAnonymousModify && - !metadata.AllowsAnonymousOperation(EntityOperationType.Update) && + if (!options.AllowAnonymous && + !metadata.IsAnonymousAllowed(DataOperation.Modify) && isUserIdDefaultValue) { - logger.LogError("Not allowed to modify entity '{entityType}' with anonymous user.", entityType); - throw new InvalidOperationException($"Anonymous modification of {entityType.GetFriendlyName()} is not allowed."); + await handler.HandleAsync(entityType, DataOperation.Modify, entityEntry.Entity, cancellationToken); } entityEntry.Property(Constants.ModifiedBy).CurrentValue = userId; @@ -134,12 +135,12 @@ internal void InternalSavingChanges(DbContextEventData eventData) } if (metadata.HasCreatedBy) { - if (!options.AllowAnonymousCreate && - !metadata.AllowsAnonymousOperation(EntityOperationType.Create) && + if (!options.AllowAnonymous && + !metadata.IsAnonymousAllowed(DataOperation.Create) && isUserIdDefaultValue) { - logger.LogError("Not allowed to create entity '{entityType}' with anonymous user.", entityType); - throw new InvalidOperationException($"Anonymous creation of {entityType.GetFriendlyName()} is not allowed."); + + await handler.HandleAsync(entityType, DataOperation.Create, entityEntry.Entity, cancellationToken); } entityEntry.Property(Constants.CreatedBy).CurrentValue = userId; } @@ -179,7 +180,7 @@ internal int InternalSavedChanges(SaveChangesCompletedEventData eventData) throw new InvalidOperationException("Unable to get entry information before saving changes."); } - var userProvider = context.GetService>(); + var userProvider = context.GetService>(); var serializer = context.GetService(); var logs = _entries @@ -227,8 +228,7 @@ internal int InternalSavedChanges(SaveChangesCompletedEventData eventData) private static bool TryGetAuditEntry(EntityEntry entityEntry, [NotNullWhen(true)] out AuditEntityEntry? auditEntry) { - var entityInclude = entityEntry.Metadata.GetAuditInclude(); - if (!entityInclude) + if (!entityEntry.Metadata.IsAuditable()) { auditEntry = null; return false; @@ -238,20 +238,20 @@ private static bool TryGetAuditEntry(EntityEntry entityEntry, [NotNullWhen(true) foreach (var propertyEntry in entityEntry.Properties) { - var propertyInclude = propertyEntry.Metadata.GetAuditInclude(); - if (propertyInclude && !Constants.PropertyNames.Contains(propertyEntry.Metadata.Name)) + if (propertyEntry.Metadata.IsAuditable() && + (entityEntry.State is EntityState.Added || + !Equals(propertyEntry.OriginalValue, propertyEntry.CurrentValue))) { - if (entityEntry.State is not EntityState.Added && Equals(propertyEntry.OriginalValue, propertyEntry.CurrentValue)) - { - continue; - } - 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 + OriginalValue = entityEntry.State is EntityState.Added + ? null + : propertyEntry.OriginalValue, + NewValue = entityEntry.State is EntityState.Deleted + ? null + : propertyEntry.CurrentValue }); } } diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs index e66abff..3f29180 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Constants.cs @@ -28,6 +28,7 @@ internal static class Constants 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 index 7cfd47d..53861fe 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs @@ -1,14 +1,15 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Options; using System.Diagnostics.CodeAnalysis; +using System.Text.Json; namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; internal sealed class AuditOptionsExtension : IDbContextOptionsExtension - where TUserProvider : class, IAuditContextProvider + where TUserProvider : class, IAuditUserProvider { public Action? Action { get; } @@ -28,24 +29,38 @@ public AuditOptionsExtension([NotNull] AuditOptionsExtension public void ApplyServices(IServiceCollection services) { + JsonSerializerOptions? jsonSerializerOptions = null; + // Configure audit options if (Action is null) { - services.TryAddEnumerable(ServiceDescriptor.Singleton, AuditOptionsConfigure>()); + services.AddOptions() + .Configure((options, context) => + context.Context.GetService() + .GetSection(Constants.ConfigurationSection) + .Bind(options)); } else { services.Configure(Action); + + var tempOptions = new AuditOptions(); + Action.Invoke(new AuditOptions()); + jsonSerializerOptions = tempOptions.PropertySerializerOptions; } // Add serializer for property conversion - services.TryAddSingleton(); + services.TryAddSingleton( + new DefaultPropertySerializer(jsonSerializerOptions)); + + // Add handler for anonymous audit operations + services.TryAddSingleton(); // Add custom plugin for audit annotations services.TryAddEnumerable(ServiceDescriptor.Scoped()); // Add audit context for user - services.TryAddScoped, TUserProvider>(); + services.TryAddScoped, TUserProvider>(); } /// diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditMetadata.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditMetadata.cs index 2e91ac3..31cf90a 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditMetadata.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Models/AuditMetadata.cs @@ -5,10 +5,12 @@ /// internal sealed class AuditMetadata { + public bool IsAuditable { get; set; } + /// /// Gets or sets the operations that can be performed anonymously. /// - public EntityOperationType AnonymousOperations { get; set; } + public DataOperation AnonymousOperations { get; set; } /// /// Gets or sets the type of the user ID. @@ -55,13 +57,14 @@ internal sealed class AuditMetadata /// /// The operation to check. /// if the operation can be performed anonymously; otherwise, . - public bool AllowsAnonymousOperation(EntityOperationType operate) => AnonymousOperations.HasFlag(operate); + 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, diff --git a/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs b/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs index b428d0d..c1da31e 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Models/AuditEntityChangeLog.cs @@ -1,4 +1,5 @@ using Microsoft.EntityFrameworkCore.ChangeTracking; +using System.Diagnostics; namespace Ling.Audit.EntityFrameworkCore; @@ -6,6 +7,7 @@ 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> { /// @@ -66,5 +68,5 @@ public class AuditEntityChangeLog<[MustNull] TUserId> /// /// Gets or sets the details of this audit log. /// - public virtual ICollection Details { get; set; } = new List(); + public virtual ICollection Details { get; set; } = []; } diff --git a/src/Ling.Audit.EntityFrameworkCore/Models/AuditFieldChangeLog.cs b/src/Ling.Audit.EntityFrameworkCore/Models/AuditFieldChangeLog.cs index c8fce38..0b69277 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Models/AuditFieldChangeLog.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Models/AuditFieldChangeLog.cs @@ -1,8 +1,11 @@ -namespace Ling.Audit.EntityFrameworkCore; +using System.Diagnostics; + +namespace Ling.Audit.EntityFrameworkCore; /// /// Represents the detail of . /// +[DebuggerDisplay("{FieldName} = {OriginalValue} => {NewValue}, Type = {ValueType}")] public class AuditFieldChangeLog { /// diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/AttributeTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/AttributeTests.cs new file mode 100644 index 0000000..0519ecb --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/AttributeTests.cs @@ -0,0 +1 @@ + \ No newline at end of file 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..0519ecb --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditEntityChangeLogTests.cs @@ -0,0 +1 @@ + \ No newline at end of file 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..0519ecb --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/DisableAuditSwitchTests.cs @@ -0,0 +1 @@ + \ No newline at end of file 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..a01b91c --- /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..6ef2db5 --- /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 + + + + + + + + + + + + + \ No newline at end of file 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..a77388b --- /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!; + } +} \ No newline at end of file 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..8e57785 --- /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!; +} \ No newline at end of file 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..f5a54f2 --- /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; + } +} \ No newline at end of file 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..9016178 --- /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); + } +} \ No newline at end of file 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..2d3e52c --- /dev/null +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Ling.Audit.EntityFrameworkCore.Tests.csproj @@ -0,0 +1,41 @@ + + + + net9.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 + + + + + + + + + + + + + \ No newline at end of file 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()); + } +} From 84df4e95cb90143532d747e157592dd8e904e338 Mon Sep 17 00:00:00 2001 From: Jing Ling Date: Mon, 31 Aug 2026 13:11:06 +0800 Subject: [PATCH 7/9] feat: prepare Ling.Audit 2.0.1 --- .editorconfig | 14 + .gitattributes | 9 + .github/actions/setup-dotnet/action.yml | 16 - .github/actions/setup-env/action.yml | 20 + .github/copilot-instructions.md | 2 +- .github/workflows/build.yml | 114 +++++ .github/workflows/pull-request.yml | 19 - .github/workflows/release.yml | 30 -- .github/workflows/test.yml | 114 +++++ Ling.Audit.sln | 21 +- README.md | 297 +++++++++++-- README.zh-CN.md | 288 +++++++++++++ docs/migrating-to-2.0.md | 29 ++ global.json | 5 - src/Directory.Build.props | 9 +- .../AspNetCoreAuditOptions.cs | 32 ++ ...etCoreDbContextOptionsBuilderExtensions.cs | 41 ++ .../DbContextOptionsBuilderExtensions.cs | 27 -- .../DefaultAuditPrincipalResolver.cs | 51 +++ .../DefaultAuditUserProvider.cs | 72 ---- .../HttpAuditUserProvider.cs | 57 +++ .../IAuditPrincipalResolver.cs | 21 + .../AspNetCoreAuditOptionsExtension.cs | 48 +++ .../Ling.Audit.AspNetCore.csproj | 16 +- .../AuditOptions.cs | 9 +- .../AuditTransactionMode.cs | 17 + .../DbContextOptionsBuilderExtensions.cs | 11 + .../Extensions/ModelBuilderExtensions.cs | 18 +- .../IAuditAnonymousHandler.cs | 27 +- .../IAuditTimeProvider.cs | 17 + .../IPropertySerializer.cs | 3 - .../Internal/AuditConventionSetPlugin.cs | 6 + .../Internal/AuditModelCustomizer.cs | 15 + .../Internal/AuditSaveChangesInterceptor.cs | 406 +++++++++++------- .../Extensions/AuditOptionsExtension.cs | 14 +- .../Extensions/DbContextExtensions.cs | 12 +- .../Ling.Audit.EntityFrameworkCore.csproj | 15 +- .../AnalyzerReleases.Unshipped.md | 1 - .../Analyzers/AuditTypeAnalyzer.cs | 32 +- .../AuditPropertyGenerator.Execute.cs | 21 +- .../AuditPropertyGenerator.Parser.cs | 6 +- .../AuditPropertyGenerator.cs | 8 +- .../Helpers/ITypeSymbolHelpers.cs | 2 +- .../Ling.Audit.SourceGenerators.csproj | 2 +- .../Properties/launchSettings.json | 2 +- .../Resources/SR.resx | 2 +- src/Ling.Audit/Ling.Audit.csproj | 6 +- .../DefaultAuditPrincipalResolverTests.cs | 93 ++++ .../Ling.Audit.AspNetCore.Tests.csproj | 31 ++ .../AttributeTests.cs | 2 +- .../AuditEntityChangeLogTests.cs | 2 +- .../DisableAuditSwitchTests.cs | 2 +- .../AuditSaveChangesInterceptorTests.cs | 2 +- ...ing.Audit.EntityFrameworkCore.Tests.csproj | 2 +- .../AuditOptionsTests.cs | 2 +- .../Core/Entities/PostEntity.cs | 2 +- .../Core/TestAuditContextProvider.cs | 2 +- .../EntityOperationTypeTests.cs | 2 +- ...ing.Audit.EntityFrameworkCore.Tests.csproj | 34 +- .../V2/AuditIntegrationTests.cs | 216 ++++++++++ .../Ling.Audit.PackageConsumer.csproj | 15 + tests/Ling.Audit.PackageConsumer/NuGet.config | 16 + tests/Ling.Audit.PackageConsumer/Program.cs | 8 + .../Analyzers/AuditTypeAnalyzerTests.cs | 21 + .../AuditPropertyGeneratorTests.cs | 105 ++++- .../Ling.Audit.SourceGenerators.Tests.csproj | 2 +- 66 files changed, 2096 insertions(+), 467 deletions(-) create mode 100644 .editorconfig create mode 100644 .gitattributes delete mode 100644 .github/actions/setup-dotnet/action.yml create mode 100644 .github/actions/setup-env/action.yml create mode 100644 .github/workflows/build.yml delete mode 100644 .github/workflows/pull-request.yml delete mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/test.yml create mode 100644 README.zh-CN.md create mode 100644 docs/migrating-to-2.0.md delete mode 100644 global.json create mode 100644 src/Ling.Audit.AspNetCore/AspNetCoreAuditOptions.cs create mode 100644 src/Ling.Audit.AspNetCore/AspNetCoreDbContextOptionsBuilderExtensions.cs delete mode 100644 src/Ling.Audit.AspNetCore/DbContextOptionsBuilderExtensions.cs create mode 100644 src/Ling.Audit.AspNetCore/DefaultAuditPrincipalResolver.cs delete mode 100644 src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs create mode 100644 src/Ling.Audit.AspNetCore/HttpAuditUserProvider.cs create mode 100644 src/Ling.Audit.AspNetCore/IAuditPrincipalResolver.cs create mode 100644 src/Ling.Audit.AspNetCore/Internal/AspNetCoreAuditOptionsExtension.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/AuditTransactionMode.cs create mode 100644 src/Ling.Audit.EntityFrameworkCore/IAuditTimeProvider.cs create mode 100644 tests/Ling.Audit.AspNetCore.Tests/DefaultAuditPrincipalResolverTests.cs create mode 100644 tests/Ling.Audit.AspNetCore.Tests/Ling.Audit.AspNetCore.Tests.csproj create mode 100644 tests/Ling.Audit.EntityFrameworkCore.Tests1/V2/AuditIntegrationTests.cs create mode 100644 tests/Ling.Audit.PackageConsumer/Ling.Audit.PackageConsumer.csproj create mode 100644 tests/Ling.Audit.PackageConsumer/NuGet.config create mode 100644 tests/Ling.Audit.PackageConsumer/Program.cs 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 index 977f8f6..c1eae9e 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1 +1 @@ -Always add XML documents in English. \ No newline at end of file +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..2111c7a --- /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: + build-and-pack: + 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 601acaa..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 @@ -20,6 +20,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ling.Audit.EntityFrameworkC 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 @@ -53,6 +57,14 @@ Global {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 @@ -63,5 +75,10 @@ Global {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/DbContextOptionsBuilderExtensions.cs b/src/Ling.Audit.AspNetCore/DbContextOptionsBuilderExtensions.cs deleted file mode 100644 index e841358..0000000 --- a/src/Ling.Audit.AspNetCore/DbContextOptionsBuilderExtensions.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Ling.Audit.AspNetCore; -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) - { - ArgumentNullException.ThrowIfNull(builder); - - builder.UseAudit(setupAction); - - return builder; - } -} 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/DefaultAuditUserProvider.cs b/src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs deleted file mode 100644 index 15e90eb..0000000 --- a/src/Ling.Audit.AspNetCore/DefaultAuditUserProvider.cs +++ /dev/null @@ -1,72 +0,0 @@ -using Ling.Audit.EntityFrameworkCore; -using Ling.Audit.EntityFrameworkCore.Internal.Extensions; -using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using System.Security.Claims; -using UAParser; - -namespace Ling.Audit.AspNetCore; - -/// -/// Default implementation of interface . -/// -internal sealed class HttpAuditContextProvider : IAuditContextProvider -{ - private readonly Lazy _lazyContext; - - /// - public string? Id => _lazyContext.Value.Id; - - /// - public string? Name => _lazyContext.Value.Name; - - /// - public string? IPAddress => _lazyContext.Value.IPAddress; - - /// - public string? ClientName => _lazyContext.Value.ClientName; - - public HttpAuditContextProvider(ICurrentDbContext current) - { - var httpContext = current.Context.GetService()?.HttpContext; - - _lazyContext = new Lazy(() => new AuditContext( - current.Context.GetService>(), - current.Context.GetService(), - current.Context.GetAuditOptions())); - } - - private class AuditContext : IAuditContextProvider - { - public string? Id { get; } - public string? Name { get; } - public string? IPAddress { get; } - public string? ClientName { get; } - - public AuditContext(ILogger logger, IHttpContextAccessor httpContextAccessor, AuditOptions options) - { - var context = httpContextAccessor.HttpContext; - if (context is null) - { - logger.LogWarning("HttpContext is null for the current request."); - return; - } - - Id = context.User.Identity.Name(options.UserIdClaimType); - Name = context.User.FindFirstValue(options.UserNameClaimType); - IPAddress = context.Connection.RemoteIpAddress?.ToString(); - - var userAgent = context.Request.Headers.UserAgent; - if (!string.IsNullOrEmpty(userAgent)) - { - ClientName = Parser.GetDefault().Parse(userAgent).ToString(); - } - else - { - logger.LogWarning("User-Agent header is missing."); - } - } - } -} 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 index 4f92b50..6cffc89 100644 --- a/src/Ling.Audit.AspNetCore/Ling.Audit.AspNetCore.csproj +++ b/src/Ling.Audit.AspNetCore/Ling.Audit.AspNetCore.csproj @@ -4,15 +4,27 @@ 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/AuditOptions.cs b/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs index dea703f..24cab70 100644 --- a/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/AuditOptions.cs @@ -25,6 +25,11 @@ public class AuditOptions /// 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 . /// @@ -49,12 +54,12 @@ public class AuditEntityComments /// /// Comment to ModifiedAt property. /// - public string ModifiedAt { get; set; } = "The primary key of the user who modified this entity."; + public string ModifiedAt { get; set; } = "The date and time when modified this entity."; /// /// Comment to ModifiedBy property. /// - public string ModifiedBy { get; set; } = "The date and time when modified this entity."; + public string ModifiedBy { get; set; } = "The primary key of the user who modified this entity."; /// /// Comment to IsDeleted property. 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/Extensions/DbContextOptionsBuilderExtensions.cs b/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs index 2bcba26..85d226b 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Extensions/DbContextOptionsBuilderExtensions.cs @@ -65,4 +65,15 @@ public static DbContextOptionsBuilder UseAnonymousHandler(this DbConte 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 index bf843b3..b92077a 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Extensions/ModelBuilderExtensions.cs @@ -32,7 +32,17 @@ public static void SetupSoftDeleteQueryFilter(this ModelBuilder builder) { var typeParameter = Expression.Parameter(type, "e"); var propertyParameter = Expression.Property(typeParameter, Constants.IsDeleted); - var lambda = Expression.Lambda(Expression.Not(propertyParameter), typeParameter); + 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); } @@ -326,6 +336,12 @@ internal static bool IsAuditable(this IReadOnlyAnnotatable annotatable) #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 /// diff --git a/src/Ling.Audit.EntityFrameworkCore/IAuditAnonymousHandler.cs b/src/Ling.Audit.EntityFrameworkCore/IAuditAnonymousHandler.cs index 7e21bbe..ebe66bd 100644 --- a/src/Ling.Audit.EntityFrameworkCore/IAuditAnonymousHandler.cs +++ b/src/Ling.Audit.EntityFrameworkCore/IAuditAnonymousHandler.cs @@ -1,20 +1,13 @@ -using Microsoft.Extensions.Logging; - namespace Ling.Audit.EntityFrameworkCore; /// -/// Interface for handling anonymous audit operations. +/// Handles an operation for which no audit user could be resolved. /// public interface IAuditAnonymousHandler { /// - /// Handles anonymous audit operation for the specified entity. + /// Handles an anonymous audit operation for the specified entity. /// - /// The type of the entity being audited. - /// The data operation being performed. - /// The entity instance being audited. - /// A token to cancel the operation. - /// A task representing the asynchronous operation. Task HandleAsync( Type entityType, DataOperation operation, @@ -23,25 +16,17 @@ Task HandleAsync( } /// -/// Default implementation of that logs anonymous operations. +/// Rejects anonymous operations unless they were explicitly allowed. /// -internal sealed class DefaultAuditAnonymousHandler( - ILogger logger) - : IAuditAnonymousHandler +internal sealed class DefaultAuditAnonymousHandler : IAuditAnonymousHandler { - /// public Task HandleAsync( Type entityType, DataOperation operation, object? entity, CancellationToken cancellationToken = default) { - logger.LogWarning( - "Anonymous {Operation} operation detected on entity type {EntityType}. Entity: {@Entity}", - operation, - entityType.FullName, - entity); - - return Task.CompletedTask; + 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/IPropertySerializer.cs b/src/Ling.Audit.EntityFrameworkCore/IPropertySerializer.cs index 1a21dd6..3a76d4c 100644 --- a/src/Ling.Audit.EntityFrameworkCore/IPropertySerializer.cs +++ b/src/Ling.Audit.EntityFrameworkCore/IPropertySerializer.cs @@ -51,9 +51,6 @@ private static JsonSerializerOptions CreateDefaultOptions() var options = JsonSerializerOptions.Web; #else var options = new JsonSerializerOptions(JsonSerializerDefaults.Web); -#if NET8_0 - options.MakeReadOnly(); -#endif #endif return options; } diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs index 1a4a668..6c27a13 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditConventionSetPlugin.cs @@ -1,4 +1,5 @@ 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; @@ -55,6 +56,11 @@ protected override void ProcessEntityTypeAdded( IConventionContext context) { entityTypeBuilder.Metadata.SetAnnotation(Constants.AuditableAnnotationName, true); + entityTypeBuilder.Metadata.SetAnnotation(Constants.MetadataAnnotationName, new AuditMetadata + { + IsAuditable = true, + AnonymousOperations = attribute.AllowedAnonymous, + }); } } diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs index 103fdc3..762ff3d 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditModelCustomizer.cs @@ -107,6 +107,21 @@ public void Configure(EntityTypeBuilder> builder) .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) diff --git a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditSaveChangesInterceptor.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditSaveChangesInterceptor.cs index 9422bb4..67511a2 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/AuditSaveChangesInterceptor.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/AuditSaveChangesInterceptor.cs @@ -1,4 +1,4 @@ -using Ling.Audit.EntityFrameworkCore.Internal.Extensions; +using Ling.Audit.EntityFrameworkCore.Internal.Extensions; using Ling.Audit.EntityFrameworkCore.Internal.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -6,227 +6,300 @@ 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, IDisposable +internal sealed class AuditSaveChangesInterceptor : SaveChangesInterceptor { - private IReadOnlyList? _entries; + private readonly ConditionalWeakTable _states = new(); - /// - public override InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) + public override InterceptionResult SavingChanges( + DbContextEventData eventData, + InterceptionResult result) { - InternalSavingChangesAsync(eventData, default) - .ConfigureAwait(false) - .GetAwaiter() - .GetResult(); + InternalSavingChangesAsync(eventData, default).ConfigureAwait(false).GetAwaiter().GetResult(); return base.SavingChanges(eventData, result); } - /// - public override int SavedChanges(SaveChangesCompletedEventData eventData, int result) - { - var count = InternalSavedChanges(eventData); - if (count > 0) - { - eventData.Context!.SaveChanges(); - } - return result; - } - - /// public override async ValueTask> SavingChangesAsync( DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) { - await InternalSavingChangesAsync(eventData, cancellationToken); - return await base.SavingChangesAsync(eventData, result, cancellationToken); + 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) + int result, + CancellationToken cancellationToken = default) + { + await InternalSavedChanges(eventData, async: true, cancellationToken).ConfigureAwait(false); + return result; + } + + public override void SaveChangesFailed(DbContextErrorEventData eventData) { - var count = InternalSavedChanges(eventData); - if (count > 0) + if (eventData.Context is { } context) { - await eventData.Context!.SaveChangesAsync(cancellationToken); + _states.Remove(context); } - return result; + + base.SaveChangesFailed(eventData); } - internal async Task InternalSavingChangesAsync(DbContextEventData eventData, CancellationToken cancellationToken) + 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 (context is null) return; + if (_states.TryGetValue(context, out var activeState) && activeState.IsSavingAuditLogs) + { + return; + } - var userProvider = context.GetService>(); - var handler = context.GetService(); - var options = context.GetAuditOptions(); - var entries = new List(); - var now = DateTimeOffset.Now; - var isUserIdDefaultValue = EqualityComparer.Default.Equals(userProvider.Id, default); + _states.Remove(context); + var state = new SaveState(); + _states.Add(context, state); - foreach (var entityEntry in context.ChangeTracker.Entries()) + try { - var entityType = entityEntry.Metadata.ClrType; - var metadata = entityEntry.Metadata.GetAuditMetadata(); - var eventType = AuditEventType.None; + 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(); - switch (entityEntry.State) + foreach (var entityEntry in context.ChangeTracker.Entries()) { - case EntityState.Deleted: - if (metadata.HasDeletedAt) - { - entityEntry.Property(Constants.DeletedAt).CurrentValue = now; - } + var entityType = entityEntry.Metadata.ClrType; + var metadata = entityEntry.Metadata.GetAuditMetadata(); + var eventType = AuditEventType.None; - if (metadata.HasDeletedBy) - { - if (!options.AllowAnonymous && - !metadata.IsAnonymousAllowed(DataOperation.Delete) && - isUserIdDefaultValue) + switch (entityEntry.State) + { + case EntityState.Deleted: + if (metadata.HasDeletedAt) { - await handler.HandleAsync(entityType, DataOperation.Delete, entityEntry.Entity, cancellationToken); + entityEntry.Property(Constants.DeletedAt).CurrentValue = now; } - 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; + if (metadata.HasDeletedBy) + { + await EnsureUserAsync( + options, metadata, handler, isAnonymous, entityType, + DataOperation.Delete, entityEntry.Entity, cancellationToken).ConfigureAwait(false); + entityEntry.Property(Constants.DeletedBy).CurrentValue = userId; + } - case EntityState.Modified: - if (metadata.HasModifiedAt) - { - entityEntry.Property(Constants.ModifiedAt).CurrentValue = now; - } - if (metadata.HasModifiedBy) - { - if (!options.AllowAnonymous && - !metadata.IsAnonymousAllowed(DataOperation.Modify) && - isUserIdDefaultValue) + if (metadata.HasIsDeleted) { - await handler.HandleAsync(entityType, DataOperation.Modify, entityEntry.Entity, cancellationToken); + entityEntry.Property(Constants.IsDeleted).CurrentValue = true; + entityEntry.State = EntityState.Modified; + eventType = AuditEventType.SoftDelete; } + else + { + eventType = AuditEventType.Delete; + } + break; - entityEntry.Property(Constants.ModifiedBy).CurrentValue = userId; - } - eventType = GetModifiedType(entityEntry, metadata); - break; + case EntityState.Modified: + if (metadata.HasModifiedAt) + { + entityEntry.Property(Constants.ModifiedAt).CurrentValue = now; + } - case EntityState.Added: - if (metadata.HasCreatedAt) - { - entityEntry.Property(Constants.CreatedAt).CurrentValue = now; - } - if (metadata.HasCreatedBy) - { - if (!options.AllowAnonymous && - !metadata.IsAnonymousAllowed(DataOperation.Create) && - isUserIdDefaultValue) + 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; - await handler.HandleAsync(entityType, DataOperation.Create, entityEntry.Entity, cancellationToken); + case EntityState.Added: + if (metadata.HasCreatedAt) + { + entityEntry.Property(Constants.CreatedAt).CurrentValue = now; } - entityEntry.Property(Constants.CreatedBy).CurrentValue = userId; - } - eventType = AuditEventType.Create; - break; - - case EntityState.Detached: - case EntityState.Unchanged: - default: - break; + + 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 (eventType is not AuditEventType.None && TryGetAuditEntry(entityEntry, out var auditEntry)) + if (AppContext.TryGetSwitch(AuditDefaults.DisableAuditingSwitch, out var disabled) && disabled) { - auditEntry.EventType = eventType; - entries.Add(auditEntry); + _states.Remove(context); + return; } - } - if (!AppContext.TryGetSwitch(AuditDefaults.DisableAuditingSwitch, out var disabled) || !disabled) + 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 { - _entries = entries; + _states.Remove(context); + throw; } } - internal int InternalSavedChanges(SaveChangesCompletedEventData eventData) + private async Task InternalSavedChanges( + SaveChangesCompletedEventData eventData, + bool async, + CancellationToken cancellationToken) { var context = eventData.Context; - - if (context is null || (AppContext.TryGetSwitch(AuditDefaults.DisableAuditingSwitch, out var disabled) && disabled)) return 0; - - var options = context.GetAuditOptions(); - var logger = context.GetService().CreateLogger(GetType()); - if (_entries is null) + if (context is null || !_states.TryGetValue(context, out var state) || state.IsSavingAuditLogs) { - logger.LogWarning("Unable to get entry information when saved changes."); - throw new InvalidOperationException("Unable to get entry information before saving changes."); + return; } - var userProvider = context.GetService>(); - var serializer = context.GetService(); + try + { + var options = context.GetAuditOptions(); + var serializer = context.GetService(); + var logger = context.GetService().CreateLogger(GetType()); + var entityCount = 0; + var fieldCount = 0; - var logs = _entries - .Select(i => new AuditEntityChangeLog + foreach (var entry in state.Entries) { - DatabaseSchema = i.Schema, - TableName = i.Table, - EntityKey = i.PrimaryKey, - EntityTypeName = i.EntityType, - EventType = i.EventType, - EventTime = DateTimeOffset.Now, - UserId = userProvider.Id, - UserName = userProvider.Name, - IPAddress = userProvider.IPAddress, - ClientName = userProvider.ClientName, - Details = i.Properties.ConvertAll(j => new AuditFieldChangeLog + var log = new AuditEntityChangeLog { - FieldName = i.EntityType + '.' + j.Name, - OriginalValue = serializer.Serialize(j.OriginalValue, j.ValueType), - NewValue = serializer.Serialize(j.NewValue, j.ValueType), - ValueType = j.ValueType.Name, - }), - }) - .ToList(); - - int entityChangedCount = 0, fieldChangedCount = 0; - foreach (var log in logs) - { - if (log.Details.Count > 0 || options.AuditNoFieldChangeEntity) - { + 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); - entityChangedCount++; - fieldChangedCount += log.Details.Count; + 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); } + } - logger.LogInformation( - "Add {EntityCount} entity changed and {FieldCount} field changed audit logs to {DbContextType}[{ContextId}].", - entityChangedCount, - fieldChangedCount, - context.GetType().GetFriendlyName(), - context.ContextId); - return entityChangedCount + fieldChangedCount; + 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) + private static bool TryGetAuditEntry( + EntityEntry entityEntry, + [NotNullWhen(true)] out AuditEntityEntry? auditEntry) { if (!entityEntry.Metadata.IsAuditable()) { @@ -235,23 +308,18 @@ private static bool TryGetAuditEntry(EntityEntry entityEntry, [NotNullWhen(true) } auditEntry = new AuditEntityEntry(entityEntry); - foreach (var propertyEntry in entityEntry.Properties) { if (propertyEntry.Metadata.IsAuditable() && (entityEntry.State is EntityState.Added || - !Equals(propertyEntry.OriginalValue, propertyEntry.CurrentValue))) + !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 + OriginalValue = entityEntry.State is EntityState.Added ? null : propertyEntry.OriginalValue, + NewValue = entityEntry.State is EntityState.Deleted ? null : propertyEntry.CurrentValue, }); } } @@ -270,12 +338,18 @@ private static AuditEventType GetModifiedType(EntityEntry entityEntry, AuditMeta return newValue ? AuditEventType.SoftDelete : AuditEventType.Recovery; } } + return AuditEventType.Modify; } - /// - public void Dispose() + private sealed class SaveState { - _entries = null; + 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/Extensions/AuditOptionsExtension.cs b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs index 53861fe..7c57114 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/AuditOptionsExtension.cs @@ -45,7 +45,7 @@ public void ApplyServices(IServiceCollection services) services.Configure(Action); var tempOptions = new AuditOptions(); - Action.Invoke(new AuditOptions()); + Action.Invoke(tempOptions); jsonSerializerOptions = tempOptions.PropertySerializerOptions; } @@ -56,6 +56,9 @@ public void ApplyServices(IServiceCollection services) // 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()); @@ -70,19 +73,24 @@ 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() => 0; + public override int GetServiceProviderHashCode() => _extension.Action?.GetHashCode() ?? 0; - public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => other is ExtensionInfo; + 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 index bdc59d7..2d89381 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs +++ b/src/Ling.Audit.EntityFrameworkCore/Internal/Extensions/DbContextExtensions.cs @@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.Extensions.Options; +using System.Text.Json; namespace Ling.Audit.EntityFrameworkCore.Internal.Extensions; @@ -23,14 +24,17 @@ internal static string GetPrimaryKey(this EntityEntry entityEntry) { ThrowHelper.ThrowIfNull(entityEntry); - return entityEntry.Metadata.FindPrimaryKey()?.GetPrimaryKey(entityEntry.Entity) ?? string.Empty; + return entityEntry.Metadata.FindPrimaryKey()?.GetPrimaryKey(entityEntry) ?? string.Empty; } - internal static string GetPrimaryKey(this IKey key, object entity) + internal static string GetPrimaryKey(this IKey key, EntityEntry entityEntry) { ThrowHelper.ThrowIfNull(key); - ThrowHelper.ThrowIfNull(entity); + ThrowHelper.ThrowIfNull(entityEntry); - return string.Join(";", key.Properties.Select(p => $"{p.Name}={p.PropertyInfo?.GetValue(entity)}")); + 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/Ling.Audit.EntityFrameworkCore.csproj b/src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj index 041fc81..c1781bd 100644 --- a/src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj +++ b/src/Ling.Audit.EntityFrameworkCore/Ling.Audit.EntityFrameworkCore.csproj @@ -4,10 +4,23 @@ 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 - + + + + + + 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/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/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.resx b/src/Ling.Audit.SourceGenerators/Resources/SR.resx index 84f84c4..64d497a 100644 --- a/src/Ling.Audit.SourceGenerators/Resources/SR.resx +++ b/src/Ling.Audit.SourceGenerators/Resources/SR.resx @@ -196,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/Ling.Audit.csproj b/src/Ling.Audit/Ling.Audit.csproj index 0fb2bce..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 @@ -61,10 +61,10 @@ - + - \ No newline at end of file + 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 index 0519ecb..8b13789 100644 --- a/tests/Ling.Audit.EntityFrameworkCore.Tests/AttributeTests.cs +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/AttributeTests.cs @@ -1 +1 @@ - \ No newline at end of file + diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditEntityChangeLogTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditEntityChangeLogTests.cs index 0519ecb..8b13789 100644 --- a/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditEntityChangeLogTests.cs +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/AuditEntityChangeLogTests.cs @@ -1 +1 @@ - \ No newline at end of file + diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/DisableAuditSwitchTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/DisableAuditSwitchTests.cs index 0519ecb..8b13789 100644 --- a/tests/Ling.Audit.EntityFrameworkCore.Tests/DisableAuditSwitchTests.cs +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/DisableAuditSwitchTests.cs @@ -1 +1 @@ - \ No newline at end of file + diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/Interceptors/AuditSaveChangesInterceptorTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests/Interceptors/AuditSaveChangesInterceptorTests.cs index a01b91c..068a559 100644 --- a/tests/Ling.Audit.EntityFrameworkCore.Tests/Interceptors/AuditSaveChangesInterceptorTests.cs +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/Interceptors/AuditSaveChangesInterceptorTests.cs @@ -15,7 +15,7 @@ public void DisableAuditingSwitch_WhenTrue_SkipsAuditing() // Act interceptor.SaveChangesBefore(context); - // Assert Ñé֤ûÓнøÐÐÈκÎÉó¼Æ×ֶεÄÐ޸Ä + // Assert ��֤û�н����κ�����ֶε��޸� var entry = context.ChangeTracker.Entries().First(); Assert.Null(entry.Property("CreatedAt").CurrentValue); Assert.Null(entry.Property("CreatedBy").CurrentValue); diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests/Ling.Audit.EntityFrameworkCore.Tests.csproj b/tests/Ling.Audit.EntityFrameworkCore.Tests/Ling.Audit.EntityFrameworkCore.Tests.csproj index 6ef2db5..0b8ec76 100644 --- a/tests/Ling.Audit.EntityFrameworkCore.Tests/Ling.Audit.EntityFrameworkCore.Tests.csproj +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests/Ling.Audit.EntityFrameworkCore.Tests.csproj @@ -38,4 +38,4 @@ - \ No newline at end of file + diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditOptionsTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditOptionsTests.cs index a77388b..02f39ec 100644 --- a/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditOptionsTests.cs +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/AuditOptionsTests.cs @@ -108,4 +108,4 @@ private class TestUser public Guid Id { get; set; } public string Name { get; set; } = null!; } -} \ No newline at end of file +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/PostEntity.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/PostEntity.cs index 8e57785..51f4b66 100644 --- a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/PostEntity.cs +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/Entities/PostEntity.cs @@ -7,4 +7,4 @@ internal sealed partial class PostEntity : IFullAudited public CategoryEntity Category { get; set; } = null!; public string Title { get; set; } = null!; public string Content { get; set; } = null!; -} \ No newline at end of file +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/TestAuditContextProvider.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/TestAuditContextProvider.cs index f5a54f2..e84e51a 100644 --- a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/TestAuditContextProvider.cs +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Core/TestAuditContextProvider.cs @@ -24,4 +24,4 @@ public AnonymousAuditContextProvider(ICurrentDbContext current) : base(current) { return null; } -} \ No newline at end of file +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/EntityOperationTypeTests.cs b/tests/Ling.Audit.EntityFrameworkCore.Tests1/EntityOperationTypeTests.cs index 9016178..2cb2654 100644 --- a/tests/Ling.Audit.EntityFrameworkCore.Tests1/EntityOperationTypeTests.cs +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/EntityOperationTypeTests.cs @@ -42,4 +42,4 @@ public void EntityOperationType_All_ShouldIncludeAllOperations() // Assert EntityOperationType.All.Should().Be(EntityOperationType.Create | EntityOperationType.Update | EntityOperationType.Delete); } -} \ No newline at end of file +} diff --git a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Ling.Audit.EntityFrameworkCore.Tests.csproj b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Ling.Audit.EntityFrameworkCore.Tests.csproj index 2d3e52c..7ce3f81 100644 --- a/tests/Ling.Audit.EntityFrameworkCore.Tests1/Ling.Audit.EntityFrameworkCore.Tests.csproj +++ b/tests/Ling.Audit.EntityFrameworkCore.Tests1/Ling.Audit.EntityFrameworkCore.Tests.csproj @@ -1,10 +1,14 @@  - net9.0 + net6.0;net7.0;net8.0;net9.0 enable enable false + false + Ling.Audit.EntityFrameworkCore.Tests + Ling.Audit.EntityFrameworkCore.Tests + latest @@ -13,29 +17,39 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + - \ No newline at end of file + 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..0b53b52 --- /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/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 + From 246c1248eecb8b762806b2ba958541ddf9f7a668 Mon Sep 17 00:00:00 2001 From: Jing Ling Date: Mon, 31 Aug 2026 15:52:54 +0800 Subject: [PATCH 8/9] fix: use portable package feed path --- tests/Ling.Audit.PackageConsumer/NuGet.config | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Ling.Audit.PackageConsumer/NuGet.config b/tests/Ling.Audit.PackageConsumer/NuGet.config index 0b53b52..5f22d45 100644 --- a/tests/Ling.Audit.PackageConsumer/NuGet.config +++ b/tests/Ling.Audit.PackageConsumer/NuGet.config @@ -2,7 +2,7 @@ - + From 6c07ef8f0a3660c290a7d966c6154f01fd5f7c3d Mon Sep 17 00:00:00 2001 From: Jing Ling Date: Mon, 31 Aug 2026 15:59:36 +0800 Subject: [PATCH 9/9] ci: satisfy required test status check --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2111c7a..f53445b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -21,7 +21,7 @@ env: NUGET_DIRECTORY: ${{ github.workspace }}/artifacts/packages jobs: - build-and-pack: + test: permissions: contents: read runs-on: ubuntu-latest