Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Uri.EscapeDataString instead of HttpUtility.UrlEncode in Boilerplate (#9868) #9875

Merged
merged 5 commits into from
Feb 12, 2025

Conversation

ysmoradi
Copy link
Member

@ysmoradi ysmoradi commented Feb 12, 2025

closes #9868

Summary by CodeRabbit

  • Refactor

    • Streamlined the construction and parsing of URL query parameters for a more efficient and consistent experience.
  • Bug Fixes

    • Enhanced the logic for extracting and processing query strings, including safer handling of culture values, to minimize errors during URL manipulation.

@ysmoradi ysmoradi requested a review from msynk February 12, 2025 13:53
Copy link

coderabbitai bot commented Feb 12, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes update how query strings are handled across multiple components. The legacy NameValueCollection and dictionary-based approaches have been replaced with a custom AppQueryStringCollection. Methods that modify or retrieve query strings have been updated accordingly, including adjustments to parameter signatures and internal logic. The modifications also include refining URI processing methods and removing redundant or legacy methods in interfaces and classes.

Changes

File(s) Change Summary
src/SourceGenerators/.../HttpClientProxySourceGenerator.cs Replaced use of NameValueCollection with AppQueryStringCollection in AppControllerBase. Updated AddQueryString to accept key and optional value; revised GetDynamicQueryString to convert and clear the new collection.
src/Templates/Boilerplate/.../ODataQuery.cs Modified ToString to use AppQueryStringCollection instead of a dictionary for constructing the query string.
src/Templates/Boilerplate/.../IAppController.cs Removed the AddQueryString(string existingQueryString) method and updated the WithQuery extension to parse query strings before invocation.
src/Templates/Boilerplate/.../UriExtensions.cs Adjusted the emptiness check in GetUrlWithoutQueryParameter using pattern matching; updated GetCulture to use TryGetValue for safer extraction of culture data.
src/Templates/Boilerplate/.../AppQueryStringCollection.cs Refactored class to inherit from Dictionary<string, object?> with a case-insensitive comparer. Removed redundant methods/properties and updated the Add, indexer, and ToString logic to apply URI encoding/decoding.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AppControllerBase
    participant AppQueryStringCollection
    
    User->>AppControllerBase: Call AddQueryString(key, value)
    AppControllerBase->>AppQueryStringCollection: Add key/value with encoding
    User->>AppControllerBase: Invoke GetDynamicQueryString()
    AppControllerBase->>AppQueryStringCollection: Convert collection to string & clear entries
    AppControllerBase->>User: Return query string result
Loading
sequenceDiagram
    participant Client
    participant ODataQuery
    participant AppQueryStringCollection

    Client->>ODataQuery: Invoke ToString()
    ODataQuery->>AppQueryStringCollection: Retrieve query parameters as string
    ODataQuery->>Client: Return constructed query string
Loading

Poem

In my burrow of code, I happily hop,
Reworking strings till the bugs all stop.
Old collections now transformed with flair,
Clean logic strewn like carrots in the air.
A rabbit’s delight in each refactored drop!
🐇✨ Happy hops in our new code crop!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ysmoradi ysmoradi marked this pull request as draft February 12, 2025 14:07
@ysmoradi ysmoradi marked this pull request as ready for review February 12, 2025 16:41
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (2)
src/SourceGenerators/Bit.SourceGenerators/HttpClientProxy/HttpClientProxySourceGenerator.cs (2)

70-70: ⚠️ Potential issue

Ensure proper URL encoding for dynamic query strings.

The current implementation directly concatenates the dynamic query string to the URL without encoding. This could lead to malformed URLs or potential security issues if the query string contains special characters.

Apply this diff to ensure proper URL encoding:

-                __url += {(action.Url.Contains('?') ? "'&'" : "'?'")} + dynamicQS;
+                __url += {(action.Url.Contains('?') ? "'&'" : "'?'")} + Uri.EscapeDataString(dynamicQS);

94-94: 🛠️ Refactor suggestion

Remove unnecessary using directive.

Since we're using Uri.EscapeDataString instead of HttpUtility.UrlEncode as per PR objectives, the System.Web namespace import is no longer needed.

-using System.Web;
🧹 Nitpick comments (4)
src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Services/AppQueryStringCollection.cs (1)

12-12: Avoid double-decoding for partially-escaped keys and values.
Since the code applies both Uri.UnescapeDataString and then re-escapes the result, partially-encoded segments (e.g. "%2B") might be altered unexpectedly. Consider removing the unescape step or adding checks to handle partially-escaped inputs.

src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/ODataQuery.cs (2)

31-31: Consider specifying an initial capacity.
If you expect to add multiple parameters, providing an initial capacity to AppQueryStringCollection can reduce resizing overhead.


68-68: Decide whether to prepend a question mark.
Returning qs.ToString() will omit the leading “?”. If you want a valid query portion for a URL, consider prefixing it with “?”.

src/SourceGenerators/Bit.SourceGenerators/HttpClientProxy/HttpClientProxySourceGenerator.cs (1)

117-123: Add null check for dictionary parameter.

While the implementation is good, it's missing a null check for the input parameter.

-    public void AddQueryStrings(Dictionary<string, object?> queryString)
+    public void AddQueryStrings(Dictionary<string, object?> queryString)
+    {
+        ArgumentNullException.ThrowIfNull(queryString);
+
+        foreach (var key in queryString.Keys)
+        {
+            AddQueryString(key, queryString[key]);
+        }
+    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f7edf0c and 7a958c1.

📒 Files selected for processing (5)
  • src/SourceGenerators/Bit.SourceGenerators/HttpClientProxy/HttpClientProxySourceGenerator.cs (2 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/ODataQuery.cs (2 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Controllers/IAppController.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Extensions/UriExtensions.cs (2 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Services/AppQueryStringCollection.cs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build and test
🔇 Additional comments (7)
src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Extensions/UriExtensions.cs (2)

27-28: LGTM! Safer culture value retrieval.

The changes improve error handling by using TryGetValue instead of direct access, making the code more robust against potential exceptions.


1-64: Verify implementation of PR objective.

While the changes in this file improve query string handling, they don't appear to address the PR's objective of replacing HttpUtility.UrlEncode with Uri.EscapeDataString. Please verify if this change is implemented in other files.

Run the following script to check for any remaining usages of HttpUtility.UrlEncode:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Search for any remaining usages of HttpUtility.UrlEncode

# Search for HttpUtility.UrlEncode usage
rg -i "HttpUtility.UrlEncode"

# Search for using statements that might import HttpUtility
rg -i "using.*HttpUtility"

Length of output: 337


No remaining active usage of HttpUtility.UrlEncode found – PR objective verified.

The search only revealed a reference to HttpUtility.UrlEncode in an XML comment within AppQueryStringCollection.cs, confirming that the change to use Uri.EscapeDataString instead has been broadly implemented.

src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Services/AppQueryStringCollection.cs (1)

8-8: Confirm this constructor syntax is supported in your C# version.
It appears you're using a record-like declaration (parentheses after the class name). Ensure the project targets a C# version that supports this syntax. Otherwise, consider rewriting it as a standard class constructor:

-public class AppQueryStringCollection() : Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase)
+public class AppQueryStringCollection : Dictionary<string, object?>
+{
+    public AppQueryStringCollection() : base(StringComparer.OrdinalIgnoreCase) {}
+}
src/Templates/Boilerplate/Bit.Boilerplate/src/Shared/Controllers/IAppController.cs (1)

19-19: Handle invalid or partially-encoded query strings.
Calling AppQueryStringCollection.Parse(existingQueryString) may cause unexpected behavior if the query string contains malformed or partially-encoded segments. Consider adding error handling or validation before parsing.

src/SourceGenerators/Bit.SourceGenerators/HttpClientProxy/HttpClientProxySourceGenerator.cs (3)

110-110: LGTM! Good choice using collection initializer syntax.

The change to AppQueryStringCollection with array collection initializer syntax is clean and efficient.


112-115: LGTM! Clear and concise implementation.

The new AddQueryString method signature with key-value parameters is more intuitive and type-safe compared to accepting a raw query string.


125-133: LGTM! Clean implementation.

The simplified GetDynamicQueryString method is more maintainable while preserving the clear-after-use behavior.

@ysmoradi ysmoradi merged commit 82cd471 into bitfoundation:develop Feb 12, 2025
3 checks passed
@ysmoradi ysmoradi deleted the 9868 branch February 12, 2025 16:51
@ysmoradi ysmoradi changed the title Use Uri.EscapeDataString instead of HttpUtility.UrlEncode in source generators (#9868) Use Uri.EscapeDataString instead of HttpUtility.UrlEncode in Boilerplate (#9868) Feb 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Bit project template must use Uri.EscapeDataString instead of HttpUtility.UrlEncode
1 participant