RSCG – Breezy

RSCG – Breezy
 
 

name Breezy
nuget https://www.nuget.org/packages/Breezy.SourceGenerator/
link https://github.com/Ludovicdln/Breezy
author Ludovicdln

ORM Mapper

 

This is how you can use Breezy .

The code that you start with is


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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>
	<ItemGroup>
	  <PackageReference Include="Breezy.SourceGenerator" Version="1.0.1"  OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
	  <PackageReference Include="Microsoft.Data.SqlClient" Version="5.1.1" />
	</ItemGroup>
</Project>


The code that you will use is



using var connection = new SqlConnection();
//in the order of the properties in Person.cs
var persons = await connection.QueryAsync<Person>("SELECT Id,firstname, lastname FROM person");



namespace BreezyDemo;

[Table("person")]//this is Breezy.Table
public class Person
{
    public int ID { get; set; }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
}



global using Breezy;
global using Microsoft.Data.SqlClient;
global using BreezyDemo;


 

The code that is generated is

// <auto-generated /> 
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace DbConnectionExtensions
{
    public static class DbConnectionExtensions
    {
        /// <summary>
        /// Execute a command asynchronously using Task.
        /// </summary>       
        /// <param name = "sql">The SQL to execute for the query.</param>
        /// <returns>The number of rows affected.</returns>
        public static async Task<int> ExecuteAsync(this DbConnection connection, string sql, CancellationToken cancellationToken = default)
        {
            bool wasClosed = connection.State == ConnectionState.Closed;
            if (wasClosed)
                await connection.OpenAsync(cancellationToken);
            await using var command = connection.CreateCommand();
            command.CommandText = sql;
            try
            {
                return await command.ExecuteNonQueryAsync(cancellationToken);
            }
            finally
            {
                if (wasClosed)
                    connection.Close();
            }
        }

        /// <summary>
        /// Execute a command asynchronously using Task.
        /// </summary>       
        /// <param name = "sql">The SQL to execute for the query.</param>
        /// <param name = "param">The parameters to pass, if any.</param>
        /// <returns>The number of rows affected.</returns>
        public static async Task<int> ExecuteAsync(this DbConnection connection, string sql, object param, CancellationToken cancellationToken = default)
        {
            bool wasClosed = connection.State == ConnectionState.Closed;
            if (wasClosed)
                await connection.OpenAsync(cancellationToken);
            await using var command = connection.CreateCommand();
            command.CommandText = sql;
            foreach (var property in param.GetType().GetProperties())
            {
                var parameter = command.CreateParameter();
                parameter.ParameterName = "@" + property.Name;
                parameter.Value = property.GetValue(param);
                command.Parameters.Add(parameter);
            }

            try
            {
                return await command.ExecuteNonQueryAsync(cancellationToken);
            }
            finally
            {
                if (wasClosed)
                    connection.Close();
            }
        }

        /// <summary>
        /// Execute a command asynchronously using Task.
        /// </summary>       
        /// <param name = "sql">The SQL to execute for the query.</param>
        /// <param name = "transaction">The transaction to use for this query.</param>
        /// <returns>The number of rows affected.</returns>
        public static async Task<int[]> ExecuteAsync(this DbConnection connection, string[] sql, DbTransaction transaction, CancellationToken cancellationToken = default)
        {
            bool wasClosed = connection.State == ConnectionState.Closed;
            if (wasClosed)
                await connection.OpenAsync(cancellationToken);
            var commands = new DbCommand[sql.Length];
            for (var i = 0; i < sql.Length; i++)
            {
                await using var command = connection.CreateCommand();
                command.CommandText = sql[i];
                command.Transaction = transaction;
                commands[i] = command;
            }

            try
            {
                var results = new int[sql.Length];
                for (var i = 0; i < commands.Length; i++)
                    results[i] = await commands[i].ExecuteNonQueryAsync(cancellationToken);
                await transaction.CommitAsync();
                return results;
            }
            catch (DbException e)
            {
                await transaction.RollbackAsync();
                return Array.Empty<int>();
            }
            finally
            {
                transaction.Dispose();
                if (wasClosed)
                    connection.Close();
            }
        }

        /// <summary>
        /// Execute a command asynchronously using Task.
        /// </summary>       
        /// <param name = "sql">The SQL to execute for the query.</param>
        /// <param name = "param">The parameters to pass, if any.</param>
        /// <param name = "transaction">The transaction to use for this query.</param>
        /// <returns>The number of rows affected.</returns>
        public static async Task<int[]> ExecuteAsync(this DbConnection connection, string[] sql, object[] param, DbTransaction transaction, CancellationToken cancellationToken = default)
        {
            bool wasClosed = connection.State == ConnectionState.Closed;
            if (wasClosed)
                await connection.OpenAsync(cancellationToken);
            var commands = new DbCommand[sql.Length];
            for (var i = 0; i < sql.Length; i++)
            {
                await using var command = connection.CreateCommand();
                command.CommandText = sql[i];
                command.Transaction = transaction;
                var paramt = param[i];
                foreach (var property in paramt.GetType().GetProperties())
                {
                    var parameter = command.CreateParameter();
                    parameter.ParameterName = "@" + property.Name;
                    parameter.Value = property.GetValue(paramt);
                    command.Parameters.Add(parameter);
                }

                commands[i] = command;
            }

            try
            {
                var results = new int[sql.Length];
                for (var i = 0; i < commands.Length; i++)
                    results[i] = await commands[i].ExecuteNonQueryAsync(cancellationToken);
                await transaction.CommitAsync();
                return results;
            }
            catch (DbException e)
            {
                await transaction.RollbackAsync();
                return Array.Empty<int>();
            }
            finally
            {
                transaction.Dispose();
                if (wasClosed)
                    connection.Close();
            }
        }
    }
}
// <auto-generated />
using System;

namespace Breezy;

public interface ICacheableQuery<T> where T : class
{
	public Task<IEnumerable<T>> GetCacheableResultsAsync(IdentityQuery identityQuery);
	public Task SetCacheableResultsAsync(IdentityQuery identityQuery, IEnumerable<T> results);
}	
		// <auto-generated />
		using System;

		namespace Breezy;

		public class IdentityQuery : IEquatable<IdentityQuery>        
        {
            private readonly int _hashCodeSql;
            private readonly int? _hashCodeParam;
            public IdentityQuery(string sql, object? param = null) => (_hashCodeSql, _hashCodeParam) = (sql.GetHashCode(), param?.GetHashCode());
            public bool Equals(IdentityQuery? other)
            {
                if (ReferenceEquals(other, this)) return true;
                return this.GetHashCode() == other?.GetHashCode();
            }
            public override string ToString() 
                => $"{_hashCodeSql.ToString()}-{_hashCodeParam?.ToString()}";
            public override bool Equals(object? obj)      
                => Equals(obj as IdentityQuery);          
            public override int GetHashCode()         
                => HashCode.Combine(_hashCodeSql, _hashCodeParam);    
        }   
