• Stars
    star
    148
  • Rank 249,983 (Top 5 %)
  • Language
    C#
  • License
    MIT License
  • Created over 3 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A project which uses Source Generation to create a FluentBuilder for a specified model or DTO

Projects

See also these blogs:

CSharp.SourceGenerators.Extensions

See this page.

FluentBuilder

A project which uses Source Generation to create a FluentBuilder for a specified model or DTO.

This project is based on Tom Phan : "auto-generate-builders-using-source-generator-in-net-5".

Install

NuGet Badge

You can install from NuGet using the following command in the package manager window:

Install-Package FluentBuilder

Or via the Visual Studio NuGet package manager or if you use the dotnet command:

dotnet add package FluentBuilder

1️⃣ Usage on a existing class

Annotate a class

Annotate an existing class with [FluentBuilder.AutoGenerateBuilder] to indicate that a FluentBuilder should be generated for this class:

using FluentBuilder;

[AutoGenerateBuilder]
public class User
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTime? Date { get; set; }

    [FluentBuilderIgnore] // Add this attribute to ignore this property when generating a FluentBuilder.
    public int Age { get; set; }

    public int Answer { get; set; } = 42; // When a default value is set, this value is also set as default in the FluentBuilder.
}

AutoGenerateBuilder - attribute

This attribute has 4 arguments:

  • type (Type): The type for which to create the builder, see 'Define a class which needs to act as a builder'
  • handleBaseClasses (bool): Handle also base-classes. Default value is true.
  • accessibility (enum FluentBuilderAccessibility): Generate builder methods for Public or PublicAndPrivate. Default value when not provided is Public.
  • methods (enum FluentBuilderMethods): Generate With*** methods or also Without*** methods. Default value when not provided is WithOnly. See also Notes

Use FluentBuilder

using System;
using FluentBuilder;

namespace Test;

class Program
{
    static void Main(string[] args)
    {
        var user = new UserBuilder()
            .WithFirstName("Test")
            .WithLastName("User")
            .Build();

        Console.WriteLine($"{user.FirstName} {user.LastName}");
    }
}

Use FluentBuilder when the class has a default (parameter-less) constructor

using FluentBuilder;

[AutoGenerateBuilder]
public class User
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTime? Date { get; set; }

    public User()
    {
        FirstName = "test";
    }
}
using System;
using FluentBuilder;

namespace Test;

class Program
{
    static void Main(string[] args)
    {
        var user = new UserBuilder()
            .WithLastName("User")
            .Build(false); // ⭐ Provide `false` for `useObjectInitializer` here.

        Console.WriteLine($"{user.FirstName} {user.LastName}");
    }
}

Use FluentBuilder when the class has a constructor with parameters

using FluentBuilder;

[AutoGenerateBuilder]
public class User
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTime? Date { get; set; }

    public User(string first)
    {
        FirstName = first;
    }
}
using System;
using FluentBuilder;

namespace Test;

class Program
{
    static void Main(string[] args)
    {
        var user = new UserBuilder()
            .UsingConstructor("First")  // ⭐ Use `UsingConstructor` here.
            .WithLastName("User")
            .Build();

        Console.WriteLine($"{user.FirstName} {user.LastName}");
    }
}

Using FluentBuilder when a class has an Array or IEnumerable<T> property

using FluentBuilder;

[AutoGenerateBuilder]
public class UserDto
{
    public IEnumerable<EmailDto> SecondaryEmails { get; set; }

    public int[] IntArray { get; set; }
}
var user = new UserDtoBuilder()
    .WithIntArray(ib => ib         // 👈 Use a Integer Array Builder
        .Add(1)                    // Add a normal integer

        .Add(() => 2)              // Add an integer with a Func<>
        .Build()
    )
    .WithSecondaryEmails(sb => sb  // 👈 Use a EmailDto IEnumerable Builder
        .Add(new EmailDto())       // Add a normal EmailDto using new() constructor

        .Add(() => new EmailDto()) // Add an EmailDto using Func<>

        .Add(eb => eb              // 👈 Use a EmailDto IEnumerable Builder to add an EmailDto
            .WithPrimary(true)
            .Build()
        )
        .Build()
    )
    .Build();

Using FluentBuilder when a class has an IDictionary<TKey, TValue> property

using FluentBuilder;

