Skip to content

feat(TcpSocket): add data type check prevent assign exception#548

Merged
ArgoZhang merged 10 commits intomasterfrom
feat-socket2
Aug 27, 2025
Merged

feat(TcpSocket): add data type check prevent assign exception#548
ArgoZhang merged 10 commits intomasterfrom
feat-socket2

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented Aug 27, 2025

Link issues

fixes #547

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Prevent assignment exceptions by validating converter return types and streamline converter instantiation via reflection, while extending the test suite and standardizing headers.

Bug Fixes:

  • Add runtime type check in DataConverter to prevent assigning values of mismatched types to entity properties.

Enhancements:

  • Introduce ActivatorExtensions for robust reflection-based instance creation.
  • Refactor DataPropertyExtensions and ITcpSocketClientExtensions to use CreateInstance for converter instantiation.

Tests:

  • Add Convert_Ok integration test for verifying TCP data package conversion with custom converters and update DoubleConverter_Ok assertion.

Chores:

  • Standardize license header across source and test files.

Copilot AI review requested due to automatic review settings August 27, 2025 05:04
@bb-auto bb-auto Bot added the enhancement New feature or request label Aug 27, 2025
@bb-auto bb-auto Bot added this to the v9.2.0 milestone Aug 27, 2025
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Aug 27, 2025

Reviewer's Guide

Enhances the TCP socket data conversion pipeline by enforcing strict type checks before property assignments, introducing a reusable reflection helper for converter instantiation, and extending unit tests to validate the new behavior.

Class diagram for new ActivatorExtensions and updated data converter usage

classDiagram
    class ActivatorExtesnions {
        +object? CreateInstance(Type type, object?[]? args = null)
        +TType? CreateInstance<TType>(Type type, object?[]? args = null)
    }
    class DataPropertyExtensions {
        +IDataPropertyConverter? GetPropertyConverter(PropertyInfo p)
    }
    class ITcpSocketClientExtensions {
        +void SetDataPackageAdapter<TEntity>(ITcpSocketClient client, ...)
    }
    class DataConverter {
        +bool Parse(ReadOnlyMemory<byte> data, TEntity entity)
    }
    DataPropertyExtensions --> ActivatorExtesnions : uses
    ITcpSocketClientExtensions --> ActivatorExtesnions : uses
    DataConverter --> DataPropertyExtensions : uses
    IDataPropertyConverter <|.. DataPropertyExtensions
    IDataConverter <|.. ITcpSocketClientExtensions
Loading

Flow diagram for property assignment with type check in DataConverter

flowchart TD
    A[Start Parse method] --> B[Get property converter attribute]
    B --> C[Convert data to value]
    C --> D{Is value type equal to property type?}
    D -- Yes --> E[Assign value to property]
    D -- No --> F[Skip assignment]
    E --> G[Continue parsing]
    F --> G[Continue parsing]
    G --> H[Return result]
Loading

File-Level Changes

Change Details Files
Enforce type safety in property converters
  • Only assign converted values when the runtime type matches the target type
DataConverter.cs
Introduce and use reflection helper for instantiation
  • Add ActivatorExtesnions with CreateInstance overloads
  • Replace direct Activator.CreateInstance calls with CreateInstance in DataPropertyExtensions
  • Apply CreateInstance in ITcpSocketClientExtensions
ActivatorExtesnions.cs
DataPropertyExtensions.cs
ITcpSocketClientExtensions.cs
Extend and adjust unit tests for data converters
  • Add Convert_Ok test with MockConverterEntity and FloatConverter
  • Update existing double converter assertion to remove explicit cast
TcpSocketFactoryTest.cs
TcpSocketPropertyConverterTest.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#547 Add data type check in TcpSocket to prevent assign exception.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds data type validation to prevent assignment exceptions in TcpSocket data conversion. The main improvement is adding a type check before setting property values to ensure the converted data matches the expected property type.

  • Introduced type validation in data conversion to prevent assignment exceptions
  • Refactored object instantiation to use a new extension method for better error handling
  • Updated version numbers for the affected packages

