RSCG – QueryStringGenerator

RSCG – QueryStringGenerator
 
 

name QueryStringGenerator
nuget https://www.nuget.org/packages/QueryStringGenerator/
link https://github.com/tparviainen/query-string-generator
author Tomi Parviainen

Generate from string properties of a class a query string for a URL.

 

This is how you can use QueryStringGenerator .

The code that you start with is


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="QueryStringGenerator" Version="1.1.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>
	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>
</Project>


The code that you will use is


using DemoQuery;
Person p = new();
p.FirstName = "Andrei";
p.LastName = "Ignat";
p.Age = 55;
Console.WriteLine(p.ToQueryString());


using QueryStringGenerator;
namespace DemoQuery;
[QueryString]
internal class Person
{
    public string FirstName { get; set; }=string.Empty;
    public int Age {  get; set; }
    public string LastName { get; set; } = string.Empty;

}


 

The code that is generated is

// <auto-generated />

namespace DemoQuery
{
    [System.CodeDom.Compiler.GeneratedCodeAttribute("QueryStringGenerator", "1.0.0")]
    internal static class QueryStringExtensionForPerson
    {
        public static string ToQueryString(this Person _this)
        {
            if (_this == null)
            {
                return string.Empty;
            }

            var sb = new System.Text.StringBuilder();

            if (_this.FirstName != null)
            {
                sb.Append($"&firstname={System.Net.WebUtility.UrlEncode(_this.FirstName)}");
            }

            if (_this.LastName != null)
            {
                sb.Append($"&lastname={System.Net.WebUtility.UrlEncode(_this.LastName)}");
            }

            return sb.ToString();
        }
    }
}

// <auto-generated />

namespace QueryStringGenerator
{
    [System.CodeDom.Compiler.GeneratedCodeAttribute("QueryStringGenerator", "1.0.0")]
    internal class QueryStringAttribute : System.Attribute
    {
        public string MethodName { get; set; }

        public QueryStringAttribute(string methodName = "ToQueryString")
        {
            MethodName = methodName;
        }
    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/QueryStringGenerator