[AutoGenerateBuilder]
public class UserDto
{
    public IDictionary<string, int> Tags { get; set; }
}
var user = new UserDtoBuilder()
    .WithTags(db => db      // 👈 Use a Dictionary<TKey, TValue> Builder
        .Add("test", 123)   // Add a key with value

        .Add(() => new KeyValuePair<string, int>("x", 42)) // Add a KeyValuePair with a Func<>
        .Build()
    )
    .Build();

2️⃣ Define a class which needs to act as a builder

This scenario is very usefull when you cannot modify the class to annotate it.

Create a public and partial builder class

And annotate this class with [AutoGenerateBuilder(typeof(XXX))] where XXX is the type for which you want to generate a FluentBuilder.

using FluentBuilder;

[AutoGenerateBuilder(typeof(UserDto))]
public partial class MyUserDtoBuilder
{
}

Use FluentBuilder

using System;
using FluentBuilder;

namespace Test;

class Program
{
    static void Main(string[] args)
    {
        var user = new MyUserDtoBuilder() // 👈 Just use your own Builder
            .WithFirstName("Test")
            .WithLastName("User")
            .Build();

        Console.WriteLine($"{user.FirstName} {user.LastName}");
    }
}

Extension Method

By default, the AsBuilder extension method is also generated which allows you to change an existing instance using the With-methods from the builder.

Example:

var user = await dbContext.Users.FirstAsync();

user = user.AsBuilder() // Lifts the user into a builder instance
    .WithLastName("Different LastName") // Updates "LastName" while keeping existing properties
    .Build(); // Changes are applied

await dbContext.SaveChangesAsync(); // User's LastName property is updated.

Notes

Since version 0.8.0, this FluentBuilder will only generate the With*** methods. If you want the builder to also generate the Without*** methods, add the enum FluentBuilderMethods.WithAndWithout to the attribute.

using FluentBuilder;

[AutoGenerateBuilder(typeof(UserDto), FluentBuilderMethods.WithAndWithout)]
public partial class MyUserDtoBuilder
{
}

More Repositories

1

SimMetrics.Net

SimMetrics is a Similarity Metric Library, e.g. from edit distance's (Levenshtein, Gotoh, Jaro etc) to other metrics, (e.g Soundex, Chapman). This library support multiple .NET versions including .NET Core (NETStandard 1.x)
C#
103
star
2

AnyOf

Use the AnyOf<TFirst, TSecond, ...> type to handle multiple defined types as input parameters or return values for methods.
C#
100
star
3

RandomDataGenerator

This is a configurable generator to create random data like Lorum Ipsum Text, Words, Text Patterns, First/Last Names, MAC-Addresses, IP-Addresses, Guids and DateTime.
C#
95
star
4

KendoGridBinderEx

This is a ModelBinder designed to consume an http request and build a json serializable object for the Kendo UI Grid datasource. AutoMapper is used to support mapping from ViewModel <> Entity.
C#
55
star
5

OpenSSL-X509Certificate2-Provider

Parses OpenSSL public and private key components and returns a X509Certificate2 with RSACryptoServiceProvider. Based on opensslkey
C#
51
star
6

ICSharpCode.TextEditorEx

Extended version based on ICSharpCode.TextEditor which support Search/Replace and Goto
C#
51
star
7

serverless-aws-lambda-typescript-examples

Examples for AWS Lambda functions created with the Serverless framework
JavaScript
49
star
8

angular-odata-es5

OData Service for Angular.io (es5 version)
TypeScript
44
star
9

NETStandard.HttpListener

HttpListener for .NET Core (NETStandard 1.3) and Universal Windows Platform (UWP)
HTML
39
star
10

MediaInfo.DotNetWrapper

A C# .NET Wrapper for the MediaInfo.Native and MediaInfo.dll
C#
35
star
11

XPath2.Net

Lightweight XPath2 for .NET
HTML
33
star
12

Howler.Blazor

A Blazor JSInterop wrapper for Howler.js.
C#
31
star
13

ProxyInterfaceSourceGenerator

This project uses Source Generation to generate an interface and a Proxy class for classes. This makes it possible to wrap external classes which do not have an interface, in a Proxy class which makes it easier to Mock and use Dependency Injection.
C#
30
star
14

DistributedCache.AzureTableStorage

IDistributedCache implementation for AzureTableStorage
C#
29
star
15

