RSGC-JSON to Class- part 4

 

 

name JsonByExampleGenerator
nuget

https://www.nuget.org/packages/JsonByExampleGenerator/

link https://github.com/hermanussen/JsonByExampleGenerator/
author Robin Hermanussen

This will generate C# classes from json files.
 

The code that you start with is


    {

    "FirstName": "Andrei",

    "LastName": "Ignat",

    "Blog": "http://msprogrammer.serviciipeweb.ro/"


The code that you will use is



    var p1 = new Person();

    p1.Blog = "http://msprogrammer.serviciipeweb.ro/";

    var config = new ConfigurationBuilder()

      .AddJsonFile("persons.json")

      .Build();

    

    var p = config.Get<Person>();

    var p2 = Person.FromConfig(config);

 

The code that is generated is


    [DataContract(Name = "Person", Namespace = "JsonToClass.Json.Persons")]

    public partial class Person

    {

    [DataMember(Name = "FirstName", EmitDefaultValue = false, Order = 0)]

    public string FirstName { get; set; }

    [DataMember(Name = "LastName", EmitDefaultValue = false, Order = 1)]

    public string LastName { get; set; }

    [DataMember(Name = "Blog", EmitDefaultValue = false, Order = 2)]

    public string Blog { get; set; }

    

    public static Person FromConfig([System.Diagnostics.CodeAnalysis.NotNull] IConfiguration config)

    {

    return config.Get<Person>();

    }

    }

Example Code: https://github.com/ignatandrei/RSCG_Examples/tree/main/JsonToClass

All RSCG

NrBlog Post
1RSCG–part 1
2RSCG- AppVersion–part 2
3http://msprogrammer.serviciipeweb.ro/2021/02/17/rsgc-enum-part-3/
4RSGC-JSON to Class- part 4
5RSGC-Constructor – Deconstructor – part 5
6RSGC – DTO Mapper – part 6
7RSGC – Skinny Controllers- part 7
8RSGC-Builder Design Pattern – part 8
9RSGC- MetadataFromObject – part 9
10RSGC- Dynamic Mock – part 10
11RSCG- Method Decorator – part 11
12RSCG – Curry – Partial function – part 12
13RSCG- part 13 – IFormattable
14RSCG- part 14 – DP_Decorator
15RSCG- part 15 – Expression Generator
16RSCG- part 16 – Many Others
17RSCG- the book
18RSCG–Template Rendering- part 17
19CI Version
20HttpClientGenerator
21Query from database
22AutoRegister
23TinyTypes
24Static2Interface
25AppSettings
26Properties
27
Roslyn Source Code Generators

RSGC-Enum-part 3

 

 

name Enum
nuget

https://www.nuget.org/packages/AOPMethodsCommon/
https://www.nuget.org/packages/AOPMethodsGenerator/

link http://msprogrammer.serviciipeweb.ro/category/roslyn/
author Andrei Ignat

This will generate code to fast parsing a int or a string to an enum
 

The code that you start with is


    [AutoEnum(template = EnumMethod.GenerateExtensionCode)]

    public enum MathematicalOperation

    {

    None=0,

    Add=1,

    Multiplication=2

    }


The code that you will use is



    var fromInt = enumMathematicalOperation.ParseExactMathematicalOperation(1);

    var fromString = enumMathematicalOperation.ParseExactMathematicalOperation("add");

    Console.WriteLine(fromInt + "-"+fromString);

 

The code that is generated is


      [GeneratedCode("AOPMethods", "")] 

      [CompilerGenerated]

      public  static partial class enumMathematicalOperation{ 

       /*

        public static int idMathematicalOperation(){

        System.Diagnostics.Debugger.Break();

        return 1;

        }

        */

        public static RSCG_Enum.MathematicalOperation ParseExactMathematicalOperation(this long value, RSCG_Enum.MathematicalOperation? defaultValue = null){

                if(0 == value)

                    return RSCG_Enum.MathematicalOperation.None;

                        if(1 == value)

                    return RSCG_Enum.MathematicalOperation.Add;

                        if(2 == value)

                    return RSCG_Enum.MathematicalOperation.Multiplication;

            

            if(defaultValue != null)

                return defaultValue.Value;

    

            throw new ArgumentException("cannot find " + value +" for RSCG_Enum.MathematicalOperation  ");

        }

       

        public static RSCG_Enum.MathematicalOperation ParseExactMathematicalOperation(this string value, RSCG_Enum.MathematicalOperation? defaultValue = null){

            //trying to see if it is a value inside

            //if(!string.IsNullOrWhiteSpace)

            if(long.TryParse(value, out long valueParsed)){

                return ParseExactMathematicalOperation(valueParsed);

            }

    

                if(0==string.Compare("None" , value, StringComparison.InvariantCultureIgnoreCase))

                    return RSCG_Enum.MathematicalOperation.None;

                        if(0==string.Compare("Add" , value, StringComparison.InvariantCultureIgnoreCase))

                    return RSCG_Enum.MathematicalOperation.Add;

                        if(0==string.Compare("Multiplication" , value, StringComparison.InvariantCultureIgnoreCase))

                    return RSCG_Enum.MathematicalOperation.Multiplication;

            

    

            if(defaultValue != null)

                return defaultValue.Value

            throw new ArgumentException("cannot find " + value +" for RSCG_Enum.MathematicalOperation  ");

        }

        /*

        

        */

        

      }

Example Code: https://github.com/ignatandrei/RSCG_Examples/tree/main/Enum

All RSCG

NrBlog Post
1RSCG–part 1
2RSCG- AppVersion–part 2
3http://msprogrammer.serviciipeweb.ro/2021/02/17/rsgc-enum-part-3/
4RSGC-JSON to Class- part 4
5RSGC-Constructor – Deconstructor – part 5
6RSGC – DTO Mapper – part 6
7RSGC – Skinny Controllers- part 7
8RSGC-Builder Design Pattern – part 8
9RSGC- MetadataFromObject – part 9
10RSGC- Dynamic Mock – part 10
11RSCG- Method Decorator – part 11
12RSCG – Curry – Partial function – part 12
13RSCG- part 13 – IFormattable
14RSCG- part 14 – DP_Decorator
15RSCG- part 15 – Expression Generator
16RSCG- part 16 – Many Others
17RSCG- the book
18RSCG–Template Rendering- part 17
19CI Version
20HttpClientGenerator
21Query from database
22AutoRegister
23TinyTypes
24Static2Interface
25AppSettings
26Properties
27
Roslyn Source Code Generators

RSCG- AppVersion–part 2

 

 

name ThisAssembly
nuget https://www.nuget.org/packages/ThisAssembly
link https://www.clarius.org/ThisAssembly/
author Daniel Cazzulino

The ThisAssembly.Info allows you access to the Assembly Information as constants, instead of going to reflection each time. I found useful to see the assembly version right away in any project that I have.

 

The code that you start with is in .csproj

<PropertyGroup>
<Version>2021.2.15.800</Version>
</PropertyGroup>

The code that you will use is

var strVersion = ThisAssembly.Info.Version;
Console.WriteLine(strVersion);

 

The code that is generated is

/// <summary>
/// Provides access to the current assembly information as pure constants, 
///  without requiring reflection.
/// </summary>
partial class ThisAssembly
{
    /// <summary>
    /// Gets the AssemblyInfo attributes.
    /// </summary>
    [GeneratedCode("ThisAssembly.AssemblyInfo", "1.0.0")]
    [CompilerGenerated]
    public static partial class Info
    {
        public const string Company = @"RSCG_Version";

        public const string Configuration = @"Debug";

        public const string FileVersion = @"2021.2.15.800";

        public const string InformationalVersion = @"2021.2.15.800";

        public const string Product = @"RSCG_Version";

        public const string Title = @"RSCG_Version";

        public const string Version = @"2021.2.15.800";

    }
}

Example Code: https://github.com/ignatandrei/RSCG_Examples/tree/main/ApplicationVersion

All RSCG

NrBlog Post
1RSCG–part 1
2RSCG- AppVersion–part 2
3http://msprogrammer.serviciipeweb.ro/2021/02/17/rsgc-enum-part-3/
4RSGC-JSON to Class- part 4
5RSGC-Constructor – Deconstructor – part 5
6RSGC – DTO Mapper – part 6
7RSGC – Skinny Controllers- part 7
8RSGC-Builder Design Pattern – part 8
9RSGC- MetadataFromObject – part 9
10RSGC- Dynamic Mock – part 10
11RSCG- Method Decorator – part 11
12RSCG – Curry – Partial function – part 12
13RSCG- part 13 – IFormattable
14RSCG- part 14 – DP_Decorator
15RSCG- part 15 – Expression Generator
16RSCG- part 16 – Many Others
17RSCG- the book
18RSCG–Template Rendering- part 17
19CI Version
20HttpClientGenerator
21Query from database
22AutoRegister
23TinyTypes
24Static2Interface
25AppSettings
26Properties
27
Roslyn Source Code Generators

RSCG–part 1

Roslyn Source Code Generators are a easy way to generate automatically code that can be injected at compile time. This code can be generated on some template file or based on existing code or both . It works by intercepting at compile time the result of compilation of the existing source code and adding to this compilation other files. It cannot modify the code, just add to it.

You can see a deep tutorial about how to do it at https://khalidabuhakmeh.com/dotnet-5-source-generators-jump-start . Also, you can read more at https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/ and at https://github.com/dotnet/roslyn/blob/master/docs/features/source-generators.cookbook.md .

There are a fair amount of them  – and I intend to detail their use .  That means

1. I will show how they can be useful for you

2. I will show examples with source code .

3. Make a video with this.

All RSCG

NrBlog Post
1RSCG–part 1
2RSCG- AppVersion–part 2
3http://msprogrammer.serviciipeweb.ro/2021/02/17/rsgc-enum-part-3/
4RSGC-JSON to Class- part 4
5RSGC-Constructor – Deconstructor – part 5
6RSGC – DTO Mapper – part 6
7RSGC – Skinny Controllers- part 7
8RSGC-Builder Design Pattern – part 8
9RSGC- MetadataFromObject – part 9
10RSGC- Dynamic Mock – part 10
11RSCG- Method Decorator – part 11
12RSCG – Curry – Partial function – part 12
13RSCG- part 13 – IFormattable
14RSCG- part 14 – DP_Decorator
15RSCG- part 15 – Expression Generator
16RSCG- part 16 – Many Others
17RSCG- the book
18RSCG–Template Rendering- part 17
19CI Version
20HttpClientGenerator
21Query from database
22AutoRegister
23TinyTypes
24Static2Interface
25AppSettings
26Properties
27
Roslyn Source Code Generators

[ADCES]Programmer2Head & DataPreparation with JupyterNotebooks

Prezentare 1:
Titlu: De la “just a programmer” la “head of his software company”
Descriere : Despre o calatorie care a inceput, nu intr-un garaj american, ci la Automatica, si care a continuat pe 3 continente
Prezentator: Radu Iovescu , https://www.linkedin.com/in/riovescu/
Prezentare 2:
Titlu: Data Preparation with Jupyter Notebook and DataFrame
Descriere::
Prezentator: Daniel Costea, MVP, https://mvp.microsoft.com/en-us/PublicProfile/5003534

Va astept miine, 9 februarie , la https://www.meetup.com/Bucharest-A-D-C-E-S-Meetup/events/275609419/

AOPMethods–dogfooding

I was trying to apply AOPMethods to – surprise! –  AOPMethods project itself. And I have discovered a new reason: I do not want to make the methods public. I just want to put try/catch around them to know what is wrong.

The fast – and not so good – idea was to transform

MethodPrefix =”pub”

into a

Dictionary<MethodsPrefix: string,  VIsibilty: string>

in order to pass something like that

{ “pub”, “public” } , {“prv”, “private”}

The second idea was better : what if I allow multiple instances and generate accordingly  ?

So I came up with this definition

[AutoMethods(template = TemplateMethod.MethodWithPartial, MethodPrefix =”pub”)]
[AutoMethods(template = TemplateMethod.CustomTemplateFile,CustomTemplateFileName =”privateTryCatch.txt”,  MethodSuffix = “bup”)]
partial class Person

And the code  processes both attributes – and generates the code. One slightly problem: Cannot have GeneratedCode and CompilerGenerated on both generated files. But – it works!

AOPMethods–adding partial functions and enums

I was finishing the AOPMethods  – and what I have been thinking is – why not add partial functions ? I have added Console.Write, but … this seems more general… So , now , this is the Person class definition with the partial function definition

[AutoMethods(template = TemplateMethod.MethodWithPartial, MethodPrefix =”pub”, MethodSuffix =”bup”)]
partial class Person
{
     partial void Method_Start(string methodName)
     {
         Console.WriteLine($”start {methodName}”);
     }
     partial void Method_End(string methodName)
     {
         Console.WriteLine($”end {methodName}”);
     }

And, because I have finished the AOPMethods , I have been thinking about the problems with enums  – every time I parse the enum. What about a autogenerated function ? So now , with this definition:

[AutoEnum(template = EnumMethod.GenerateExtensionCode)]
     /// <summary>
     /// my test
     /// </summary>
     public enum Test:long
     {
         a,
         //the b should be 1
         b,
         /// <summary>
         /// x should be 2
         /// </summary>
         x=5,
         y=7

    }

I can do this

long y = 7;
var s = y.ParseExactTest2();
var q=y.ToString().ParseExactTest2();
var s1 = s.ToString().ParseExactTest2();

For reference, the generated code with Roslyn AOPMethods is:

public static AOPMethodsTest.Test2 ParseExactTest2(this long value, AOPMethodsTest.Test2? defaultValue = null)
{
     if (0 == value)
         return AOPMethodsTest.Test2.a1;
     if (1 == value)
         return AOPMethodsTest.Test2.b1;
     if (5 == value)
         return AOPMethodsTest.Test2.x1;
     if (7 == value)
         return AOPMethodsTest.Test2.y1;

    if (defaultValue != null)
         return defaultValue.Value;

    throw new ArgumentException(“cannot find ” + value + ” for AOPMethodsTest.Test2  “);
}

public static AOPMethodsTest.Test2 ParseExactTest2(this string value, AOPMethodsTest.Test2? defaultValue = null)
{
     //trying to see if it is a value inside
     //if(!string.IsNullOrWhiteSpace)
     if (long.TryParse(value, out long valueParsed))
     {
         return ParseExactTest2(valueParsed);
     }

    if (0 == string.Compare(“a1”, value, StringComparison.InvariantCultureIgnoreCase))
         return AOPMethodsTest.Test2.a1;
     if (0 == string.Compare(“b1”, value, StringComparison.InvariantCultureIgnoreCase))
         return AOPMethodsTest.Test2.b1;
     if (0 == string.Compare(“x1”, value, StringComparison.InvariantCultureIgnoreCase))
         return AOPMethodsTest.Test2.x1;
     if (0 == string.Compare(“y1”, value, StringComparison.InvariantCultureIgnoreCase))
         return AOPMethodsTest.Test2.y1;

     if (defaultValue != null)
         return defaultValue.Value;

    throw new ArgumentException(“cannot find ” + value + ” for AOPMethodsTest.Test2  “);
}

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.