// <auto-generated /> 
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace BreezyDemo
{
    public static class PersonExtensions
    {
        /// <summary>
        /// Execute a query asynchronously using Task.
        /// </summary>
        /// <typeparam name = "T">The type of results to return.</typeparam>
        /// <param name = "sql">The SQL to execute for the query.</param>
        /// <param name = "cancellationToken">The cancellation token for this command.</param>
        /// <returns>
        /// A sequence of data of <typeparamref name = "T"/>;
        /// </returns>
        public static async Task<IEnumerable<Person>> QueryAsync<T>(this DbConnection connection, string sql, CancellationToken cancellationToken = default)
            where T : Person
        {
            bool wasClosed = connection.State == ConnectionState.Closed;
            if (wasClosed)
                await connection.OpenAsync(cancellationToken);
            await using var command = connection.CreateCommand();
            command.CommandText = sql;
            await using var reader = await command.ExecuteReaderAsync(cancellationToken: cancellationToken);
            var persons = new Dictionary<int, Person>();
            try
            {
                while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
                {
                    Person person = null;
                    var person1Id = reader.IsDBNull(0) ? default : reader.GetInt32(0);
                    if (!persons.TryGetValue(person1Id, out person))
                    {
                        person = new Person()
                        {
                            ID = person1Id,
                            FirstName = reader.IsDBNull(1) ? default : reader.GetString(1),
                            LastName = reader.IsDBNull(2) ? default : reader.GetString(2),
                        };
                        persons.Add(person1Id, person);
                    }
                }

                return persons.Values;
            }
            finally
            {
                reader.Close();
                if (wasClosed)
                    connection.Close();
            }
        }

        /// <summary>
        /// Execute a query asynchronously using Task.
        /// </summary>
        /// <typeparam name = "T">The type of results to return.</typeparam>
        /// <param name = "sql">The SQL to execute for the query.</param>
        /// <param name = "param">The parameters to pass, if any.</param>
        /// <param name = "cancellationToken">The cancellation token for this command.</param>
        /// <returns>
        /// A sequence of data of <typeparamref name = "T"/>;
        /// </returns>
        public static async Task<IEnumerable<Person>> QueryAsync<T>(this DbConnection connection, string sql, object param, CancellationToken cancellationToken = default)
            where T : Person
        {
            bool wasClosed = connection.State == ConnectionState.Closed;
            if (wasClosed)
                await connection.OpenAsync(cancellationToken);
            await using var command = connection.CreateCommand();
            command.CommandText = sql;
            foreach (var property in param.GetType().GetProperties())
            {
                var parameter = command.CreateParameter();
                parameter.ParameterName = "@" + property.Name;
                parameter.Value = property.GetValue(param);
                command.Parameters.Add(parameter);
            }

            await using var reader = await command.ExecuteReaderAsync(cancellationToken: cancellationToken);
            var persons = new Dictionary<int, Person>();
            try
            {
                while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
                {
                    Person person = null;
                    var person1Id = reader.IsDBNull(0) ? default : reader.GetInt32(0);
                    if (!persons.TryGetValue(person1Id, out person))
                    {
                        person = new Person()
                        {
                            ID = person1Id,
                            FirstName = reader.IsDBNull(1) ? default : reader.GetString(1),
                            LastName = reader.IsDBNull(2) ? default : reader.GetString(2),
                        };
                        persons.Add(person1Id, person);
                    }
                }

                return persons.Values;
            }
            finally
            {
                reader.Close();
                if (wasClosed)
                    connection.Close();
            }
        }

        /// <summary>
        /// Execute a query asynchronously using Task.
        /// </summary>
        /// <typeparam name = "T">The type of results to return.</typeparam>
        /// <param name = "sql">The SQL to execute for the query.</param>
        /// <param name = "cacheableQuery">The cache that you need to impl, if you want to be faster.</param>
        /// <param name = "cancellationToken">The cancellation token for this command.</param>
        /// <returns>
        /// A sequence of data of <typeparamref name = "T"/>;
        /// </returns>
        public static async Task<IEnumerable<Person>> QueryAsync<T>(this DbConnection connection, string sql, ICacheableQuery<Person> cacheableQuery, CancellationToken cancellationToken = default)
            where T : Person
        {
            bool wasClosed = connection.State == ConnectionState.Closed;
            if (wasClosed)
                await connection.OpenAsync(cancellationToken);
            await using var command = connection.CreateCommand();
            command.CommandText = sql;
            var identityQuery = new IdentityQuery(sql);
            var cacheableResults = await cacheableQuery.GetCacheableResultsAsync(identityQuery);
            if (cacheableResults.Any())
                return cacheableResults;
            await using var reader = await command.ExecuteReaderAsync(cancellationToken: cancellationToken);
            var persons = new Dictionary<int, Person>();
            try
            {
                while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
                {
                    Person person = null;
                    var person1Id = reader.IsDBNull(0) ? default : reader.GetInt32(0);
                    if (!persons.TryGetValue(person1Id, out person))
                    {
                        person = new Person()
                        {
                            ID = person1Id,
                            FirstName = reader.IsDBNull(1) ? default : reader.GetString(1),
                            LastName = reader.IsDBNull(2) ? default : reader.GetString(2),
                        };
                        persons.Add(person1Id, person);
                    }
                }

                await cacheableQuery.SetCacheableResultsAsync(identityQuery, persons.Values);
                return persons.Values;
            }
            finally
            {
                reader.Close();
                if (wasClosed)
                    connection.Close();
            }
        }

        /// <summary>
        /// Execute a query asynchronously using Task.
        /// </summary>
        /// <typeparam name = "T">The type of results to return.</typeparam>
        /// <param name = "sql">The SQL to execute for the query.</param>
        /// <param name = "param">The parameters to pass, if any.</param>
        /// <param name = "cacheableQuery">The cache that you need to impl, if you want to be faster.</param>
        /// <param name = "cancellationToken">The cancellation token for this command.</param>
        /// <returns>
        /// A sequence of data of <typeparamref name = "T"/>;
        /// </returns>
        public static async Task<IEnumerable<Person>> QueryAsync<T>(this DbConnection connection, string sql, object param, ICacheableQuery<Person> cacheableQuery, CancellationToken cancellationToken = default)
            where T : Person
        {
            bool wasClosed = connection.State == ConnectionState.Closed;
            if (wasClosed)
                await connection.OpenAsync(cancellationToken);
            await using var command = connection.CreateCommand();
            command.CommandText = sql;
            foreach (var property in param.GetType().GetProperties())
            {
                var parameter = command.CreateParameter();
                parameter.ParameterName = "@" + property.Name;
                parameter.Value = property.GetValue(param);
                command.Parameters.Add(parameter);
            }

            var identityQuery = new IdentityQuery(sql);
            var cacheableResults = await cacheableQuery.GetCacheableResultsAsync(identityQuery);
            if (cacheableResults.Any())
                return cacheableResults;
            await using var reader = await command.ExecuteReaderAsync(cancellationToken: cancellationToken);
            var persons = new Dictionary<int, Person>();
            try
            {
                while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
                {
                    Person person = null;
                    var person1Id = reader.IsDBNull(0) ? default : reader.GetInt32(0);
                    if (!persons.TryGetValue(person1Id, out person))
                    {
                        person = new Person()
                        {
                            ID = person1Id,
                            FirstName = reader.IsDBNull(1) ? default : reader.GetString(1),
                            LastName = reader.IsDBNull(2) ? default : reader.GetString(2),
                        };
                        persons.Add(person1Id, person);
                    }
                }

                await cacheableQuery.SetCacheableResultsAsync(identityQuery, persons.Values);
                return persons.Values;
            }
            finally
            {
                reader.Close();
                if (wasClosed)
                    connection.Close();
            }
        }

        /// <summary>
        /// Execute a single-row query asynchronously using Task.
        /// </summary>
        /// <typeparam name = "T">The type of result to return.</typeparam>
        /// <param name = "sql">The SQL to execute for the query.</param>
        /// <param name = "cancellationToken">The cancellation token for this command.</param>
        /// <returns>
        /// A first sequence of data of <typeparamref name = "T"/>;
        /// </returns>
        public static async Task<Person?> QueryFirstOrDefaultAsync<T>(this DbConnection connection, string sql, CancellationToken cancellationToken = default)
            where T : Person
        {
            return (await connection.QueryAsync<Person>(sql, cancellationToken)).FirstOrDefault();
        }

        /// <summary>
        /// Execute a single-row query asynchronously using Task.
        /// </summary>
        /// <typeparam name = "T">The type of result to return.</typeparam>
        /// <param name = "sql">The SQL to execute for the query.</param>
        /// <param name = "param">The parameters to pass, if any.</param>
        /// <param name = "cancellationToken">The cancellation token for this command.</param>
        /// <returns>
        /// A first sequence of data of <typeparamref name = "T"/>;
        /// </returns>
        public static async Task<Person?> QueryFirstOrDefaultAsync<T>(this DbConnection connection, string sql, object param, CancellationToken cancellationToken = default)
            where T : Person
        {
            return (await connection.QueryAsync<Person>(sql, param, cancellationToken)).FirstOrDefault();
        }

        /// <summary>
        /// Execute a single-row query asynchronously using Task.
        /// </summary>
        /// <typeparam name = "T">The type of result to return.</typeparam>
        /// <param name = "sql">The SQL to execute for the query.</param>
        /// <param name = "cacheableQuery">The cache that you need to impl, if you want to be faster.</param>
        /// <param name = "cancellationToken">The cancellation token for this command.</param>
        /// <returns>
        /// A first sequence of data of <typeparamref name = "T"/>;
        /// </returns>
        public static async Task<Person?> QueryFirstOrDefaultAsync<T>(this DbConnection connection, string sql, ICacheableQuery<Person> cacheableQuery, CancellationToken cancellationToken = default)
            where T : Person
        {
            return (await connection.QueryAsync<Person>(sql, cacheableQuery, cancellationToken)).FirstOrDefault();
        }

        /// <summary>
        /// Execute a single-row query asynchronously using Task.
        /// </summary>
        /// <typeparam name = "T">The type of result to return.</typeparam>
        /// <param name = "sql">The SQL to execute for the query.</param>
        /// <param name = "param">The parameters to pass, if any.</param>
        /// <param name = "cacheableQuery">The cache that you need to impl, if you want to be faster.</param>
        /// <param name = "cancellationToken">The cancellation token for this command.</param>
        /// <returns>
        /// A first sequence of data of <typeparamref name = "T"/>;
        /// </returns>
        public static async Task<Person?> QueryFirstOrDefaultAsync<T>(this DbConnection connection, string sql, object param, ICacheableQuery<Person> cacheableQuery, CancellationToken cancellationToken = default)
            where T : Person
        {
            return (await connection.QueryAsync<Person>(sql, param, cacheableQuery, cancellationToken)).FirstOrDefault();
        }
    }
}
// <auto-generated />
using System;

namespace Breezy;

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class SplitOnAttribute : Attribute
{
	public int[] Index { get; init; }

	public SplitOnAttribute(params int[] index) => Index = index ?? throw new ArgumentNullException("index not defined"); 
}
// <auto-generated />
using System;

namespace Breezy;

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class TableAttribute : Attribute
{
	public string Name { get; init; }

	public TableAttribute(string name) => Name = name ?? throw new ArgumentNullException(name); 
}

Code and pdf at

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

RSCG – EnumClass

RSCG – EnumClass
 
 

name EnumClass
nuget https://www.nuget.org/packages/EnumClass.Generator/
link https://github.com/ashenBlade/EnumClass
author ashen.Blade

enum 2 class

 

This is how you can use EnumClass .