Blazor.DownloadFileFast

Fast download from files to the browser from Blazor without any javascript library reference or dependency.
C#
28
star
16

ReflectionBridge

ReflectionBridge : Provides some extensions which define a bridge for the differences between Type and TypeInfo.
C#
25
star
17

System.Text.Json.EnumExtensions

An extended version from the JsonStringEnumConverter which supports attributes like EnumMember, Display and Description
C#
24
star
18

RestEase-Client-Generator

A Visual Studio Extension to generate a RestEase compatible client based on a Swagger / OpenAPI specification files
C#
22
star
19

QueryInterceptor.Core

Provides a generic way to intercept IQueryable expression trees using custom expression visitors.
C#
21
star
20

GitHubReleaseNotes

Generate Release Notes in markdown format from GitHub projects using Oktokit and LibGit2Sharp.
C#
20
star
21

BlazorWasmGrpcWithAADAuth

Blazor + Wasm + Grpc + Azure AD Authentication
C#
18
star
22

jsMind.Blazor

A Blazor JSInterop wrapper for jsMind
JavaScript
17
star
23

WebDAV-AudioPlayer

An AudioPlayer based on CSCore to play music from a WebDAV location using WebDAV-Client
C#
15
star
24

Matroska

An Ebml based serializer to deserialize a Matroska file (.mkv or .webm)
C#
14
star
25

Replicate.Net

A C# RestEase client for Replicate (A latent text-to-image diffusion model capable of generating photo-realistic images given any text input).
C#
13
star
26

Blazor.WebAssembly.Authentication.Auth0

Blazor WebAssembly Auth0 Oidc Authentication with support for Audience
C#
11
star
27

GraphQL.EntityFrameworkCore.DynamicLinq

GraphQL extensions for EntityFrameworkCore.DynamicLinq to automatically configure the query arguments and execute the query
C#
10
star
28

ExcelFormulaParser

Excel Formula Parser
C#
9
star
29

HotChocolate.Data.Extensions

Contains some "IgnoreCase" String filters for eq, contains, endsWith and startsWith.
C#
9
star
30

PrimeNG-DataTable-Extensions

OData extensions for the PrimeNG DataTable
TypeScript
8
star
31

BlazorWasmGrpcWithAuth0

Blazor + Wasm + Grpc + Auth0 Authentication
C#
8
star
32

WebDAV-Client

An easy-to-use async WebDAV client for .NETStandard, Portable and .NET
C#
7
star
33

WSDLGenerator

A tool to generate a WSDL file from a C# DLL which contains one more Microsoft WebServices.
C#
7
star
34

Dutch-CoronaCheck-QR-Code-Decoder-and-Verifier

Decoding and verifying the Dutch CoronaCheck QR Code
C#
7
star
35

Blazor.YouTubeDownloader

Example Blazor WebAssemblyApp to download the Audio from a YouTube video
C#
6
star
36

Linq.PropertyTranslator.Core

