Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/tparviainen/query-string-generator
C# incremental generator to create a method that returns the query string of the object.
https://github.com/tparviainen/query-string-generator
csharp-generator csharp-sourcegenerator incremental-generator
Last synced: 24 days ago
JSON representation
C# incremental generator to create a method that returns the query string of the object.
- Host: GitHub
- URL: https://github.com/tparviainen/query-string-generator
- Owner: tparviainen
- License: mit
- Created: 2022-06-12T06:00:31.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2024-11-18T16:47:05.000Z (24 days ago)
- Last Synced: 2024-11-18T17:59:50.917Z (24 days ago)
- Topics: csharp-generator, csharp-sourcegenerator, incremental-generator
- Language: C#
- Homepage:
- Size: 70.3 KB
- Stars: 6
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- RSCG_Examples - https://github.com/tparviainen/query-string-generator
README
# Query String Generator
C# incremental generator to create a method that returns the query string of the object.
# Usage
## 1. Install the [NuGet](https://www.nuget.org/packages/QueryStringGenerator) package
```
PM> Install-Package QueryStringGenerator
```## 2. Update the Model(s)
Class must be decorated with `QueryString` attribute, which is declared in `QueryStringGenerator` namespace.
```csharp
using QueryStringGenerator;[QueryString]
public class Model
{
public int? Limit { get; set; }
public int? Offset { get; set; }
public string? Sort { get; set; }
}
```## 3. Call `ToQueryString` Method to the Instance of the Class
By default the generated method name is `ToQueryString`, which when called returns the query string of the object.
```csharp
var model = new Model
{
Limit = 10,
Sort = "Price"
};Console.WriteLine($"Query string: {model.ToQueryString()}");
/*
This code example produces the following results:Query string: &limit=10&sort=Price
*/
```# Generated Source Code
Below is the auto-generated extension method for the class defined in step 2. above.
```csharp
//namespace QueryStringGenerator.App.Models
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("QueryStringGenerator", "1.0.0")]
public static class QueryStringExtensionForModel
{
public static string ToQueryString(this Model _this)
{
if (_this == null)
{
return string.Empty;
}var sb = new global::System.Text.StringBuilder();
if (_this.Limit != null)
{
sb.Append($"&limit={_this.Limit}");
}if (_this.Offset != null)
{
sb.Append($"&offset={_this.Offset}");
}if (_this.Sort != null)
{
sb.Append($"&sort={System.Net.WebUtility.UrlEncode(_this.Sort)}");
}return sb.ToString();
}
}
}
```# Supported Data Types
- Nullable value types, including enums
- Reference types**NOTE:** The query string _value_ for enum is the name of the enum starting with a lowercase character.