The code that you start with is


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

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

  <ItemGroup>
    <PackageReference Include="EnumClass.Generator" Version="1.3.0" OutputItemType="Analyzer" />
  </ItemGroup>
	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>
</Project>


The code that you will use is


// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

Console.WriteLine(EnumClassDemo.EnumClass.Colors.None.ToString());
Console.WriteLine(EnumClassDemo.EnumClass.Colors.Red.TestMe());



using EnumClass.Attributes;

namespace EnumClassDemo;
[EnumClass]
public enum Colors
{
    None=0,
    Red,
    Green,
    Blue,
}



namespace EnumClassDemo.EnumClass;
public abstract partial class Colors
{
    public partial class RedEnumValue
    {
        public string? TestMe()
        {
            return ToString();
        }
    }
}

 

The code that is generated is

#nullable enable

using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace EnumClassDemo.EnumClass
{

public abstract partial class Colors: IEquatable<Colors>, IEquatable<global::EnumClassDemo.Colors>, IComparable<Colors>, IComparable<global::EnumClassDemo.Colors>, IComparable
{
    protected readonly global::EnumClassDemo.Colors _realEnumValue;

    protected Colors(global::EnumClassDemo.Colors enumValue)
    {
        this._realEnumValue = enumValue;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static explicit operator global::EnumClassDemo.Colors(Colors value)
    {
        return value._realEnumValue;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static implicit operator int(Colors value)
    {
        return (int) value._realEnumValue;
    }

    public bool Equals(Colors? other)
    {
        return !ReferenceEquals(other, null) && other._realEnumValue == this._realEnumValue;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public bool Equals(global::EnumClassDemo.Colors other)
    {
        return other == this._realEnumValue;
    }

    public override bool Equals(object? other)
    {
        if (ReferenceEquals(other, null)) return false;
        if (ReferenceEquals(other, this)) return true;
        if (other is Colors)
        {
            return this.Equals((Colors) other);
        }
        if (other is global::EnumClassDemo.Colors)
        {
            return this.Equals((global::EnumClassDemo.Colors) other);
        }
        return false;
    }

    public static bool operator ==(Colors left, global::EnumClassDemo.Colors right)
    {
        return left.Equals(right);
    }

    public static bool operator !=(Colors left, global::EnumClassDemo.Colors right)
    {
        return !left.Equals(right);
    }

    public static bool operator ==(global::EnumClassDemo.Colors left, Colors right)
    {
        return right.Equals(left);
    }

    public static bool operator !=(global::EnumClassDemo.Colors left, Colors right)
    {
        return !right.Equals(left);
    }

    public static bool operator ==(Colors left, Colors right)
    {
        return !ReferenceEquals(left, null) && left.Equals(right);
    }

    public static bool operator !=(Colors left, Colors right)
    {
        return ReferenceEquals(left, null) || !left.Equals(right);
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public override int GetHashCode()
    {
        return this._realEnumValue.GetHashCode();
    }

    public static bool TryParse(string value, out Colors? colors)
    {
        switch (value)
        {
            case "None":
                colors = None;
                return true;
            case "Red":
                colors = Red;
                return true;
            case "Green":
                colors = Green;
                return true;
            case "Blue":
                colors = Blue;
                return true;
            case "Colors.None":
                colors = None;
                return true;
            case "Colors.Red":
                colors = Red;
                return true;
            case "Colors.Green":
                colors = Green;
                return true;
            case "Colors.Blue":
                colors = Blue;
                return true;
        }
        colors = null;
        return false;
    }


    public static bool TryParse(int value, out Colors? colors)
    {
        switch (value)
        {
            case 0:
                colors = None;
                return true;
            case 1:
                colors = Red;
                return true;
            case 2:
                colors = Green;
                return true;
            case 3:
                colors = Blue;
                return true;
        }
        colors = null;
        return false;
    }


    public int CompareTo(object? other)
    {
        if (ReferenceEquals(this, other)) return 0;
        if (ReferenceEquals(null, other)) return 1;
        if (other is Colors)
        {
            Colors temp = (Colors) other;
            int left = ((int)this._realEnumValue);
            int right = ((int)temp._realEnumValue);
            return left < right ? -1 : left == right ? 0 : 1;
        }
        if (other is global::EnumClassDemo.Colors)
        {
            int left = ((int)this._realEnumValue);
            int right = ((int)other);
            return left < right ? -1 : left == right ? 0 : 1;
        }
        throw new ArgumentException($"Object to compare must be either {typeof(Colors)} or {typeof(global::EnumClassDemo.Colors)}. Given type: {other.GetType()}", "other");
    }

    public int CompareTo(Colors? other)
    {
        if (ReferenceEquals(this, other)) return 0;
        if (ReferenceEquals(null, other)) return 1;
            int left = ((int)this._realEnumValue);
            int right = ((int)other._realEnumValue);
            return left < right ? -1 : left == right ? 0 : 1;
    }

    public int CompareTo(global::EnumClassDemo.Colors other)
    {
            int left = ((int)this._realEnumValue);
            int right = ((int)other);
            return left < right ? -1 : left == right ? 0 : 1;
    }

    public abstract void Switch(Action<NoneEnumValue> noneSwitch, Action<RedEnumValue> redSwitch, Action<GreenEnumValue> greenSwitch, Action<BlueEnumValue> blueSwitch);
    public abstract TResult Switch<TResult>(Func<NoneEnumValue, TResult> noneSwitch, Func<RedEnumValue, TResult> redSwitch, Func<GreenEnumValue, TResult> greenSwitch, Func<BlueEnumValue, TResult> blueSwitch);
    public abstract void Switch<T0>(T0 arg0, Action<NoneEnumValue, T0> noneSwitch, Action<RedEnumValue, T0> redSwitch, Action<GreenEnumValue, T0> greenSwitch, Action<BlueEnumValue, T0> blueSwitch);
    public abstract TResult Switch<TResult, T0>(T0 arg0, Func<NoneEnumValue, T0, TResult> noneSwitch, Func<RedEnumValue, T0, TResult> redSwitch, Func<GreenEnumValue, T0, TResult> greenSwitch, Func<BlueEnumValue, T0, TResult> blueSwitch);
    public abstract void Switch<T0, T1>(T0 arg0, T1 arg1, Action<NoneEnumValue, T0, T1> noneSwitch, Action<RedEnumValue, T0, T1> redSwitch, Action<GreenEnumValue, T0, T1> greenSwitch, Action<BlueEnumValue, T0, T1> blueSwitch);
    public abstract TResult Switch<TResult, T0, T1>(T0 arg0, T1 arg1, Func<NoneEnumValue, T0, T1, TResult> noneSwitch, Func<RedEnumValue, T0, T1, TResult> redSwitch, Func<GreenEnumValue, T0, T1, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, TResult> blueSwitch);
    public abstract void Switch<T0, T1, T2>(T0 arg0, T1 arg1, T2 arg2, Action<NoneEnumValue, T0, T1, T2> noneSwitch, Action<RedEnumValue, T0, T1, T2> redSwitch, Action<GreenEnumValue, T0, T1, T2> greenSwitch, Action<BlueEnumValue, T0, T1, T2> blueSwitch);
    public abstract TResult Switch<TResult, T0, T1, T2>(T0 arg0, T1 arg1, T2 arg2, Func<NoneEnumValue, T0, T1, T2, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, TResult> blueSwitch);
    public abstract void Switch<T0, T1, T2, T3>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, Action<NoneEnumValue, T0, T1, T2, T3> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3> blueSwitch);
    public abstract TResult Switch<TResult, T0, T1, T2, T3>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, Func<NoneEnumValue, T0, T1, T2, T3, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, TResult> blueSwitch);
    public abstract void Switch<T0, T1, T2, T3, T4>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Action<NoneEnumValue, T0, T1, T2, T3, T4> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4> blueSwitch);
    public abstract TResult Switch<TResult, T0, T1, T2, T3, T4>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Func<NoneEnumValue, T0, T1, T2, T3, T4, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, TResult> blueSwitch);
    public abstract void Switch<T0, T1, T2, T3, T4, T5>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Action<NoneEnumValue, T0, T1, T2, T3, T4, T5> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4, T5> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4, T5> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4, T5> blueSwitch);
    public abstract TResult Switch<TResult, T0, T1, T2, T3, T4, T5>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Func<NoneEnumValue, T0, T1, T2, T3, T4, T5, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, T5, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, T5, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, T5, TResult> blueSwitch);
    public abstract void Switch<T0, T1, T2, T3, T4, T5, T6>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Action<NoneEnumValue, T0, T1, T2, T3, T4, T5, T6> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4, T5, T6> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4, T5, T6> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4, T5, T6> blueSwitch);
    public abstract TResult Switch<TResult, T0, T1, T2, T3, T4, T5, T6>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Func<NoneEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> blueSwitch);

    public static readonly NoneEnumValue None = new NoneEnumValue();
    public partial class NoneEnumValue: Colors
    {
        public NoneEnumValue(): base(global::EnumClassDemo.Colors.None) { }
        public override string ToString()
        {
            return "None";
        }

        public override void Switch(Action<NoneEnumValue> noneSwitch, Action<RedEnumValue> redSwitch, Action<GreenEnumValue> greenSwitch, Action<BlueEnumValue> blueSwitch)
        {
            noneSwitch(this);
        }

        public override TResult Switch<TResult>(Func<NoneEnumValue, TResult> noneSwitch, Func<RedEnumValue, TResult> redSwitch, Func<GreenEnumValue, TResult> greenSwitch, Func<BlueEnumValue, TResult> blueSwitch)
        {
            return noneSwitch(this);
        }

        public override void Switch<T0>(T0 arg0, Action<NoneEnumValue, T0> noneSwitch, Action<RedEnumValue, T0> redSwitch, Action<GreenEnumValue, T0> greenSwitch, Action<BlueEnumValue, T0> blueSwitch)
        {
            noneSwitch(this, arg0);
        }

        public override TResult Switch<TResult, T0>(T0 arg0, Func<NoneEnumValue, T0, TResult> noneSwitch, Func<RedEnumValue, T0, TResult> redSwitch, Func<GreenEnumValue, T0, TResult> greenSwitch, Func<BlueEnumValue, T0, TResult> blueSwitch)
        {
            return noneSwitch(this, arg0);
        }

        public override void Switch<T0, T1>(T0 arg0, T1 arg1, Action<NoneEnumValue, T0, T1> noneSwitch, Action<RedEnumValue, T0, T1> redSwitch, Action<GreenEnumValue, T0, T1> greenSwitch, Action<BlueEnumValue, T0, T1> blueSwitch)
        {
            noneSwitch(this, arg0, arg1);
        }

        public override TResult Switch<TResult, T0, T1>(T0 arg0, T1 arg1, Func<NoneEnumValue, T0, T1, TResult> noneSwitch, Func<RedEnumValue, T0, T1, TResult> redSwitch, Func<GreenEnumValue, T0, T1, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, TResult> blueSwitch)
        {
            return noneSwitch(this, arg0, arg1);
        }

        public override void Switch<T0, T1, T2>(T0 arg0, T1 arg1, T2 arg2, Action<NoneEnumValue, T0, T1, T2> noneSwitch, Action<RedEnumValue, T0, T1, T2> redSwitch, Action<GreenEnumValue, T0, T1, T2> greenSwitch, Action<BlueEnumValue, T0, T1, T2> blueSwitch)
        {
            noneSwitch(this, arg0, arg1, arg2);
        }

        public override TResult Switch<TResult, T0, T1, T2>(T0 arg0, T1 arg1, T2 arg2, Func<NoneEnumValue, T0, T1, T2, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, TResult> blueSwitch)
        {
            return noneSwitch(this, arg0, arg1, arg2);
        }

        public override void Switch<T0, T1, T2, T3>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, Action<NoneEnumValue, T0, T1, T2, T3> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3> blueSwitch)
        {
            noneSwitch(this, arg0, arg1, arg2, arg3);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, Func<NoneEnumValue, T0, T1, T2, T3, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, TResult> blueSwitch)
        {
            return noneSwitch(this, arg0, arg1, arg2, arg3);
        }

        public override void Switch<T0, T1, T2, T3, T4>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Action<NoneEnumValue, T0, T1, T2, T3, T4> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4> blueSwitch)
        {
            noneSwitch(this, arg0, arg1, arg2, arg3, arg4);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3, T4>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Func<NoneEnumValue, T0, T1, T2, T3, T4, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, TResult> blueSwitch)
        {
            return noneSwitch(this, arg0, arg1, arg2, arg3, arg4);
        }

        public override void Switch<T0, T1, T2, T3, T4, T5>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Action<NoneEnumValue, T0, T1, T2, T3, T4, T5> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4, T5> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4, T5> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4, T5> blueSwitch)
        {
            noneSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3, T4, T5>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Func<NoneEnumValue, T0, T1, T2, T3, T4, T5, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, T5, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, T5, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, T5, TResult> blueSwitch)
        {
            return noneSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5);
        }

        public override void Switch<T0, T1, T2, T3, T4, T5, T6>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Action<NoneEnumValue, T0, T1, T2, T3, T4, T5, T6> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4, T5, T6> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4, T5, T6> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4, T5, T6> blueSwitch)
        {
            noneSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3, T4, T5, T6>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Func<NoneEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> blueSwitch)
        {
            return noneSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override int GetHashCode()
        {
            return 0;
        }
    }

    public static readonly RedEnumValue Red = new RedEnumValue();
    public partial class RedEnumValue: Colors
    {
        public RedEnumValue(): base(global::EnumClassDemo.Colors.Red) { }
        public override string ToString()
        {
            return "Red";
        }

        public override void Switch(Action<NoneEnumValue> noneSwitch, Action<RedEnumValue> redSwitch, Action<GreenEnumValue> greenSwitch, Action<BlueEnumValue> blueSwitch)
        {
            redSwitch(this);
        }

        public override TResult Switch<TResult>(Func<NoneEnumValue, TResult> noneSwitch, Func<RedEnumValue, TResult> redSwitch, Func<GreenEnumValue, TResult> greenSwitch, Func<BlueEnumValue, TResult> blueSwitch)
        {
            return redSwitch(this);
        }

        public override void Switch<T0>(T0 arg0, Action<NoneEnumValue, T0> noneSwitch, Action<RedEnumValue, T0> redSwitch, Action<GreenEnumValue, T0> greenSwitch, Action<BlueEnumValue, T0> blueSwitch)
        {
            redSwitch(this, arg0);
        }

        public override TResult Switch<TResult, T0>(T0 arg0, Func<NoneEnumValue, T0, TResult> noneSwitch, Func<RedEnumValue, T0, TResult> redSwitch, Func<GreenEnumValue, T0, TResult> greenSwitch, Func<BlueEnumValue, T0, TResult> blueSwitch)
        {
            return redSwitch(this, arg0);
        }

        public override void Switch<T0, T1>(T0 arg0, T1 arg1, Action<NoneEnumValue, T0, T1> noneSwitch, Action<RedEnumValue, T0, T1> redSwitch, Action<GreenEnumValue, T0, T1> greenSwitch, Action<BlueEnumValue, T0, T1> blueSwitch)
        {
            redSwitch(this, arg0, arg1);
        }

        public override TResult Switch<TResult, T0, T1>(T0 arg0, T1 arg1, Func<NoneEnumValue, T0, T1, TResult> noneSwitch, Func<RedEnumValue, T0, T1, TResult> redSwitch, Func<GreenEnumValue, T0, T1, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, TResult> blueSwitch)
        {
            return redSwitch(this, arg0, arg1);
        }

        public override void Switch<T0, T1, T2>(T0 arg0, T1 arg1, T2 arg2, Action<NoneEnumValue, T0, T1, T2> noneSwitch, Action<RedEnumValue, T0, T1, T2> redSwitch, Action<GreenEnumValue, T0, T1, T2> greenSwitch, Action<BlueEnumValue, T0, T1, T2> blueSwitch)
        {
            redSwitch(this, arg0, arg1, arg2);
        }

        public override TResult Switch<TResult, T0, T1, T2>(T0 arg0, T1 arg1, T2 arg2, Func<NoneEnumValue, T0, T1, T2, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, TResult> blueSwitch)
        {
            return redSwitch(this, arg0, arg1, arg2);
        }

        public override void Switch<T0, T1, T2, T3>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, Action<NoneEnumValue, T0, T1, T2, T3> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3> blueSwitch)
        {
            redSwitch(this, arg0, arg1, arg2, arg3);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, Func<NoneEnumValue, T0, T1, T2, T3, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, TResult> blueSwitch)
        {
            return redSwitch(this, arg0, arg1, arg2, arg3);
        }

        public override void Switch<T0, T1, T2, T3, T4>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Action<NoneEnumValue, T0, T1, T2, T3, T4> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4> blueSwitch)
        {
            redSwitch(this, arg0, arg1, arg2, arg3, arg4);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3, T4>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Func<NoneEnumValue, T0, T1, T2, T3, T4, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, TResult> blueSwitch)
        {
            return redSwitch(this, arg0, arg1, arg2, arg3, arg4);
        }

        public override void Switch<T0, T1, T2, T3, T4, T5>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Action<NoneEnumValue, T0, T1, T2, T3, T4, T5> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4, T5> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4, T5> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4, T5> blueSwitch)
        {
            redSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3, T4, T5>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Func<NoneEnumValue, T0, T1, T2, T3, T4, T5, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, T5, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, T5, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, T5, TResult> blueSwitch)
        {
            return redSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5);
        }

        public override void Switch<T0, T1, T2, T3, T4, T5, T6>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Action<NoneEnumValue, T0, T1, T2, T3, T4, T5, T6> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4, T5, T6> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4, T5, T6> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4, T5, T6> blueSwitch)
        {
            redSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3, T4, T5, T6>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Func<NoneEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> blueSwitch)
        {
            return redSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override int GetHashCode()
        {
            return 1;
        }
    }

    public static readonly GreenEnumValue Green = new GreenEnumValue();
    public partial class GreenEnumValue: Colors
    {
        public GreenEnumValue(): base(global::EnumClassDemo.Colors.Green) { }
        public override string ToString()
        {
            return "Green";
        }

        public override void Switch(Action<NoneEnumValue> noneSwitch, Action<RedEnumValue> redSwitch, Action<GreenEnumValue> greenSwitch, Action<BlueEnumValue> blueSwitch)
        {
            greenSwitch(this);
        }

        public override TResult Switch<TResult>(Func<NoneEnumValue, TResult> noneSwitch, Func<RedEnumValue, TResult> redSwitch, Func<GreenEnumValue, TResult> greenSwitch, Func<BlueEnumValue, TResult> blueSwitch)
        {
            return greenSwitch(this);
        }

        public override void Switch<T0>(T0 arg0, Action<NoneEnumValue, T0> noneSwitch, Action<RedEnumValue, T0> redSwitch, Action<GreenEnumValue, T0> greenSwitch, Action<BlueEnumValue, T0> blueSwitch)
        {
            greenSwitch(this, arg0);
        }

        public override TResult Switch<TResult, T0>(T0 arg0, Func<NoneEnumValue, T0, TResult> noneSwitch, Func<RedEnumValue, T0, TResult> redSwitch, Func<GreenEnumValue, T0, TResult> greenSwitch, Func<BlueEnumValue, T0, TResult> blueSwitch)
        {
            return greenSwitch(this, arg0);
        }

        public override void Switch<T0, T1>(T0 arg0, T1 arg1, Action<NoneEnumValue, T0, T1> noneSwitch, Action<RedEnumValue, T0, T1> redSwitch, Action<GreenEnumValue, T0, T1> greenSwitch, Action<BlueEnumValue, T0, T1> blueSwitch)
        {
            greenSwitch(this, arg0, arg1);
        }

        public override TResult Switch<TResult, T0, T1>(T0 arg0, T1 arg1, Func<NoneEnumValue, T0, T1, TResult> noneSwitch, Func<RedEnumValue, T0, T1, TResult> redSwitch, Func<GreenEnumValue, T0, T1, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, TResult> blueSwitch)
        {
            return greenSwitch(this, arg0, arg1);
        }

        public override void Switch<T0, T1, T2>(T0 arg0, T1 arg1, T2 arg2, Action<NoneEnumValue, T0, T1, T2> noneSwitch, Action<RedEnumValue, T0, T1, T2> redSwitch, Action<GreenEnumValue, T0, T1, T2> greenSwitch, Action<BlueEnumValue, T0, T1, T2> blueSwitch)
        {
            greenSwitch(this, arg0, arg1, arg2);
        }

        public override TResult Switch<TResult, T0, T1, T2>(T0 arg0, T1 arg1, T2 arg2, Func<NoneEnumValue, T0, T1, T2, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, TResult> blueSwitch)
        {
            return greenSwitch(this, arg0, arg1, arg2);
        }

        public override void Switch<T0, T1, T2, T3>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, Action<NoneEnumValue, T0, T1, T2, T3> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3> blueSwitch)
        {
            greenSwitch(this, arg0, arg1, arg2, arg3);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, Func<NoneEnumValue, T0, T1, T2, T3, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, TResult> blueSwitch)
        {
            return greenSwitch(this, arg0, arg1, arg2, arg3);
        }

        public override void Switch<T0, T1, T2, T3, T4>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Action<NoneEnumValue, T0, T1, T2, T3, T4> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4> blueSwitch)
        {
            greenSwitch(this, arg0, arg1, arg2, arg3, arg4);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3, T4>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Func<NoneEnumValue, T0, T1, T2, T3, T4, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, TResult> blueSwitch)
        {
            return greenSwitch(this, arg0, arg1, arg2, arg3, arg4);
        }

        public override void Switch<T0, T1, T2, T3, T4, T5>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Action<NoneEnumValue, T0, T1, T2, T3, T4, T5> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4, T5> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4, T5> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4, T5> blueSwitch)
        {
            greenSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3, T4, T5>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Func<NoneEnumValue, T0, T1, T2, T3, T4, T5, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, T5, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, T5, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, T5, TResult> blueSwitch)
        {
            return greenSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5);
        }

        public override void Switch<T0, T1, T2, T3, T4, T5, T6>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Action<NoneEnumValue, T0, T1, T2, T3, T4, T5, T6> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4, T5, T6> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4, T5, T6> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4, T5, T6> blueSwitch)
        {
            greenSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3, T4, T5, T6>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Func<NoneEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> blueSwitch)
        {
            return greenSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override int GetHashCode()
        {
            return 2;
        }
    }

    public static readonly BlueEnumValue Blue = new BlueEnumValue();
    public partial class BlueEnumValue: Colors
    {
        public BlueEnumValue(): base(global::EnumClassDemo.Colors.Blue) { }
        public override string ToString()
        {
            return "Blue";
        }

        public override void Switch(Action<NoneEnumValue> noneSwitch, Action<RedEnumValue> redSwitch, Action<GreenEnumValue> greenSwitch, Action<BlueEnumValue> blueSwitch)
        {
            blueSwitch(this);
        }

        public override TResult Switch<TResult>(Func<NoneEnumValue, TResult> noneSwitch, Func<RedEnumValue, TResult> redSwitch, Func<GreenEnumValue, TResult> greenSwitch, Func<BlueEnumValue, TResult> blueSwitch)
        {
            return blueSwitch(this);
        }

        public override void Switch<T0>(T0 arg0, Action<NoneEnumValue, T0> noneSwitch, Action<RedEnumValue, T0> redSwitch, Action<GreenEnumValue, T0> greenSwitch, Action<BlueEnumValue, T0> blueSwitch)
        {
            blueSwitch(this, arg0);
        }

        public override TResult Switch<TResult, T0>(T0 arg0, Func<NoneEnumValue, T0, TResult> noneSwitch, Func<RedEnumValue, T0, TResult> redSwitch, Func<GreenEnumValue, T0, TResult> greenSwitch, Func<BlueEnumValue, T0, TResult> blueSwitch)
        {
            return blueSwitch(this, arg0);
        }

        public override void Switch<T0, T1>(T0 arg0, T1 arg1, Action<NoneEnumValue, T0, T1> noneSwitch, Action<RedEnumValue, T0, T1> redSwitch, Action<GreenEnumValue, T0, T1> greenSwitch, Action<BlueEnumValue, T0, T1> blueSwitch)
        {
            blueSwitch(this, arg0, arg1);
        }

        public override TResult Switch<TResult, T0, T1>(T0 arg0, T1 arg1, Func<NoneEnumValue, T0, T1, TResult> noneSwitch, Func<RedEnumValue, T0, T1, TResult> redSwitch, Func<GreenEnumValue, T0, T1, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, TResult> blueSwitch)
        {
            return blueSwitch(this, arg0, arg1);
        }

        public override void Switch<T0, T1, T2>(T0 arg0, T1 arg1, T2 arg2, Action<NoneEnumValue, T0, T1, T2> noneSwitch, Action<RedEnumValue, T0, T1, T2> redSwitch, Action<GreenEnumValue, T0, T1, T2> greenSwitch, Action<BlueEnumValue, T0, T1, T2> blueSwitch)
        {
            blueSwitch(this, arg0, arg1, arg2);
        }

        public override TResult Switch<TResult, T0, T1, T2>(T0 arg0, T1 arg1, T2 arg2, Func<NoneEnumValue, T0, T1, T2, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, TResult> blueSwitch)
        {
            return blueSwitch(this, arg0, arg1, arg2);
        }

        public override void Switch<T0, T1, T2, T3>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, Action<NoneEnumValue, T0, T1, T2, T3> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3> blueSwitch)
        {
            blueSwitch(this, arg0, arg1, arg2, arg3);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, Func<NoneEnumValue, T0, T1, T2, T3, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, TResult> blueSwitch)
        {
            return blueSwitch(this, arg0, arg1, arg2, arg3);
        }

        public override void Switch<T0, T1, T2, T3, T4>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Action<NoneEnumValue, T0, T1, T2, T3, T4> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4> blueSwitch)
        {
            blueSwitch(this, arg0, arg1, arg2, arg3, arg4);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3, T4>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Func<NoneEnumValue, T0, T1, T2, T3, T4, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, TResult> blueSwitch)
        {
            return blueSwitch(this, arg0, arg1, arg2, arg3, arg4);
        }

        public override void Switch<T0, T1, T2, T3, T4, T5>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Action<NoneEnumValue, T0, T1, T2, T3, T4, T5> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4, T5> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4, T5> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4, T5> blueSwitch)
        {
            blueSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3, T4, T5>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Func<NoneEnumValue, T0, T1, T2, T3, T4, T5, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, T5, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, T5, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, T5, TResult> blueSwitch)
        {
            return blueSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5);
        }

        public override void Switch<T0, T1, T2, T3, T4, T5, T6>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Action<NoneEnumValue, T0, T1, T2, T3, T4, T5, T6> noneSwitch, Action<RedEnumValue, T0, T1, T2, T3, T4, T5, T6> redSwitch, Action<GreenEnumValue, T0, T1, T2, T3, T4, T5, T6> greenSwitch, Action<BlueEnumValue, T0, T1, T2, T3, T4, T5, T6> blueSwitch)
        {
            blueSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
        }

        public override TResult Switch<TResult, T0, T1, T2, T3, T4, T5, T6>(T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Func<NoneEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> noneSwitch, Func<RedEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> redSwitch, Func<GreenEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> greenSwitch, Func<BlueEnumValue, T0, T1, T2, T3, T4, T5, T6, TResult> blueSwitch)
        {
            return blueSwitch(this, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override int GetHashCode()
        {
            return 3;
        }
    }

    private static readonly Colors[] _members = new Colors[4] { None, Red, Green, Blue, };

    public static System.Collections.Generic.IReadOnlyCollection<Colors> GetAllMembers()
    {
        return _members;
    }
}
}

