Category: roslyn

RSCG – Valuify

RSCG – Valuify
 
 

name Valuify
nuget https://www.nuget.org/packages/Valuify/
link https://github.com/MooVC/valuify
author Paul Martins

Generating Equals from properties

 

This is how you can use Valuify .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
  <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="Valuify" Version="1.1.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>
 
  
</Project>

The code that you will use is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
// See https://aka.ms/new-console-template for more information
using GeneratorEqualsDemo;
var p1 = new Person()
{
    ID = 1,
    FirstName = "Andrei",
    LastName = "Ignat"
};
var p2= new Person()
{
    ID = 1,
    FirstName = "Andrei",
    LastName = "Ignat"
};
Console.WriteLine(p1==p2);
01
02
03
04
05
06
07
08
09
10
namespace GeneratorEqualsDemo;
 
[Valuify.Valuify]
partial class Person
{
    public int ID { get; set; }
    public string? FirstName { get; set; }
   
    public string? LastName { get; set; }
}

 

The code that is generated is

01
02
03
04
05
06
07
08
09
10
11
namespace Valuify
{
    using System;
    using System.Diagnostics.CodeAnalysis;
 
    [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
    internal sealed class ValuifyAttribute
        : Attribute
    {
    }
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
namespace GeneratorEqualsDemo
{
    using System;
    using System.Collections.Generic;
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable disable
    #endif
 
    partial class Person
    {
        public static bool operator ==(Person left, Person right)
        {
            if (ReferenceEquals(left, right))
            {
                return true;
            }
 
            if (ReferenceEquals(left, null) || ReferenceEquals(right, null))
            {
                return false;
            }
 
            return global::System.Collections.Generic.EqualityComparer<int>.Default.Equals(left.ID, right.ID)
                && global::System.Collections.Generic.EqualityComparer<string>.Default.Equals(left.FirstName, right.FirstName)
                && global::System.Collections.Generic.EqualityComparer<string>.Default.Equals(left.LastName, right.LastName);
        }
    }
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable restore
    #endif
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
namespace GeneratorEqualsDemo
{
    using System;
    using System.Collections.Generic;
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable disable
    #endif
 
    partial class Person
    {
        public sealed override bool Equals(object other)
        {
            return Equals(other as Person);
        }
    }
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable restore
    #endif
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
namespace GeneratorEqualsDemo
{
    using System;
    using System.Collections.Generic;
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable disable
    #endif
 
    partial class Person
    {
        public sealed override int GetHashCode()
        {
            return global::Valuify.Internal.HashCode.Combine(ID, FirstName, LastName);
        }
    }
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable restore
    #endif
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
namespace GeneratorEqualsDemo
{
    using System;
    using System.Collections.Generic;
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable disable
    #endif
 
    partial class Person
    {
        public bool Equals(Person other)
        {
            return this == other;
        }
    }
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable restore
    #endif
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
namespace GeneratorEqualsDemo
{
    using System;
    using System.Collections.Generic;
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable disable
    #endif
 
    partial class Person
        : IEquatable<Person>
    {
    }
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable restore
    #endif
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
namespace GeneratorEqualsDemo
{
    using System;
    using System.Collections.Generic;
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable disable
    #endif
 
    partial class Person
    {
        public static bool operator !=(Person left, Person right)
        {
            return !(left == right);
        }
    }
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable restore
    #endif
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
namespace GeneratorEqualsDemo
{
    using System;
    using System.Collections.Generic;
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable disable
    #endif
 
    partial class Person
    {
        public sealed override string ToString()
        {
            return string.Format("Person { ID = {0}, FirstName = {1}, LastName = {2} }", ID, FirstName, LastName);
        }
    }
 
    #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
    #nullable restore
    #endif
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
namespace Valuify.Internal
{
    using System;
    using System.Collections;
 
    internal static class HashCode
    {
        private const int HashSeed = 0x1505;
        private const int HashPrime = -1521134295;
 
        public static int Combine(params object[] values)
        {
            int hash = HashSeed;
 
            foreach (object value in values)
            {
                if (value is IEnumerable && !(value is string))
                {
                    IEnumerable enumerable = (IEnumerable)value;
 
                    foreach (object element in enumerable)
                    {
                        hash = PerformCombine(hash, element);
                    }
                }
                else
                {
                    hash = PerformCombine(hash, value);
                }
            }
 
            return hash;
        }
 
        private static int PerformCombine(int hash, object value)
        {
            int other = GetHashCode(value);
 
            unchecked
            {
                return (other * HashPrime) + hash;
            }
        }
 
        private static int GetHashCode(object value)
        {
            int code = 0;
 
            if (value != null)
            {
                code = value.GetHashCode();
            }
 
            return code;
        }
    }
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
namespace Valuify.Internal
{
    using System;
    using System.Collections;
 
    internal sealed class SequenceEqualityComparer
    {
        public static readonly SequenceEqualityComparer Default = new SequenceEqualityComparer();
 
        public bool Equals(IEnumerable left, IEnumerable right)
        {
            if (ReferenceEquals(left, right))
            {
                return true;
            }
 
            if (ReferenceEquals(left, null) || ReferenceEquals(null, right))
            {
                return false;
            }
 
            return Equals(left.GetEnumerator(), right.GetEnumerator());
        }
 
        public int GetHashCode(IEnumerable enumerable)
        {
            return HashCode.Combine(enumerable);
        }
 
        private static bool Equals(IEnumerator left, IEnumerator right)
        {
            while (left.MoveNext())
            {
                if (!right.MoveNext())
                {
                    return false;
                }
 
                if (!Equals(left.Current, right.Current))
                {
                    return false;
                }
            }
 
            return !right.MoveNext();
        }
    }
}

Code and pdf at

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

RSCG – Equatable.Generator

RSCG – Equatable.Generator
 
 

name Equatable.Generator
nuget https://www.nuget.org/packages/Equatable.Generator/
link https://github.com/loresoft/Equatable.Generator
author Eden Prairie

Generating Equals from properties

 

This is how you can use Equatable.Generator .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
  <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="Equatable.Generator" Version="2.0.0" />
  </ItemGroup>
</Project>

The code that you will use is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
// See https://aka.ms/new-console-template for more information
using GeneratorEqualsDemo;
var p1 = new Person()
{
    ID = 1,
    FirstName = "Andrei",
    LastName = "Ignat"
};
var p2= new Person()
{
    ID = 2,
    FirstName = "aNdrei",
    LastName = "Ignat"
};
Console.WriteLine(p1==p2);
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
using Equatable.Attributes;
 
namespace GeneratorEqualsDemo;
 
[Equatable]
partial class Person
{
    [IgnoreEquality]
    public int ID { get; set; }
    [StringEquality(StringComparison.OrdinalIgnoreCase)]
    public string? FirstName { get; set; }
    [StringEquality(StringComparison.OrdinalIgnoreCase)]
 
    public string? LastName { get; set; }
}

 

The code that is generated is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// <auto-generated />
#nullable enable
 
namespace GeneratorEqualsDemo
{
    partial class Person : global::System.IEquatable<global::GeneratorEqualsDemo.Person?>
    {
        /// <inheritdoc />
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Equatable.SourceGenerator", "2.0.0+10ad4b045a688eb10980afcd11ddb8e64505eda6")]
        public bool Equals(global::GeneratorEqualsDemo.Person? other)
        {
            return !(other is null)
                && global::System.StringComparer.OrdinalIgnoreCase.Equals(FirstName, other.FirstName)
                && global::System.StringComparer.OrdinalIgnoreCase.Equals(LastName, other.LastName);
 
        }
 
        /// <inheritdoc />
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Equatable.SourceGenerator", "2.0.0+10ad4b045a688eb10980afcd11ddb8e64505eda6")]
        public override bool Equals(object? obj)
        {
            return Equals(obj as global::GeneratorEqualsDemo.Person);
        }
 
        /// <inheritdoc />
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Equatable.SourceGenerator", "2.0.0+10ad4b045a688eb10980afcd11ddb8e64505eda6")]
        public static bool operator ==(global::GeneratorEqualsDemo.Person? left, global::GeneratorEqualsDemo.Person? right)
        {
            return global::System.Collections.Generic.EqualityComparer<global::GeneratorEqualsDemo.Person?>.Default.Equals(left, right);
        }
 
        /// <inheritdoc />
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Equatable.SourceGenerator", "2.0.0+10ad4b045a688eb10980afcd11ddb8e64505eda6")]
        public static bool operator !=(global::GeneratorEqualsDemo.Person? left, global::GeneratorEqualsDemo.Person? right)
        {
            return !(left == right);
        }
 
        /// <inheritdoc />
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Equatable.SourceGenerator", "2.0.0+10ad4b045a688eb10980afcd11ddb8e64505eda6")]
        public override int GetHashCode(){
            int hashCode = 1938039292;
            hashCode = (hashCode * -1521134295) + global::System.StringComparer.OrdinalIgnoreCase.GetHashCode(FirstName!);
            hashCode = (hashCode * -1521134295) + global::System.StringComparer.OrdinalIgnoreCase.GetHashCode(LastName!);
            return hashCode;
 
        }
 
    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/Equatable.Generator

RSCG – Darp.BinaryObjects

RSCG – Darp.BinaryObjects
 
 

name Darp.BinaryObjects
nuget https://www.nuget.org/packages/Darp.BinaryObjects/
link https://github.com/rosslight/Darp.BinaryObjects
author Ross Light GmbH

Serialize bits of data

 

This is how you can use Darp.BinaryObjects .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
   
    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
 
   
    <ItemGroup>
      <PackageReference Include="Darp.BinaryObjects" Version="0.4.0" />
    </ItemGroup>
 
</Project>

The code that you will use is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
using BitsDemo;
using Darp.BinaryObjects;
 
var z = new zlib_header(0x78, 0x9C);
 
var size = z.GetByteCount();
 
// Write the values back to a buffer
var writeBuffer = new byte[size];
if(z.TryWriteLittleEndian(writeBuffer))
{
    Console.WriteLine("writing to buffer" );
    foreach (var item in writeBuffer)
    {
        Console.Write(item+" ");
    }
}
01
02
03
04
05
06
07
08
09
10
using Darp.BinaryObjects;
using System.IO.Compression;
 
namespace BitsDemo;
 
[BinaryObject]
partial record zlib_header(byte cmf, byte flg)
{
     
}

 

The code that is generated is

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// <auto-generated/>
#nullable enable
 
namespace BitsDemo
{
    /// <remarks> <list type="table">
    /// <item> <term><b>Field</b></term> <description><b>Byte Length</b></description> </item>
    /// <item> <term><see cref="cmf"/></term> <description>1</description> </item>
    /// <item> <term><see cref="flg"/></term> <description>1</description> </item>
    /// <item> <term> --- </term> <description>2</description> </item>
    /// </list> </remarks>
    partial record zlib_header : global::Darp.BinaryObjects.IWritable, global::Darp.BinaryObjects.ISpanReadable<zlib_header>
    {
        /// <inheritdoc />
        [global::System.Diagnostics.Contracts.Pure]
        [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Darp.BinaryObjects.Generator", "0.4.0.0")]
        public int GetByteCount() => 2;
 
        /// <inheritdoc />
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Darp.BinaryObjects.Generator", "0.4.0.0")]
        public bool TryWriteLittleEndian(global::System.Span<byte> destination) => TryWriteLittleEndian(destination, out _);
        /// <inheritdoc />
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Darp.BinaryObjects.Generator", "0.4.0.0")]
        public bool TryWriteLittleEndian(global::System.Span<byte> destination, out int bytesWritten)
        {
            bytesWritten = 0;
 
            if (destination.Length < 2)
                return false;
            global::Darp.BinaryObjects.Generated.Utilities.WriteUInt8(destination[0..], this.cmf);
            global::Darp.BinaryObjects.Generated.Utilities.WriteUInt8(destination[1..], this.flg);
            bytesWritten += 2;
 
            return true;
        }
        /// <inheritdoc />
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Darp.BinaryObjects.Generator", "0.4.0.0")]
        public bool TryWriteBigEndian(global::System.Span<byte> destination) => TryWriteBigEndian(destination, out _);
        /// <inheritdoc />
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Darp.BinaryObjects.Generator", "0.4.0.0")]
        public bool TryWriteBigEndian(global::System.Span<byte> destination, out int bytesWritten)
        {
            bytesWritten = 0;
 
            if (destination.Length < 2)
                return false;
            global::Darp.BinaryObjects.Generated.Utilities.WriteUInt8(destination[0..], this.cmf);
            global::Darp.BinaryObjects.Generated.Utilities.WriteUInt8(destination[1..], this.flg);
            bytesWritten += 2;
 
            return true;
        }
 
        /// <inheritdoc />
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Darp.BinaryObjects.Generator", "0.4.0.0")]
        public static bool TryReadLittleEndian(global::System.ReadOnlySpan<byte> source, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out zlib_header? value) => TryReadLittleEndian(source, out value, out _);
        /// <inheritdoc />
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Darp.BinaryObjects.Generator", "0.4.0.0")]
        public static bool TryReadLittleEndian(global::System.ReadOnlySpan<byte> source, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out zlib_header? value, out int bytesRead)
        {
            bytesRead = 0;
            value = default;
 
            if (source.Length < 2)
                return false;
            var ___readcmf = global::Darp.BinaryObjects.Generated.Utilities.ReadUInt8(source[0..1]);
            var ___readflg = global::Darp.BinaryObjects.Generated.Utilities.ReadUInt8(source[1..2]);
            bytesRead += 2;
 
            value = new zlib_header(___readcmf, ___readflg);
            return true;
        }
        /// <inheritdoc />
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Darp.BinaryObjects.Generator", "0.4.0.0")]
        public static bool TryReadBigEndian(global::System.ReadOnlySpan<byte> source, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out zlib_header? value) => TryReadBigEndian(source, out value, out _);
        /// <inheritdoc />
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Darp.BinaryObjects.Generator", "0.4.0.0")]
        public static bool TryReadBigEndian(global::System.ReadOnlySpan<byte> source, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out zlib_header? value, out int bytesRead)
        {
            bytesRead = 0;
            value = default;
 
            if (source.Length < 2)
                return false;
            var ___readcmf = global::Darp.BinaryObjects.Generated.Utilities.ReadUInt8(source[0..1]);
            var ___readflg = global::Darp.BinaryObjects.Generated.Utilities.ReadUInt8(source[1..2]);
            bytesRead += 2;
 
            value = new zlib_header(___readcmf, ___readflg);
            return true;
        }
    }
}
 
namespace Darp.BinaryObjects.Generated
{
    using Darp.BinaryObjects;
    using System;
    using System.Buffers.Binary;
    using System.CodeDom.Compiler;
    using System.Collections.Generic;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
 
    /// <summary>Helper methods used by generated BinaryObjects.</summary>
    [GeneratedCodeAttribute("Darp.BinaryObjects.Generator", "0.4.0.0")]
    file static class Utilities
    {
        /// <summary> Writes a <c>byte</c> to the destination </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void WriteUInt8(Span<byte> destination, byte value)
        {
            destination[0] = value;
        }
        /// <summary> Reads a <c>byte</c> from the given source </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static byte ReadUInt8(ReadOnlySpan<byte> source)
        {
            return source[0];
        }
    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/Darp.BinaryObjects

RSCG – Dolly

RSCG – Dolly
 
 

name Dolly
nuget https://www.nuget.org/packages/Dolly/
link https://github.com/AnderssonPeter/Dolly
author Peter Andersson

Clone objects with ease.

 

This is how you can use Dolly .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="Dolly" Version="0.0.7">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>
    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
</Project>

The code that you will use is

01
02
03
04
05
06
07
08
09
10
// See https://aka.ms/new-console-template for more information
using CloneData;
 
Console.WriteLine("Hello, World!");
Person p = new ();
p.FirstName = "Andrei";
p.LastName = "Ignat";
p.Age = 54;
var p1=p.DeepClone();
Console.WriteLine(p1.Name());
01
02
03
04
05
06
07
08
09
10
11
12
namespace CloneData;
[Dolly.Clonable]
public partial class Person
{
    public string FirstName { get; set; } = "";
    public string LastName { get; set; } = "";
    [Dolly.CloneIgnore]
    public int Age { get; set; }
    public string Name() => $"{FirstName} {LastName}";
 
    public Person[] Childs { get; set; } = [];
}

 

The code that is generated is

1
2
3
4
5
6
7
8
9
using System;
 
namespace Dolly
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
    public class ClonableAttribute : Attribute
    {
    }
}
1
2
3
4
5
6
7
8
9
using System;
 
namespace Dolly
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
    public class CloneIgnoreAttribute : Attribute
    {
    }
}
1
2
3
4
5
6
7
8
9
using System;
namespace Dolly
{
    public interface IClonable<T> : ICloneable
    {
        T DeepClone();
        T ShallowClone();
    }
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
using Dolly;
using System.Linq;
namespace CloneData;
partial class Person : IClonable<Person>
{
    object ICloneable.Clone() => this.DeepClone();
    public virtual Person DeepClone() =>
        new ()
        {
            FirstName = FirstName,
            LastName = LastName,
            Childs = Childs.Select(item => item.DeepClone()).ToArray()
        };
 
    public virtual Person ShallowClone() =>
        new ()
        {
            FirstName = FirstName,
            LastName = LastName,
            Childs = Childs.ToArray()
        };
}

Code and pdf at

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

RSCG – Dapper.AOT

RSCG – Dapper.AOT
 
 

name Dapper.AOT
nuget https://www.nuget.org/packages/Dapper.AOT/
link https://aot.dapperlib.dev/
author Marc Gravell

Generating AOT code for Dapper -hydrating classes from SQL queries.

 

This is how you can use Dapper.AOT .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="Dapper" Version="2.1.35" />
    <PackageReference Include="Dapper.AOT" Version="1.0.31" />
    <PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.2" />
  </ItemGroup>
    <PropertyGroup>
        <InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Dapper.AOT</InterceptorsPreviewNamespaces>
    </PropertyGroup>
    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
</Project>

The code that you will use is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="Dapper" Version="2.1.35" />
    <PackageReference Include="Dapper.AOT" Version="1.0.31" />
    <PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.2" />
  </ItemGroup>
    <PropertyGroup>
        <InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Dapper.AOT</InterceptorsPreviewNamespaces>
    </PropertyGroup>
    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
</Project>
1
2
3
4
// See https://aka.ms/new-console-template for more information
 
Console.WriteLine("Hello, World!");
var p= Product.GetProduct(new SqlConnection("Server=localhost;Database=AdventureWorks2019;Trusted_Connection=True;"), 1);
1
2
3
4
5
6
7
8
9
namespace DapperDemo;
internal partial class Product
{
    public int ID { get; set; }
    public string Name { get; set; } = "";
    public string ProductId { get; set; } = "";
    public static Product GetProduct(SqlConnection connection, int productId) => connection.QueryFirst<Product>(
    "select ID, Name, ProductId from Production.Product where ProductId=@productId", new { productId });
}
1
2
3
4
5
6
global using Dapper;
global using Microsoft.Data.SqlClient;
global using DapperDemo;
 
 
[module: DapperAot]

 

The code that is generated is

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#nullable enable
namespace Dapper.AOT // interceptors must be in a known namespace
{
    file static class DapperGeneratedInterceptors
    {
        [global::System.Runtime.CompilerServices.InterceptsLocationAttribute("D:\\gth\\RSCG_Examples\\v2\\rscg_examples\\Dapper.AOT\\src\\DapperDemo\\DapperDemo\\Product.cs", 8, 93)]
        internal static global::DapperDemo.Product QueryFirst0(this global::System.Data.IDbConnection cnn, string sql, object? param, global::System.Data.IDbTransaction? transaction, int? commandTimeout, global::System.Data.CommandType? commandType)
        {
            // Query, TypedResult, HasParameters, SingleRow, Text, AtLeastOne, BindResultsByName, KnownParameters
            // takes parameter: <anonymous type: int productId>
            // parameter map: productId
            // returns data: global::DapperDemo.Product
            global::System.Diagnostics.Debug.Assert(!string.IsNullOrWhiteSpace(sql));
            global::System.Diagnostics.Debug.Assert((commandType ?? global::Dapper.DapperAotExtensions.GetCommandType(sql)) == global::System.Data.CommandType.Text);
            global::System.Diagnostics.Debug.Assert(param is not null);
 
            return global::Dapper.DapperAotExtensions.Command(cnn, transaction, sql, global::System.Data.CommandType.Text, commandTimeout.GetValueOrDefault(), CommandFactory0.Instance).QueryFirst(param, RowFactory0.Instance);
 
        }
 
 
        private static global::Dapper.CommandFactory<object?> DefaultCommandFactory => global::Dapper.CommandFactory.Simple;
 
        private sealed class RowFactory0 : global::Dapper.RowFactory<global::DapperDemo.Product>
        {
            internal static readonly RowFactory0 Instance = new();
            private RowFactory0() {}
            public override object? Tokenize(global::System.Data.Common.DbDataReader reader, global::System.Span<int> tokens, int columnOffset)
            {
                for (int i = 0; i < tokens.Length; i++)
                {
                    int token = -1;
                    var name = reader.GetName(columnOffset);
                    var type = reader.GetFieldType(columnOffset);
                    switch (NormalizedHash(name))
                    {
                        case 926444256U when NormalizedEquals(name, "id"):
                            token = type == typeof(int) ? 0 : 3; // two tokens for right-typed and type-flexible
                            break;
                        case 2369371622U when NormalizedEquals(name, "name"):
                            token = type == typeof(string) ? 1 : 4;
                            break;
                        case 2521315361U when NormalizedEquals(name, "productid"):
                            token = type == typeof(string) ? 2 : 5;
                            break;
 
                    }
                    tokens[i] = token;
                    columnOffset++;
 
                }
                return null;
            }
            public override global::DapperDemo.Product Read(global::System.Data.Common.DbDataReader reader, global::System.ReadOnlySpan<int> tokens, int columnOffset, object? state)
            {
                global::DapperDemo.Product result = new();
                foreach (var token in tokens)
                {
                    switch (token)
                    {
                        case 0:
                            result.ID = reader.GetInt32(columnOffset);
                            break;
                        case 3:
                            result.ID = GetValue<int>(reader, columnOffset);
                            break;
                        case 1:
                            result.Name = reader.GetString(columnOffset);
                            break;
                        case 4:
                            result.Name = GetValue<string>(reader, columnOffset);
                            break;
                        case 2:
                            result.ProductId = reader.GetString(columnOffset);
                            break;
                        case 5:
                            result.ProductId = GetValue<string>(reader, columnOffset);
                            break;
 
                    }
                    columnOffset++;
 
                }
                return result;
 
            }
 
        }
 
        private sealed class CommandFactory0 : global::Dapper.CommandFactory<object?> // <anonymous type: int productId>
        {
            internal static readonly CommandFactory0 Instance = new();
            public override void AddParameters(in global::Dapper.UnifiedCommand cmd, object? args)
            {
                var typed = Cast(args, static () => new { productId = default(int) }); // expected shape
                var ps = cmd.Parameters;
                global::System.Data.Common.DbParameter p;
                p = cmd.CreateParameter();
                p.ParameterName = "productId";
                p.DbType = global::System.Data.DbType.Int32;
                p.Direction = global::System.Data.ParameterDirection.Input;
                p.Value = AsValue(typed.productId);
                ps.Add(p);
 
            }
            public override void UpdateParameters(in global::Dapper.UnifiedCommand cmd, object? args)
            {
                var typed = Cast(args, static () => new { productId = default(int) }); // expected shape
                var ps = cmd.Parameters;
                ps[0].Value = AsValue(typed.productId);
 
            }
            public override bool CanPrepare => true;
 
        }
 
 
    }
}
namespace System.Runtime.CompilerServices
{
    // this type is needed by the compiler to implement interceptors - it doesn't need to
    // come from the runtime itself, though
 
    [global::System.Diagnostics.Conditional("DEBUG")] // not needed post-build, so: evaporate
    [global::System.AttributeUsage(global::System.AttributeTargets.Method, AllowMultiple = true)]
    sealed file class InterceptsLocationAttribute : global::System.Attribute
    {
        public InterceptsLocationAttribute(string path, int lineNumber, int columnNumber)
        {
            _ = path;
            _ = lineNumber;
            _ = columnNumber;
        }
    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/Dapper.AOT

RSCG – Microsoft.Windows.CsWin32

RSCG – Microsoft.Windows.CsWin32
 
 

name Microsoft.Windows.CsWin32
nuget https://www.nuget.org/packages/Microsoft.Windows.CsWin32/
link https://github.com/microsoft/CsWin32
author Microsoft

Generating WinAPI code in C#

 

This is how you can use Microsoft.Windows.CsWin32 .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="Microsoft.Windows.CsWin32" Version="0.3.106">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>
    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
 
</Project>

The code that you will use is

1
Console.WriteLine("Hello, World!" + Windows.Win32.PInvoke.GetTickCount());
1
GetTickCount

 

The code that is generated is

01
02
03
04
05
06
07
08
09
10
11
// ------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
 
#pragma warning disable CS1591,CS1573,CS0465,CS0649,CS8019,CS1570,CS1584,CS1658,CS0436,CS8981
[assembly: global::System.Reflection.AssemblyMetadata("Microsoft.Windows.CsWin32","0.3.106+a37a0b4b70")]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// ------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
 
#pragma warning disable CS1591,CS1573,CS0465,CS0649,CS8019,CS1570,CS1584,CS1658,CS0436,CS8981
using global::System;
using global::System.Diagnostics;
using global::System.Diagnostics.CodeAnalysis;
using global::System.Runtime.CompilerServices;
using global::System.Runtime.InteropServices;
using global::System.Runtime.Versioning;
using winmdroot = global::Windows.Win32;
namespace Windows.Win32
{
 
    /// <content>
    /// Contains extern methods from "KERNEL32.dll".
    /// </content>
    [global::System.CodeDom.Compiler.GeneratedCode("Microsoft.Windows.CsWin32", "0.3.106+a37a0b4b70")]
    internal static partial class PInvoke
    {
        /// <summary>Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days.</summary>
        /// <returns>The return value is the number of milliseconds that have elapsed since the system was started.</returns>
        /// <remarks>
        /// <para>The resolution of the <b>GetTickCount</b> function is limited to the resolution of the system timer, which is typically in the range of  10 milliseconds to 16 milliseconds. The resolution of the <b>GetTickCount</b> function is not affected by adjustments made by the <a href="https://docs.microsoft.com/windows/desktop/api/sysinfoapi/nf-sysinfoapi-getsystemtimeadjustment">GetSystemTimeAdjustment</a> function. The elapsed time is stored as a <b>DWORD</b> value. Therefore, the time will wrap around to zero if the system is run continuously for 49.7 days. To avoid this problem, use the <a href="https://docs.microsoft.com/windows/desktop/api/sysinfoapi/nf-sysinfoapi-gettickcount64">GetTickCount64</a> function. Otherwise, check for an overflow condition when comparing times. If you need a higher resolution timer, use a <a href="https://docs.microsoft.com/windows/desktop/Multimedia/multimedia-timers">multimedia timer</a> or a <a href="https://docs.microsoft.com/windows/desktop/winmsg/about-timers">high-resolution timer</a>. To obtain the time elapsed since the computer was started, retrieve the System Up Time counter in the performance data in the registry key <b>HKEY_PERFORMANCE_DATA</b>. The value returned is an 8-byte value. For more information, see <a href="https://docs.microsoft.com/windows/desktop/PerfCtrs/performance-counters-portal">Performance Counters</a>. To obtain the time the system has spent in the working state since it was started, use the <a href="https://docs.microsoft.com/windows/desktop/api/realtimeapiset/nf-realtimeapiset-queryunbiasedinterrupttime">QueryUnbiasedInterruptTime</a> function. <div class="alert"><b>Note</b>  The <a href="https://docs.microsoft.com/windows/desktop/api/realtimeapiset/nf-realtimeapiset-queryunbiasedinterrupttime">QueryUnbiasedInterruptTime</a> function produces different results on debug ("checked") builds of Windows, because the interrupt-time count and tick count are advanced by approximately 49 days. This helps to identify bugs that might not occur until the system has been running for a long time. The checked build is available to MSDN subscribers through the <a href="https://msdn.microsoft.com/default.aspx">Microsoft Developer Network (MSDN)</a> Web site.</div> <div> </div></para>
        /// <para><see href="https://learn.microsoft.com/windows/win32/api/sysinfoapi/nf-sysinfoapi-gettickcount#">Read more on docs.microsoft.com</see>.</para>
        /// </remarks>
        [DllImport("KERNEL32.dll", ExactSpelling = true)]
        [DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
        [SupportedOSPlatform("windows5.0")]
        internal static extern uint GetTickCount();
    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/Microsoft.Windows.CsWin32

RSCG – GoLive.Generator.BlazorInterop

RSCG – GoLive.Generator.BlazorInterop
 
 

name GoLive.Generator.BlazorInterop
nuget https://www.nuget.org/packages/GoLive.Generator.BlazorInterop/
link https://github.com/surgicalcoder/BlazorInteropGenerator
author surgicalcoder

Generating interop from C# to javascript for Blazor

 

This is how you can use GoLive.Generator.BlazorInterop .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
 
  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="GoLive.Generator.BlazorInterop" Version="2.0.7">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.0-rc.2.24474.3" />
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.0-rc.2.24474.3" PrivateAssets="all" />
  </ItemGroup>
     
    <ItemGroup>
        <AdditionalFiles Include="BlazorInterop.json" />
    </ItemGroup>
    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
 
 
</Project>

The code that you will use is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
{
  "Files": [
    {
      "Output_DeleteThis_ToHave_InYourProject": "JSInterop.cs",
      "ClassName": "JSInterop",
      "Source": "wwwroot\\blazorinterop.js",
      "Namespace": "GoLive.Generator.BlazorInterop.Playground.Client",
      "ObjectToInterop": "window.blazorInterop",
      "Init": ["window={}"]
    }
  ],
  "InvokeVoidString": "await JSRuntime.InvokeVoidAsync(\"{0}\", {1});",
  "InvokeString": "return await JSRuntime.InvokeAsync<T>(\"{0}\",{1});"
}
1
2
3
4
5
6
7
8
9
window.blazorInterop = {
    showModal: function (dialogId) {
        window.alert('see after this the page title'+dialogId);
        return true;
    },
    setPageTitle: function(title) {
        document.title = title;
    },   
};
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
@page "/"
 
@inject IJSRuntime JS
 
<PageTitle>Home</PageTitle>
 
<h1>Hello, world!</h1>
 
Welcome to your new app.
 
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
 
@code {
    private int currentCount = 0;
 
    private async Task IncrementCount()
    {
        currentCount++;
        var res= await JS.showModalAsync<bool>(currentCount);
        await JS.setPageTitleVoidAsync($" after {currentCount}  the result is " + res);
    }
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>MyTestBlazoe</title>
    <base href="/" />
    <link rel="stylesheet" href="lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="css/app.css" />
    <link rel="icon" type="image/png" href="favicon.png" />
    <link href="MyTestBlazoe.styles.css" rel="stylesheet" />
    <script src="blazorinterop.js" ></script>
</head>
 
<body>
    <div id="app">
        <svg class="loading-progress">
            <circle r="40%" cx="50%" cy="50%" />
            <circle r="40%" cx="50%" cy="50%" />
        </svg>
        <div class="loading-progress-text"></div>
    </div>
 
    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="." class="reload">Reload</a>
        <span class="dismiss">🗙</span>
    </div>
    <script src="_framework/blazor.webassembly.js"></script>
</body>
 
</html>

 

The code that is generated is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System.Threading.Tasks;
using Microsoft.JSInterop;
 
namespace GoLive.Generator.BlazorInterop.Playground.Client
{
    public static class JSInterop
    {
        public static string _window_blazorInterop_showModal => "window.blazorInterop.showModal";
 
        public static async Task showModalVoidAsync(this IJSRuntime JSRuntime, object @dialogId)
        {
            await JSRuntime.InvokeVoidAsync("window.blazorInterop.showModal", @dialogId);
        }
 
        public static async Task<T> showModalAsync<T>(this IJSRuntime JSRuntime, object @dialogId)
        {
            return await JSRuntime.InvokeAsync<T>("window.blazorInterop.showModal", @dialogId);
        }
 
        public static string _window_blazorInterop_setPageTitle => "window.blazorInterop.setPageTitle";
 
        public static async Task setPageTitleVoidAsync(this IJSRuntime JSRuntime, object @title)
        {
            await JSRuntime.InvokeVoidAsync("window.blazorInterop.setPageTitle", @title);
        }
 
        public static async Task<T> setPageTitleAsync<T>(this IJSRuntime JSRuntime, object @title)
        {
            return await JSRuntime.InvokeAsync<T>("window.blazorInterop.setPageTitle", @title);
        }
    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/GoLive.Generator.BlazorInterop

RSCG – Hsu.Sg.FluentMember

RSCG – Hsu.Sg.FluentMember
 
 

name Hsu.Sg.FluentMember
nuget https://www.nuget.org/packages/Hsu.Sg.FluentMember/
link https://github.com/hsu-net/source-generators
author Net Hsu

Adding builder pattern to classes

 

This is how you can use Hsu.Sg.FluentMember .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
  </PropertyGroup>
 
      <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
 
      <ItemGroup>
        <PackageReference Include="Hsu.Sg.FluentMember" Version="2024.101.8-rc175707">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
      </ItemGroup>
 
      
       
</Project>

The code that you will use is

1
2
3
4
5
6
using Builder;
 
var pOld = new Person();
pOld= pOld.WithFirstName("Andrei").WithLastName("Ignat").WithMiddleName("G");
 
System.Console.WriteLine(pOld.FullName());
01
02
03
04
05
06
07
08
09
10
11
12
13
14
namespace Builder;
[Hsu.Sg.FluentMember.FluentMember]
public partial class Person
{
    public string FirstName { get; init; }
    public string? MiddleName { get; init; }
    public string LastName { get; init; }
 
    public string FullName()
    {
        return FirstName + " " + MiddleName + " "+LastName;
    }
     
}

 

The code that is generated is

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// <auto-generated/>
 
using System;
 
namespace Hsu.Sg.FluentMember
{
    /// <summary>
    /// The flag to generate member set method.
    /// </summary>
    [AttributeUsage(
        AttributeTargets.Struct |
        AttributeTargets.Class,
        AllowMultiple = false,
        Inherited = false)]
    internal sealed class FluentMemberAttribute : Attribute
    {
         
        /// <summary>
        ///     The public member are generated.
        /// </summary>
        public bool Public { get; set; } = true;
 
        /// <summary>
        ///     The internal member are generated.
        /// </summary>
        public bool Internal { get; set; }
 
        /// <summary>
        ///     The private member are generated.
        /// </summary>
        public bool Private { get; set; }
 
        /// <summary>
        ///     Only [FluentMemberGen] member are generated.
        /// </summary>
        public bool Only { get; set; }
 
        /// <summary>
        /// The prefix of member name.
        /// </summary>
        /// <remarks>default is `With`</remarks>
        public string Prefix { get; set; } = string.Empty;
    }
 
    [AttributeUsage(AttributeTargets.Field |
        AttributeTargets.Property |
        AttributeTargets.Event,
        AllowMultiple = false,
        Inherited = false)]
    internal sealed class FluentMemberGenAttribute : Attribute
    {
        /// <summary>
        ///   Ignore member.
        /// </summary>
        public bool Ignore { get; set; }
 
        /// <summary>
        /// The specific name of member.
        /// </summary>
        public string Identifier { get; set; } = string.Empty;
 
        /// <summary>
        /// The prefix of member name.
        /// </summary>
        /// <remarks>default is `With`</remarks>
        public string Prefix { get; set; } = string.Empty;
 
        /// <summary>
        /// The modifier of member
        /// </summary>
        /// <remarks>default is <see cref="Accessibility.Inherit"/></remarks>
        public Accessibility Modifier { get; set; } = Accessibility.Inherit;
    }
 
    /// <summary>
    /// The accessibility for fluent member set method.
    /// </summary>
    //[System.DefaultValue(Inherit)]
    internal enum Accessibility
    {
        /// <summary>
        /// Inherit from the member.
        /// </summary>
        Inherit,
        /// <summary>
        /// Is public access.
        /// </summary>
        Public,
        /// <summary>
        /// Is internal access.
        /// </summary>
        Internal,
        /// <summary>
        /// Is protected access.
        /// </summary>
        Protected,
        /// <summary>
        /// Is private access.
        /// </summary>
        Private
    }
     
    /// <summary>
    /// The event assignment
    /// </summary>
    //[System.DefaultValue(Add)]
    public enum EventAssignable
    {
        /// <summary>
        /// To add the event
        /// </summary>
        Add,
        /// <summary>
        /// To remove the event
        /// </summary>
        Remove,
        /// <summary>
        /// To set the event
        /// </summary>
        Assign
    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/Hsu.Sg.FluentMember

RSCG – QueryStringGenerator

RSCG – QueryStringGenerator
 
 

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

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

 

This is how you can use QueryStringGenerator .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="QueryStringGenerator" Version="1.1.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>
    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
</Project>

The code that you will use is

1
2
3
4
5
6
using DemoQuery;
Person p = new();
p.FirstName = "Andrei";
p.LastName = "Ignat";
p.Age = 55;
Console.WriteLine(p.ToQueryString());
01
02
03
04
05
06
07
08
09
10
using QueryStringGenerator;
namespace DemoQuery;
[QueryString]
internal class Person
{
    public string FirstName { get; set; }=string.Empty;
    public int Age {  get; set; }
    public string LastName { get; set; } = string.Empty;
 
}

 

The code that is generated is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// <auto-generated />
 
namespace DemoQuery
{
    [System.CodeDom.Compiler.GeneratedCodeAttribute("QueryStringGenerator", "1.0.0")]
    internal static class QueryStringExtensionForPerson
    {
        public static string ToQueryString(this Person _this)
        {
            if (_this == null)
            {
                return string.Empty;
            }
 
            var sb = new System.Text.StringBuilder();
 
            if (_this.FirstName != null)
            {
                sb.Append($"&firstname={System.Net.WebUtility.UrlEncode(_this.FirstName)}");
            }
 
            if (_this.LastName != null)
            {
                sb.Append($"&lastname={System.Net.WebUtility.UrlEncode(_this.LastName)}");
            }
 
            return sb.ToString();
        }
    }
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
// <auto-generated />
 
namespace QueryStringGenerator
{
    [System.CodeDom.Compiler.GeneratedCodeAttribute("QueryStringGenerator", "1.0.0")]
    internal class QueryStringAttribute : System.Attribute
    {
        public string MethodName { get; set; }
 
        public QueryStringAttribute(string methodName = "ToQueryString")
        {
            MethodName = methodName;
        }
    }
}

Code and pdf at

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

RSCG – GenPack

RSCG – GenPack
 
 

name GenPack
nuget https://www.nuget.org/packages/GenPack/
link https://github.com/dimohy/GenPack
author dimohy

Generating Binary Serialization and properties for class

 

This is how you can use GenPack .

The code that you start with is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="GenPack" Version=" 0.9.0-preview1" OutputItemType="Analyzer" ReferenceOutputAssembly="true" />
    </ItemGroup>
    <PropertyGroup>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
        <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
    </PropertyGroup>
</Project>

The code that you will use is

1
2
3
4
5
6
using SerializerDemo;
 
var p= new Person() { Name= "Andrei Ignat" };
var bytes= p.ToPacket();
var entity = Person.FromPacket(bytes);
Console.WriteLine("name is "+entity.Name);
01
02
03
04
05
06
07
08
09
10
11
12
13
14
using GenPack;
 
namespace SerializerDemo;
 
 
[GenPackable]
public partial record Person
{
 
    public readonly static PacketSchema Schema = PacketSchemaBuilder.Create()
           .@short("Id", "Age description")
           .@string("Name", "Name description")
           .Build();
}

 

The code that is generated is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#pragma warning disable CS0219
namespace SerializerDemo
{
    public partial record Person : GenPack.IGenPackable
    {
        /// <summary>
        /// Age description
        /// </summary>
        public short Id { get; set; }
        /// <summary>
        /// Name description
        /// </summary>
        public string Name { get; set; } = string.Empty;
        public byte[] ToPacket()
        {
            using var ms = new System.IO.MemoryStream();
            ToPacket(ms);
            return ms.ToArray();
        }
        public void ToPacket(System.IO.Stream stream)
        {
            System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
            writer.Write(Id);
            writer.Write(Name);
        }
        public static SerializerDemo.Person FromPacket(byte[] data)
        {
            using var ms = new System.IO.MemoryStream(data);
            return FromPacket(ms);
        }
        public static SerializerDemo.Person FromPacket(System.IO.Stream stream)
        {
            SerializerDemo.Person result = new SerializerDemo.Person();
            System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
            int size = 0;
            byte[] buffer = null;
            result.Id = reader.ReadInt16();
            result.Name = reader.ReadString();
            return result;
        }
    }
}

Code and pdf at

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

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.