This is a .NET Core port of the PropertyTranslator (https://github.com/peschuster/PropertyTranslator).
C#
6
star
37

CoverageConverter

Convert .coverage files (binary format) to .coveragexml (xml format) files to support SonarCloud code-coverage when using VSTest@2
C#
6
star
38

System.IO.EnhancedFileSystemWatcher

EnhancedFileSystemWatcher, which can be used to suppress duplicate events that fire on a single change to the file.
C#
5
star
39

OpenAI

OpenAI related projects
C#
5
star
40

Nethereum-CodeGenerator

A web based Generator which creates a Nethereum based C# Interface and Service based on Solidity Smart Contracts
EJS
5
star
41

QRCode

QR Code : Encoder, Decoder and Fixer
C#
5
star
42

DSMRParser.Example

An example on how to parse a P1 DSMR Telegram using .NET
C#
4
star
43

RamlToOpenApiConverter

Converts a RAML to Open API Specification (native C# dotnet)
C#
4
star
44

QboxNext

QboxNext is a modified clone of Qplatform, based on https://bitbucket.org/qboxnext/qboxnext
C#
4
star
45

Portable.ConcurrentDictionary

Portable, Silverlight 5.0 and Windows Phone Silverlight 8.0 & 8.1 implementation of the ConcurrentDictionary
C#
4
star
46

FileWatcher

FileWatcher
C#
4
star
47

JsonConverter

Common interface for Json Converters (Newtonsoft.Json & System.Text.Json & SimpleJson)
C#
4
star
48

Pulumi.Azure.Constants

Additional constants for creating and configuring Microsoft Azure resources with Pulumi.Azure
C#
4
star
49

System.AppDomain.Core

A replacement for AppDomain.CurrentDomain.GetAssemblies() call which is not present for NetCoreApp/NetStandard.
C#
4
star
50

UZipDotNet

This project will give you the tools needed to compress and decompress files using the Deflate method of compression, and to read and write standard Zip files. The source is copied from http://www.codeproject.com/Articles/359758/Processing-Standard-Zip-Files-with-Csharp-compress. The original license is CPOL by the author is Uzi Granot.
C#
4
star
51

ProtoBufJsonConverter

Convert a protobuf message to a JSON string or object using the proto definition file.
C#
4
star
52

dotnetcore-windows-service

A .NET Core Windows Service example
C#
3
star
53

AspNetCore.Security.Auth0

AspNetCore.Security.Auth0
C#
3
star
54

EmbeddedImageGrabber

Extracting Embedded Images from an Assembly
C#
3
star
55

PactExample

Some examples for Pact.Net and WireMock.Net
C#
3
star
56

ghaction-CompressFiles

A GitHub Action for compressing files using Brotli or GZip
Shell
3
star
57

Stef.Validation

Guard methods for argument validation (NotNull, NotEmpty, ...)
C#
3
star
58

CoronaDashboard

Een Corona Dashboard gebaseerd op cijfers van Nederland gemaakt in Blazor en Blazorise
C#
2
star
59

Solidity-Examples

Solidity SmartContract Examples
C#
2
star
60

System.Linq.Dynamic.Core.TestApps

System.Linq.Dynamic.Core.TestApps
C#
2
star
61

bower-kendo-ui-web

Bower package for KendoUIWeb (2014.1.318)
2
star
62

LongGuid

A LongGuid solution with 512 bits per identifier as opposed to the default 128 bits.
C#
2
star
63

MyDbUtils

Generate script file from a MSSQL database to create or alter: Stored Procedures, Functions, Views and Triggers
C#
2
star
64

HotChocolateExample

HotChocolate Example
C#
2
star
65

BlazorAppHandlebarsDemo

BlazorApp WASM Handlebars.Net.Helpers Demo
HTML
2
star
66

FluentValidation.Extensions.AutoMapper

FluentValidation Extensions for AutoMapper
C#
1
star
67

CloudBerryDecrypter

CloudBerryDecrypter
C#
1
star
68

BlazorDragAndDrop

BlazorDragAndDrop Demo
C#
1
star
69

string-split-join

StringUtils for splitting and joining strings with support for separatorCharacter and escapeCharacter.
TypeScript
1
star
70

KubernetesExample

A example project about Kubernetes and C# WebApi
C#
1
star
71

Infura.io-api

API for Infura.io based on RestEase
C#
1
star
72

JPush.NET

JPush.NET is SDK for .NET for sending and monitoring JPush messages, following JPush official REST API V2 and V3.
C#
1
star
73

AmazonS3CreatePreSignedUrlExample

AmazonS3 Example for "Create PreSignedUrl with Expire date"
C#
1
star
74

Span.ReaderWriter

SpanReader and SpanWriter which wraps a `Span<byte>` and provide a convenient functionality for reading and writing.
C#
1
star
75

ASPNetCoreGraphQL

ASPNetCore GraphQL Example
C#
1
star
76

ghaction-BlazorWebAssemblyFileHashFixer

GitHub Action to fix the sha256 file-hashes from the resources defined in "blazor.boot.json" and "service-worker-assets.js".
JavaScript
1
star
77

AzurePipelinesTest3

AzurePipelines Example project to show build errors for net35 and uap10
C#
1
star
78

Linq.Expression.Optimizer.Core

This is a .NETCore / NETStandard port from https://github.com/Thorium/Linq.Expression.Optimizer
F#
1
star
79

RestEaseExamples

RestEase examples
C#
1
star
80

SmartContractFunction

An Azure Function to call Ethereum Smart Contracts
C#
1
star
81

WebApplicationStructureMap

WebApplication (WebAPI ) with StructureMap
C#
1
star
82

PdfUtils

Some Pdf Utilities
HTML
1
star