Code and pdf at

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

RSCG – AutoRegisterInject

RSCG – AutoRegisterInject
 
 

name AutoRegisterInject
nuget https://www.nuget.org/packages/AutoRegisterInject/
link https://github.com/patrickklaeren/AutoRegisterInject
author Patrick Klaeren

Generating class DI registration from attributes

 

This is how you can use AutoRegisterInject .

The code that you start with is


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

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

  <ItemGroup>
    <PackageReference Include="AutoRegisterInject" Version="1.2.1" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
  </ItemGroup>
	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>
</Project>


The code that you will use is


// See https://aka.ms/new-console-template for more information
using AutoRegisterInjectDemo;
using Microsoft.Extensions.DependencyInjection;

Console.WriteLine("Hello, World!");
ServiceCollection sc = new();
sc.AutoRegisterFromAutoRegisterInjectDemo();
var b=sc.BuildServiceProvider();
var con = b.GetRequiredService<DatabaseCon>();
var db=b.GetRequiredService<IDatabase>();
db.Open();



namespace AutoRegisterInjectDemo;

[RegisterScoped]
internal class Database : IDatabase
{
    private readonly DatabaseCon con;

    public Database(DatabaseCon con)
    {
        this.con = con;
    }
    public void Open()
    {
        Console.WriteLine($"open {con.Connection}");
    }

}