Reviewed Changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
src/extensions/BootstrapBlazor.Socket/Extensions/ActivatorExtesnions.cs New extension methods for safe object instantiation with type checking
src/extensions/BootstrapBlazor.Socket/DataConverter/DataConverter.cs Added type validation before property assignment
src/extensions/BootstrapBlazor.Socket/Extensions/DataPropertyExtensions.cs Refactored to use new CreateInstance extension method
src/extensions/BootstrapBlazor.TcpSocket/Extensions/ITcpSocketClientExtensions.cs Refactored to use new CreateInstance extension method
test/UnitTestTcpSocket/TcpSocketFactoryTest.cs Added test case for data conversion functionality
test/UnitTestTcpSocket/TcpSocketPropertyConverterTest.cs Removed unnecessary type cast in assertion
src/extensions/BootstrapBlazor.Socket/BootstrapBlazor.Socket.csproj Version bump to 9.0.3
src/extensions/BootstrapBlazor.TcpSocket/BootstrapBlazor.TcpSocket.csproj Version bump to 9.0.2

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment thread src/extensions/BootstrapBlazor.Socket/Extensions/ActivatorExtesnions.cs Outdated
Comment thread src/extensions/BootstrapBlazor.Socket/DataConverter/DataConverter.cs Outdated
Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `src/extensions/BootstrapBlazor.Socket/Extensions/ActivatorExtesnions.cs:12` </location>
<code_context>
+/// <summary>
+/// Activator 扩展方法
+/// </summary>
+public static class ActivatorExtesnions
+{
+    /// <summary>
</code_context>

<issue_to_address>
Typo in class name: 'ActivatorExtesnions' should be 'ActivatorExtensions'.

Please rename both the class and file to 'ActivatorExtensions' for consistency.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
public static class ActivatorExtesnions
=======
public static class ActivatorExtensions
>>>>>>> REPLACE

</suggested_fix>

### Comment 2
<location> `src/extensions/BootstrapBlazor.Socket/Extensions/ActivatorExtesnions.cs:22` </location>
<code_context>
+    /// <returns></returns>
+    public static object? CreateInstance(this Type type, object?[]? args = null)
+    {
+        var bindings = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Default;
+        return Activator.CreateInstance(type, bindings, null, args, null);
+    }
</code_context>

<issue_to_address>
BindingFlags.Default is redundant when combined with other flags.

BindingFlags.Default is zero and does not change the behavior when combined with other flags. Removing it will make the code clearer.
</issue_to_address>

### Comment 3
<location> `test/UnitTestTcpSocket/TcpSocketFactoryTest.cs:942` </location>
<code_context>
+        await tcs.Task;
+
+        // 验证实体类不为空
+        Assert.NotNull(entity);
+        Assert.Equal("3.14", entity.Value1.ToString("#.##"));
+
+        Task ReceivedCallBack(MockConverterEntity? data)
</code_context>

<issue_to_address>
Test assertions could be more comprehensive.

Also assert 'Header' and 'Body' properties to fully validate the conversion logic.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        // 验证实体类不为空
        Assert.NotNull(entity);
        Assert.Equal("3.14", entity.Value1.ToString("#.##"));
=======
        // 验证实体类不为空
        Assert.NotNull(entity);
        Assert.Equal("3.14", entity.Value1.ToString("#.##"));
        // 验证 Header 和 Body 属性
        Assert.NotNull(entity.Header);
        Assert.NotNull(entity.Body);
        // 可根据预期值进一步断言
        // Assert.Equal(expectedHeader, entity.Header);
        // Assert.Equal(expectedBody, entity.Body);
>>>>>>> REPLACE

</suggested_fix>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/extensions/BootstrapBlazor.Socket/Extensions/ActivatorExtesnions.cs Outdated
Comment thread src/extensions/BootstrapBlazor.Socket/Extensions/ActivatorExtesnions.cs Outdated
Comment thread test/UnitTestTcpSocket/TcpSocketFactoryTest.cs
@ArgoZhang ArgoZhang merged commit 6f8d8aa into master Aug 27, 2025
1 check passed
@ArgoZhang ArgoZhang deleted the feat-socket2 branch August 27, 2025 05:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(TcpSocket): add data type check prevent assign exception

2 participants