namespace AutoRegisterInjectDemo
{
    internal interface IDatabase
    {
        void Open();
    }
}


namespace AutoRegisterInjectDemo;

[RegisterSingleton]
internal class DatabaseCon
{
    public string? Connection { get; set; }
}



 

The code that is generated is

// <auto-generated>
//     Automatically generated by AutoRegisterInject.
//     Changes made to this file may be lost and may cause undesirable behaviour.
// </auto-generated>
[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class RegisterScopedAttribute : System.Attribute { }
[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class RegisterSingletonAttribute : System.Attribute { }
[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class RegisterTransientAttribute : System.Attribute { }
[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
internal sealed class RegisterHostedServiceAttribute : System.Attribute { }
// <auto-generated>
//     Automatically generated by AutoRegisterInject.
//     Changes made to this file may be lost and may cause undesirable behaviour.
// </auto-generated>
using Microsoft.Extensions.DependencyInjection;
public static class AutoRegisterInjectServiceCollectionExtension
{
    public static Microsoft.Extensions.DependencyInjection.IServiceCollection AutoRegisterFromAutoRegisterInjectDemo(this Microsoft.Extensions.DependencyInjection.IServiceCollection serviceCollection)
    {
        return AutoRegister(serviceCollection);
    }

    internal static Microsoft.Extensions.DependencyInjection.IServiceCollection AutoRegister(this Microsoft.Extensions.DependencyInjection.IServiceCollection serviceCollection)
    {
        serviceCollection.AddScoped<AutoRegisterInjectDemo.IDatabase, AutoRegisterInjectDemo.Database>();
serviceCollection.AddSingleton<AutoRegisterInjectDemo.DatabaseCon>();
        return serviceCollection;
    }
}

Code and pdf at

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

RSCG – ProxyGen

RSCG – ProxyGen
 
 

name ProxyGen
nuget https://www.nuget.org/packages/ProxyGen.net/
link https://github.com/Sholtee/ProxyGen
author Dénes Solti

intercepting and duck typing

 

This is how you can use ProxyGen .

The code that you start with is


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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>
  <ItemGroup>
    <PackageReference Include="ProxyGen.NET" Version="8.2.1" />
  </ItemGroup>

</Project>


The code that you will use is


Person person = new ();
person.FirstName= "Andrei";
person.LastName = "Ignat";
IPerson duck = DuckGenerator<IPerson, Person>.Activate(Tuple.Create(person));
Console.WriteLine(duck.FullName());



namespace ProxyGenDemo;

public class Person 
{
    public int ID { get; set; }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public string FullName()
    {
        return $"{FirstName} {LastName}";
    }
}



namespace ProxyGenDemo;

public interface IPerson
{
    string? FirstName { get; set; }
    string? LastName { get; set; }

    string FullName();
}


global using ProxyGenDemo;
global using Solti.Utils.Proxy.Generators;
global using Solti.Utils.Proxy.Attributes;

//[assembly: EmbedGeneratedType(typeof(ProxyGenerator<IMyInterface, MyInterceptor<IMyInterface>>))]
[assembly: EmbedGeneratedType(typeof(DuckGenerator<IPerson, Person>))]

 

The code that is generated is

#pragma warning disable
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("ProxyGen.NET", "8.2.1.0"), global::System.Diagnostics.DebuggerNonUserCodeAttribute, global::System.Runtime.CompilerServices.CompilerGeneratedAttribute]
internal sealed class Duck_BB1E45629CF5010E4068E5BFBB7EF53B : global::Solti.Utils.Proxy.Internals.DuckBase<global::ProxyGenDemo.Person>, global::ProxyGenDemo.IPerson
{
    public Duck_BB1E45629CF5010E4068E5BFBB7EF53B(global::ProxyGenDemo.Person target) : base(target)
    {
    }

    [global::System.Runtime.CompilerServices.MethodImplAttribute(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
    global::System.String global::ProxyGenDemo.IPerson.FullName() => this.Target.FullName();
    global::System.String global::ProxyGenDemo.IPerson.FirstName {[global::System.Runtime.CompilerServices.MethodImplAttribute(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
        get => this.Target.FirstName; [global::System.Runtime.CompilerServices.MethodImplAttribute(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
        set => this.Target.FirstName = value; }

    global::System.String global::ProxyGenDemo.IPerson.LastName {[global::System.Runtime.CompilerServices.MethodImplAttribute(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
        get => this.Target.LastName; [global::System.Runtime.CompilerServices.MethodImplAttribute(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
        set => this.Target.LastName = value; }

    public static readonly global::System.Func<global::System.Object, global::System.Object> __Activator = tuple =>
    {
        switch (tuple)
        {
            case global::System.Tuple<global::ProxyGenDemo.Person> t0:
                return new global::Duck_BB1E45629CF5010E4068E5BFBB7EF53B(t0.Item1);
            default:
                throw new global::System.MissingMethodException("Constructor with the given layout cannot be found.");
        }
    };
    [global::System.Runtime.CompilerServices.ModuleInitializerAttribute]
    public static void Initialize() => global::Solti.Utils.Proxy.Internals.LoadedTypes.Register(typeof(global::Duck_BB1E45629CF5010E4068E5BFBB7EF53B));
}

Code and pdf at

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

RSCG – DeeDee

RSCG – DeeDee
 
 

name DeeDee
nuget https://www.nuget.org/packages/DeeDee/
link https://github.com/joh-pot/DeeDee/
author joh-pot

Mediatr generated data

 

This is how you can use DeeDee .

The code that you start with is


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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>
	<ItemGroup>
		<PackageReference Include="DeeDee" Version="2.0.0" />
		<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
		
	</ItemGroup>

</Project>


The code that you will use is


Console.WriteLine("Hello, World!");
ServiceCollection services = new ();
DeeDeeDemo.DeeDee.Generated.IocExtensions.AddDispatcher(services);

services.AddSingleton(typeof(IPipelineAction<Ping, Pong>), typeof(GenericLoggerHandler)); // This will run 1st

var serviceProvider = services.BuildServiceProvider();

var mediator = serviceProvider.GetRequiredService<DeeDeeDemo.DeeDee.Generated.Models.IDispatcher>();
var id = Guid.NewGuid();
var request = new Ping(id);

var response = mediator.Send(request);

Console.WriteLine("-----------------------------------");
Console.WriteLine("ID: " + id);
Console.WriteLine(request);
Console.WriteLine(response);




public sealed record Ping(Guid Id) : IRequest<Pong>;

public sealed record Pong(Guid Id);


public sealed class PingHandler : IPipelineAction<Ping, Pong>
{

    public Pong Invoke(Ping request, ref PipelineContext<Pong> context, Next<Pong> next)
    {
        Console.WriteLine("4) Returning pong!");
        return new Pong(request.Id);
    }
}



public sealed class GenericLoggerHandler : IPipelineAction<Ping, Pong>
{
    public Pong Invoke(Ping request, ref PipelineContext<Pong> context, Next<Pong> next)
    {
        Console.WriteLine("1) Running logger handler");
        try
        {
            var response = next(request , ref context);
            Console.WriteLine("5) No error!");
            return response;
        }
        catch (Exception ex)
        {
            Console.WriteLine("error:" + ex.Message);
            throw;
        }
    }
}

 

The code that is generated is

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using DeeDee.Models;
using ServiceProvider = DeeDee.Models.ServiceProvider;

namespace DeeDeeDemo.DeeDee.Generated.Models
{
    public class Dispatcher : IDispatcher
    {
        private readonly ServiceProvider _serviceFactory;
        private readonly Lazy<Next<Pong>> _Ping_Pong_lazy;
        public Dispatcher(ServiceProvider service)
        {
            _serviceFactory = service;
            _Ping_Pong_lazy = new Lazy<Next<Pong>>(Build<Ping, Pong>);
        }

        public Pong Send(Ping request)
        {
            var context = new PipelineContext<Pong>();
            Next<Pong> builtPipeline = _Ping_Pong_lazy.Value;
            return builtPipeline(request, ref context);
        }

        private NextAsync BuildAsync<TRequest>()
            where TRequest : IRequest
        {
            {
                var actions = _serviceFactory.GetServices<IPipelineActionAsync<TRequest>>();
                var builtPipeline = actions.Aggregate((NextAsync)((req, ctx, tkn) => Task.CompletedTask), (next, pipeline) => (req, ctx, tkn) => pipeline.InvokeAsync((TRequest)req, ctx, next, tkn));
                return builtPipeline;
            }
        }

        private Next Build<TRequest>()
            where TRequest : IRequest
        {
            {
                var actions = _serviceFactory.GetServices<IPipelineAction<TRequest>>();
                var builtPipeline = actions.Aggregate((Next)((IRequest req, ref PipelineContext ctx) =>
                {
                    {
                    }
                }), (next, pipeline) => (IRequest req, ref PipelineContext ctx) => pipeline.Invoke((TRequest)req, ref ctx, next));
                return builtPipeline;
            }
        }

        private NextAsync<TResponse> BuildAsync<TRequest, TResponse>()
            where TRequest : IRequest<TResponse>
        {
            {
                var actions = _serviceFactory.GetServices<IPipelineActionAsync<TRequest, TResponse>>();
                var builtPipeline = actions.Aggregate((NextAsync<TResponse>)((req, ctx, tkn) => Task.FromResult(ctx.Result)), (next, pipeline) => (req, ctx, tkn) => pipeline.InvokeAsync((TRequest)req, ctx, next, tkn));
                return builtPipeline;
            }
        }

        private Next<TResponse> Build<TRequest, TResponse>()
            where TRequest : IRequest<TResponse>
        {
            {
                var actions = _serviceFactory.GetServices<IPipelineAction<TRequest, TResponse>>();
                var builtPipeline = actions.Aggregate((Next<TResponse>)((IRequest<TResponse> req, ref PipelineContext<TResponse> ctx) => ctx.Result), (next, pipeline) => (IRequest<TResponse> req, ref PipelineContext<TResponse> ctx) => pipeline.Invoke((TRequest)req, ref ctx, next));
                return builtPipeline;
            }
        }
    }
}
using System;
using System.Threading;
using System.Threading.Tasks;
using DeeDee.Models;

namespace DeeDeeDemo.DeeDee.Generated.Models
{
    public interface IDispatcher
    {
        public Pong Send(Ping request);
    }
}

            using System;
            using System.Linq;
            using System.Reflection;
            using DeeDee.Models;
            using DeeDeeDemo.DeeDee.Generated.Models;
            using Microsoft.Extensions.DependencyInjection;
            using ServiceProvider = DeeDee.Models.ServiceProvider;
            namespace DeeDeeDemo.DeeDee.Generated

            {
                internal static class IocExtensions
                {
                    public static IServiceCollection AddDispatcher(this IServiceCollection services, Lifetime lifetime = Lifetime.Singleton)
                    {
                        switch(lifetime)
                        {
                            case Lifetime.Singleton:
                                services.AddSingleton<IDispatcher, Dispatcher>();
                                services.AddSingleton<ServiceProvider>(ctx => ctx.GetRequiredService);
                                break;

                            case Lifetime.Scoped:
                                services.AddScoped<IDispatcher, Dispatcher>();
                                services.AddScoped<ServiceProvider>(ctx => ctx.GetRequiredService);
                                break;

                            case Lifetime.Transient:
                                services.AddTransient<IDispatcher, Dispatcher>();
                                services.AddTransient<ServiceProvider>(ctx => ctx.GetRequiredService);
                                break;
                        }
                        
                        RegisterPipelineActions(services);
                        
                        return services;
                    }

                    private static void RegisterPipelineActions(IServiceCollection services)
                    {
                        var pipelineTypes = AppDomain
                            .CurrentDomain
                            .GetAssemblies()
                            .SelectMany
                            (
                                a => a.GetTypes().Where
                                (
                                   x => !x.IsInterface &&
                                        !x.IsAbstract &&
                                        x.GetInterfaces()
                                            .Any
                                            (
                                                y => y.Name.Equals(typeof(IPipelineActionAsync<,>).Name,
                                                         StringComparison.InvariantCulture) ||
                                                     y.Name.Equals(typeof(IPipelineActionAsync<>).Name,
                                                         StringComparison.InvariantCulture) ||
                                                     y.Name.Equals(typeof(IPipelineAction<>).Name,
                                                         StringComparison.InvariantCulture) ||
                                                     y.Name.Equals(typeof(IPipelineAction<,>).Name, StringComparison.InvariantCulture)
                                            )
                                ).GroupBy(type => type.GetInterfaces()[0]).SelectMany(g => g.OrderByDescending(s => s.GetCustomAttribute<StepAttribute>()?.Order))
                            );

                        foreach (var type in pipelineTypes)
                        {
                            foreach (var implementedInterface in type.GetInterfaces())
                            {
                                var bindAs = type.GetCustomAttribute<BindAsAttribute>();
                                switch (bindAs?.Lifetime)
                                {
                                    case Lifetime.Singleton:
                                        services.AddSingleton(implementedInterface, type);
                                        break;
                                    case Lifetime.Scoped:
                                        services.AddScoped(implementedInterface, type);
                                        break;  
                                    case Lifetime.Transient:
                                        services.AddTransient(implementedInterface, type);
                                        break;
                                    default:
                                        services.AddSingleton(implementedInterface, type);
                                        break;
                                }
                                
                            }
                        } 
                    }
                }
            }

Code and pdf at

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

RSCG – MemoryPack

RSCG – MemoryPack
 
 

name MemoryPack
nuget https://www.nuget.org/packages/MemoryPack/
link https://github.com/Cysharp/MemoryPack
author Cysharp, Inc

Efficient serializer

 

This is how you can use MemoryPack .

The code that you start with is


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

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

  <ItemGroup>
    <PackageReference Include="MemoryPack" Version="1.9.16" />
  </ItemGroup>
	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>
</Project>


The code that you will use is


var v = new Person { Age = 53, Name = "Andrei Ignat" };

var bin = MemoryPackSerializer.Serialize(v);
var val = MemoryPackSerializer.Deserialize<Person>(bin);
Console.WriteLine(val.Name);


namespace MemoryPackDemo;

[MemoryPackable]
public partial class Person
{
    public int Age { get; set; }
    public string? Name { get; set; }
}


 

The code that is generated is


// <auto-generated/>
#nullable enable
#pragma warning disable CS0108 // hides inherited member
#pragma warning disable CS0162 // Unreachable code
#pragma warning disable CS0164 // This label has not been referenced
#pragma warning disable CS0219 // Variable assigned but never used
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
#pragma warning disable CS8601 // Possible null reference assignment
#pragma warning disable CS8602
#pragma warning disable CS8604 // Possible null reference argument for parameter
#pragma warning disable CS8619
#pragma warning disable CS8620
#pragma warning disable CS8631 // The type cannot be used as type parameter in the generic type or method
#pragma warning disable CS8765 // Nullability of type of parameter
#pragma warning disable CS9074 // The 'scoped' modifier of parameter doesn't match overridden or implemented member
#pragma warning disable CA1050 // Declare types in namespaces.

using System;
using MemoryPack;

namespace MemoryPackDemo;

/// <remarks>
/// MemoryPack GenerateType: Object<br/>
/// <code>
/// <b>int</b> Age<br/>
/// <b>string</b> Name<br/>
/// </code>
/// </remarks>
partial class Person : IMemoryPackable<Person>
{


    static Person()
    {
        global::MemoryPack.MemoryPackFormatterProvider.Register<Person>();
    }

    [global::MemoryPack.Internal.Preserve]
    static void IMemoryPackFormatterRegister.RegisterFormatter()
    {
        if (!global::MemoryPack.MemoryPackFormatterProvider.IsRegistered<Person>())
        {
            global::MemoryPack.MemoryPackFormatterProvider.Register(new global::MemoryPack.Formatters.MemoryPackableFormatter<Person>());
        }
        if (!global::MemoryPack.MemoryPackFormatterProvider.IsRegistered<Person[]>())
        {
            global::MemoryPack.MemoryPackFormatterProvider.Register(new global::MemoryPack.Formatters.ArrayFormatter<Person>());
        }

    }

    [global::MemoryPack.Internal.Preserve]
    static void IMemoryPackable<Person>.Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, scoped ref Person? value) 
    {

        if (value == null)
        {
            writer.WriteNullObjectHeader();
            goto END;
        }

        writer.WriteUnmanagedWithObjectHeader(2, value.@Age);
        writer.WriteString(value.@Name);

    END:

        return;
    }

    [global::MemoryPack.Internal.Preserve]
    static void IMemoryPackable<Person>.Deserialize(ref MemoryPackReader reader, scoped ref Person? value)
    {

        if (!reader.TryReadObjectHeader(out var count))
        {
            value = default!;
            goto END;
        }


        
        int __Age;
        string __Name;

        
        if (count == 2)
        {
            if (value == null)
            {
                reader.ReadUnmanaged(out __Age);
                __Name = reader.ReadString();


                goto NEW;
            }
            else
            {
                __Age = value.@Age;
                __Name = value.@Name;

                reader.ReadUnmanaged(out __Age);
                __Name = reader.ReadString();

                goto SET;
            }

        }
        else if (count > 2)
        {
            MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(Person), 2, count);
            goto READ_END;
        }
        else
        {
            if (value == null)
            {
               __Age = default!;
               __Name = default!;
            }
            else
            {
               __Age = value.@Age;
               __Name = value.@Name;
            }


            if (count == 0) goto SKIP_READ;
            reader.ReadUnmanaged(out __Age); if (count == 1) goto SKIP_READ;
            __Name = reader.ReadString(); if (count == 2) goto SKIP_READ;

    SKIP_READ:
            if (value == null)
            {
                goto NEW;
            }
            else            
            {
                goto SET;
            }

        }

    SET:
        
        value.@Age = __Age;
        value.@Name = __Name;
        goto READ_END;

    NEW:
        value = new Person()
        {
            @Age = __Age,
            @Name = __Name
        };
    READ_END:

    END:

        return;
    }
}

Code and pdf at

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

RSCG – Matryoshki

RSCG – Matryoshki
 
 

name Matryoshki
nuget https://www.nuget.org/packages/Matryoshki/
link https://github.com/krasin-ga/matryoshki/
author Georgy Krasin

Adding decorators to an implementation of interface

 

This is how you can use Matryoshki .

The code that you start with is


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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>
	<ItemGroup>
		<PackageReference Include="Matryoshki" Version="1.1.4" />
		<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />

	</ItemGroup>


</Project>


The code that you will use is



using Matryoshki.Abstractions;
Decorate<IPerson> // you can use Decorate<> alias if you prefer
    .With<AddLog>()
    .Name<PersonMatryoshka>();

var services = new ServiceCollection();

services.AddTransient<IPerson, Person>();
services.AddTransient<PersonMatryoshka, PersonMatryoshka>();
var serviceProvider = services.BuildServiceProvider();
var sp=serviceProvider.GetRequiredService<PersonMatryoshka>();
sp.FirstName = "Andrei";
sp.LastName = "Ignat";
Console.WriteLine(sp.FullName());




namespace MatryoshkiDemo;

internal class AddLog : IAdornment
{
    public TResult MethodTemplate<TResult>(Call<TResult> call)
    {        
        Console.WriteLine($"start Calling {call.MemberName}  !");
        var data    =call.Forward();
        Console.WriteLine($"end calling {call.MemberName} !");
        return data;

    }
}


namespace MatryoshkiDemo;

public interface IPerson
{
    string? FirstName { get; set; }
    int ID { get; set; }
    string? LastName { get; set; }

    string FullName();
}



namespace MatryoshkiDemo;

public class Person : IPerson
{
    public int ID { get; set; }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }

    public string FullName()
    {
        return $"{FirstName} {LastName}";
    }
}


 

The code that is generated is

[assembly: Matryoshki.Abstractions.CompiledAdornmentAttribute("MatryoshkiDemo.AddLog", "AddLog", "DQpuYW1lc3BhY2UgTWF0cnlvc2hraURlbW87DQoNCmludGVybmFsIGNsYXNzIEFkZExvZyA6IElBZG9ybm1lbnQNCnsNCiAgICBwdWJsaWMgVFJlc3VsdCBNZXRob2RUZW1wbGF0ZTxUUmVzdWx0PihDYWxsPFRSZXN1bHQ+IGNhbGwpDQogICAgeyAgICAgICAgDQogICAgICAgIENvbnNvbGUuV3JpdGVMaW5lKCQic3RhcnQgQ2FsbGluZyB7Y2FsbC5NZW1iZXJOYW1lfSAgISIpOw0KICAgICAgICB2YXIgZGF0YSAgICA9Y2FsbC5Gb3J3YXJkKCk7DQogICAgICAgIENvbnNvbGUuV3JpdGVMaW5lKCQiZW5kIGNhbGxpbmcge2NhbGwuTWVtYmVyTmFtZX0gISIpOw0KICAgICAgICByZXR1cm4gZGF0YTsNCg0KICAgIH0NCn0=")]
using System;

#nullable enable
public interface IPerson
{
    int ID { get; set; }

    string? FirstName { get; set; }

    string? LastName { get; set; }

    string FullName();
    public class Adapter : IPerson
    {
        private readonly MatryoshkiDemo.Person _inner;
        public Adapter(MatryoshkiDemo.Person inner)
        {
            _inner = inner;
        }

        public int ID { get => _inner.ID; set => _inner.ID = value; }
        public string? FirstName { get => _inner.FirstName; set => _inner.FirstName = value; }
        public string? LastName { get => _inner.LastName; set => _inner.LastName = value; }

        public string FullName() => _inner.FullName();
    }
}
using System;
using MatryoshkiDemo;

#nullable enable
public class IPersonWithAddLog : MatryoshkiDemo.IPerson
{
    private readonly MatryoshkiDemo.IPerson _inner;
    public IPersonWithAddLog(MatryoshkiDemo.IPerson inner)
    {
        _inner = inner;
    }

    private static readonly string[] MethodParameterNamesForPropertyFirstName = new string[]
    {
    };
    public string? FirstName
    {
        get
        {
            Console.WriteLine($"Hello, {"FirstName"}!");
            return _inner.FirstName;
        }

        set
        {
            Console.WriteLine($"Hello, {"FirstName"}!");
            {
                Matryoshki.Abstractions.Nothing.FromPropertyAction(_inner, value, static (@innerΔΔΔ, @valueΔΔΔ) => @innerΔΔΔ.FirstName = @valueΔΔΔ);
                return;
            }
        }
    }

    private static readonly string[] MethodParameterNamesForPropertyID = new string[]
    {
    };
    public int ID
    {
        get
        {
            Console.WriteLine($"Hello, {"ID"}!");
            return _inner.ID;
        }

        set
        {
            Console.WriteLine($"Hello, {"ID"}!");
            {
                Matryoshki.Abstractions.Nothing.FromPropertyAction(_inner, value, static (@innerΔΔΔ, @valueΔΔΔ) => @innerΔΔΔ.ID = @valueΔΔΔ);
                return;
            }
        }
    }

    private static readonly string[] MethodParameterNamesForPropertyLastName = new string[]
    {
    };
    public string? LastName
    {
        get
        {
            Console.WriteLine($"Hello, {"LastName"}!");
            return _inner.LastName;
        }

        set
        {
            Console.WriteLine($"Hello, {"LastName"}!");
            {
                Matryoshki.Abstractions.Nothing.FromPropertyAction(_inner, value, static (@innerΔΔΔ, @valueΔΔΔ) => @innerΔΔΔ.LastName = @valueΔΔΔ);
                return;
            }
        }
    }

    private static readonly string[] MethodParameterNamesForMethodFullName = new string[]
    {
    };
    public string FullName()
    {
        Console.WriteLine($"Hello, {"FullName"}!");
        return _inner.FullName();
    }
}
using System;
using MatryoshkiDemo;

#nullable enable
public class PersonMatryoshka : MatryoshkiDemo.IPerson
{
    private readonly MatryoshkiDemo.IPerson _inner;
    public PersonMatryoshka(MatryoshkiDemo.IPerson inner)
    {
        _inner = inner;
    }

    private static readonly string[] MethodParameterNamesForPropertyFirstName = new string[]
    {
    };
    public string? FirstName
    {
        get
        {
            Console.WriteLine($"start Calling {"FirstName"}  !");
            var data = _inner.FirstName;
            Console.WriteLine($"end calling {"FirstName"} !");
            return data;
        }

        set
        {
            Console.WriteLine($"start Calling {"FirstName"}  !");
            var data = Matryoshki.Abstractions.Nothing.FromPropertyAction(_inner, value, static (@innerΔΔΔ, @valueΔΔΔ) => @innerΔΔΔ.FirstName = @valueΔΔΔ);
            Console.WriteLine($"end calling {"FirstName"} !");
            return;
        }
    }

    private static readonly string[] MethodParameterNamesForPropertyID = new string[]
    {
    };
    public int ID
    {
        get
        {
            Console.WriteLine($"start Calling {"ID"}  !");
            var data = _inner.ID;
            Console.WriteLine($"end calling {"ID"} !");
            return data;
        }

        set
        {
            Console.WriteLine($"start Calling {"ID"}  !");
            var data = Matryoshki.Abstractions.Nothing.FromPropertyAction(_inner, value, static (@innerΔΔΔ, @valueΔΔΔ) => @innerΔΔΔ.ID = @valueΔΔΔ);
            Console.WriteLine($"end calling {"ID"} !");
            return;
        }
    }

    private static readonly string[] MethodParameterNamesForPropertyLastName = new string[]
    {
    };
    public string? LastName
    {
        get
        {
            Console.WriteLine($"start Calling {"LastName"}  !");
            var data = _inner.LastName;
            Console.WriteLine($"end calling {"LastName"} !");
            return data;
        }

        set
        {
            Console.WriteLine($"start Calling {"LastName"}  !");
            var data = Matryoshki.Abstractions.Nothing.FromPropertyAction(_inner, value, static (@innerΔΔΔ, @valueΔΔΔ) => @innerΔΔΔ.LastName = @valueΔΔΔ);
            Console.WriteLine($"end calling {"LastName"} !");
            return;
        }
    }

    private static readonly string[] MethodParameterNamesForMethodFullName = new string[]
    {
    };
    public string FullName()
    {
        Console.WriteLine($"start Calling {"FullName"}  !");
        var data = _inner.FullName();
        Console.WriteLine($"end calling {"FullName"} !");
        return data;
    }
}

Code and pdf at

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

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.