RSCG Example–AppSettings editor–part 25

 

 

name AppSettingsEditor
nuget

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

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

This will generate classes code from appsettings . Additionally , it generates API controller for editing and an UI interface
 

The code that you start with is


    {

      "Logging": {

        "LogLevel": {

          "Default": "Information",

          "Microsoft": "Warning",

          "Microsoft.Hosting.Lifetime": "Information"

        }

      },

      "AllowedHosts": "*"

    }


The code that you will use is



    endpoints.MapSettingsView<SettingsJson.appsettings>(Configuration);

 

The code that is generated is


    //------------------------------------------------------------------------------                                                                       

    // <auto-generated>

    //     This code was generated by a tool.

    //     Runtime Version:

    //

    //     Changes to this file may cause incorrect behavior and will be lost if

    //     the code is regenerated.

    // </auto-generated>

    //------------------------------------------------------------------------------

    using System;

    using System.Collections.Generic;

    using System.Runtime.Serialization;

    using Microsoft.Extensions.Configuration;

    using appSettingsEditor;

    namespace SettingsEditor.SettingsJson

    {

    

        //[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]

        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("appSettingsEditorAPI", "2021.3.21.2300")]

        public partial class LogLevel: IAppSettingsConfig<LogLevel> 

        {

            public object GetFromPropertyName(string propName, bool returnNull =false){

                

                propName=propName?.ToUpper();

                

                switch(propName){

                    

                    case "DEFAULT":

                        return this.Default ;

                    

                    case "MICROSOFT":

                        return this.Microsoft ;

                    

                    case "MICROSOFTHOSTINGLIFETIME":

                        return this.MicrosoftHostingLifetime ;

                    

                    default:

                        if(returnNull)

                            return null;

    

                        throw new ArgumentException("cannot found from LogLevel prop "+propName);            

    

                }

                

                

            }

    

            public IEnumerable<string> Properties(){

                

                    yield return "Default" ;

                

                    yield return "Microsoft" ;

                

                    yield return "MicrosoftHostingLifetime" ;

                

                yield break;

            }

            

            [System.Text.Json.Serialization.JsonPropertyName("Default")]

            public string Default { get; set; }

            

            [System.Text.Json.Serialization.JsonPropertyName("Microsoft")]

            public string Microsoft { get; set; }

            

            [System.Text.Json.Serialization.JsonPropertyName("Microsoft.Hosting.Lifetime")]

            public string MicrosoftHostingLifetime { get; set; }

            

            public  LogLevel LoadFromConfig(IConfiguration config)

            { 

                

                    config.GetSection("Logging.LogLevel").Bind(this);

                    return this;

                

            }

        }

    

        //[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]

        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("appSettingsEditorAPI", "2021.3.21.2300")]

        public partial class Logging: IAppSettingsConfig<Logging> 

        {

            public object GetFromPropertyName(string propName, bool returnNull =false){

                

                propName=propName?.ToUpper();

                

                switch(propName){

                    

                    case "LOGLEVEL":

                        return this.LogLevel ;

                    

                    default:

                        if(returnNull)

                            return null;

    

                        throw new ArgumentException("cannot found from Logging prop "+propName);            

    

                }

                

                

            }

    

            public IEnumerable<string> Properties(){

                

                    yield return "LogLevel" ;

                

                yield break;

            }

            

            [System.Text.Json.Serialization.JsonPropertyName("LogLevel")]

            public LogLevel LogLevel { get; set; }

            

            public  Logging LoadFromConfig(IConfiguration config)

            { 

                

                    config.GetSection("Logging").Bind(this);

                    return this;

                

            }

        }

    

        //[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]

        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("appSettingsEditorAPI", "2021.3.21.2300")]

        public partial class appsettings: IAppSettingsConfig<appsettings> 

        {

            public object GetFromPropertyName(string propName, bool returnNull =false){

                

                propName=propName?.ToUpper();

                

                switch(propName){

                    

                    case "LOGGING":

                        return this.Logging ;

                    

                    case "ALLOWEDHOSTS":

                        return this.AllowedHosts ;

                    

                    default:

                        if(returnNull)

                            return null;

    

                        throw new ArgumentException("cannot found from appsettings prop "+propName);            

    

                }

                

                

            }

    

            public IEnumerable<string> Properties(){

                

                    yield return "Logging" ;

                

                    yield return "AllowedHosts" ;

                

                yield break;

            }

            

            [System.Text.Json.Serialization.JsonPropertyName("Logging")]

            public Logging Logging { get; set; }

            

            [System.Text.Json.Serialization.JsonPropertyName("AllowedHosts")]

            public string AllowedHosts { get; set; }

            

            public  appsettings LoadFromConfig(IConfiguration config)

            { 

                

                    return config.Get<appsettings>();

                

            }

        }

    

    }

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

Friday Links 441

  • Retiring old service versions
  • 10 Customer Persona Tools & Templates – Content Harmony
  • (3) Arialdo Martini’s answer to Does the Pomodoro Technique work? What parts of it are the most helpful / least helpful? – Quora
  • The Current State of OpenTelemetry in .NET | Petabridge
  • LisaDziuba/Marketing-for-Engineers: A curated collection of marketing articles & tools to grow your product.
  • Project Manager – Visual Studio Marketplace
  • Degeneracy, Code and Innovation | adl.io | Aaron Longwell of Longwell Consulting, LLC
  • 6 Tips on working from home – Yonder
  • microsoft/FeatureManagement-Dotnet: Microsoft.FeatureManagement provides standardized APIs for enabling feature flags within applications. Utilize this library to secure a consistent experience when developing applications that use patterns such as beta a
  • Using PredicateBuilder with EF Core for Complex Queries | Mitchel Sellers
  • Entity Framework Core 5 vs SQLBulkCopy MichaB BiaBecki Blog
  • microsoft/msquic: Cross platform C implementation of the IETF QUIC protocol.
  • SQL: Why I prefer sequences to IDENTITY columns – The Bit Bucket
  • Generate C# Client API for ASP.NET Web API – CodeProject
  • nikersify/pico: Take browser screenshots in Javascript =���
  • utility | RxJS Primitives
  • Conditionally Apply LINQ Clauses | Khalid Abuhakmeh
  • 7 JavaScript Animation Libraries You Can Use Right Now to Surprise Your Users
  • Simple holidays
  • usablica/intro.js: A better way for new feature introduction and step-by-step users guide for your website and project.
  • RSCG Example–Static To Interface–part 24

     

     

    name Static To Interface
    nuget

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

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

    This will generate code for any static properties of a class to generate interface, record and a class with real behaviour
     

    The code that you start with is

    
        public partial class Helpers
    
        {
    
        public partial ISystem_DateTime FromStaticDate();
    
        }
    
    
    

    The code that you will use is

    
    
        var dateStatic1 = (new Helpers().FromStaticDate());//static        
    
        var dateStatic2 = recISystem_DateTime.MakeNew();//static
    
        var dateVar3 = new clsISystem_DateTime(); //variable = real 
    
        await Task.Delay(10 * 1000);
    
        Console.WriteLine(dateStatic1.Now.Second);
    
        Console.WriteLine(dateStatic2.Now.Second);
    
        Console.WriteLine(dateVar3.Now.Second);
    
    

     

    The code that is generated is

    
        namespace RSCG_Static_Console { 
    
        public interface ISystem_DateTime {
    
        System.DateTime Now  {get;}
    
        System.DateTime UtcNow  {get;}
    
        System.DateTime Today  {get;}
    
        }// interface
    
        //now the partial class
    
        public record recISystem_DateTime (System.DateTime Now,System.DateTime UtcNow,System.DateTime Today) : ISystem_DateTime
    
        { 
    
        public static recISystem_DateTime MakeNew() {
    
        return new recISystem_DateTime(System.DateTime.Now,System.DateTime.UtcNow,System.DateTime.Today);
    
        } //end makenew
    
        } //end record
    
        public class clsISystem_DateTime : ISystem_DateTime 
    
        { 
    
        public  System.DateTime Now  {get { return System.DateTime.Now; } }
    
        public  System.DateTime UtcNow  {get { return System.DateTime.UtcNow; } }
    
        public  System.DateTime Today  {get { return System.DateTime.Today; } }
    
        } //end record
    
        partial class Program {
    
        public partial ISystem_DateTime FromStaticDate() {
    
        return recISystem_DateTime.MakeNew();
    
        } // method
    
        } // class
    
        } // namespace
    
    

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

    RSCG Example – Tiny Types – Part 23

     

     

    name BaseTypes
    nuget

    https://www.nuget.org/packages/AndreasDorfer.BaseTypes/

    link https://github.com/Andreas-Dorfer/base-types
    author Andreas Dorfer

    Generated tiny types from any value type
     

    The code that you start with is

    
        [Int] public partial record DepartmentId;
    
        public Employee GetFromId(int idDepartment, int idEmployee)
    
        {
    
            
    
            return new Employee()
    
            {
    
                ID = idEmployee,
    
                DepartmentId = idDepartment,
    
                Name = "Andrei " + idEmployee
    
        
    
            };
    
        }
    
        public Employee GetFromId(DepartmentId departmentId,  EmployeeId employeeId)
    
        {
    
            return GetFromId(departmentId, employeeId);
    
        }
    
    
    

    The code that you will use is

    
    
        e.GetFromId(10, 34);
    
        e.GetFromId(new DepartmentId(34), new EmployeeId(10));
    
    

     

    The code that is generated is

    
        [System.ComponentModel.TypeConverter(typeof(AD.BaseTypes.Converters.BaseTypeTypeConverter<DepartmentId, int>))]
    
        [System.Text.Json.Serialization.JsonConverter(typeof(AD.BaseTypes.Json.BaseTypeJsonConverter<DepartmentId, int>))]
    
        sealed partial record DepartmentId : System.IComparable<DepartmentId>, System.IComparable, AD.BaseTypes.IBaseType<int>
    
        {
    
            public DepartmentId(int value)
    
            {
    
                this.Value = value;
    
            }
    
            public int Value { get; }
    
            public override string ToString() => Value.ToString();
    
            public int CompareTo(object? obj) => CompareTo(obj as DepartmentId);
    
            public int CompareTo(DepartmentId? other) => other is null ? 1 : System.Collections.Generic.Comparer<int>.Default.Compare(Value, other.Value);
    
            public static implicit operator int(DepartmentId item) => item.Value;
    
            public static DepartmentId Create(int value) => new(value);
    
        }
    
    

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

    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 Example–SourceInject- part 22

       

    name SourceInject
    nuget

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

    link https://github.com/giggio/sourceinject
    author Giovanni Bassi

    Auto register services in startup   The code that you start with is

    
        using Microsoft.Extensions.DependencyInjection;
    
        using System;
    
        using System.Threading.Tasks;
    
        
    
        namespace AutoRegisterBL
    
        {
    
            [Inject(ServiceLifetime.Transient)]
    
            public class Repo
    
            {
    
                public async Task<person> GetFromId(int id)
    
                {
    
                    await Task.Delay(1000);
    
                    return new Person()
    
                    {
    
                        ID = id,
    
                        Name = " Andrei Ignat " + id
    
                    };
    
                }
    
            }
    
        }
    
    
    

    The code that you will use is

    
    
        //in startup.cs
    
        services.DiscoverInAutoRegisterBL();
    
    

       The code that is generated is

    
        // <auto-generated>
    
        using Microsoft.Extensions.DependencyInjection;
    
        
    
        public static class GeneratedServicesExtension
    
        {
    
            public static void DiscoverInAutoRegisterBL(this IServiceCollection services) =&gt; services.Discover();
    
            internal static void Discover(this IServiceCollection services)
    
            {
    
                services.AddTransient<autoregisterbl.repo>();
    
        
    
            }
    
        }
    
        
    
        public static class AutoRegisterBLDiscoverer
    
        {
    
            public static void Discover(IServiceCollection services) =&gt; services.Discover();
    
        }
    
    

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

    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

    Friday Links 437

  • Software architecture diagrams – which tool should we use? – DEV
  • LisaDziuba/Marketing-for-Engineers: A curated collection of marketing articles & tools to grow your product.
  • microsoft/MS-Lumos: Tools to compare metrics between datasets, accounting for population differences and invariant features.
  • Advanced Linux Commands Cheat Sheet | Red Hat Developer
  • Foam | A personal knowledge management and sharing system for VSCode
  • Development With A Dot – Introducing SharedFlat
  • How Stack Overflow hires engineers – Stack Overflow Blog
  • 30% didn t kill the App Store model. SaaS did. | Capiche
  • If you wanna make your own open-source chip, just Google it. Literally. Web giant says it’ll fab them for free ” The Register
  • ASP.NET Core Web API + DynamoDB Locally – CodeProject
  • treosh/web-vitals-reporter: A tiny (800 B) utility to simplify web vitals reporting.
  • nathan-osman/chronosnap: Android app for capturing timed photo sequences.
  • What Do You Do Better Than the Cloud? – Brent Ozar Unlimited�
  • What does idempotent mean? ” Particular Software
  • You Can Download the Entirety of English Wikipedia to Browse Offline
  • LiveSharp Integrated hot-reload solution for C# projects
  • Extreme programming meets systematic testing using Coyote – Open Source Blog
  • .Net Core Developer Roadmap. A developer roadmap for all the tools && | by Adem Zeina | Developers Cafe | Medium
  • It’s probably time to stop recommending Clean Code @ Things Of Interest
  • Animate.css
  • RSCG example–Query Generator–part 21

       

    name DatabaseToWebAPI
    nuget

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

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

    This will generate code (WebAPI/Swagger) for any table/view from SqlServer. You can see the table via Angular   The code that you start with is

    
        //add queries.json with all the connection string and tables necessary
    
        //add in templates folder the files to generate controllers
    
        using RoslynQueryGenerator;
    
        using System.Collections.Generic;
    
        //TODO : modify namespace
    
        namespace WebFromQuery.Classes
    
        {
    
            public class FieldDescription
    
            {
    
                public string ItemName { get; set; }
    
                public string QueryName { get; set; }
    
        
    
                public string FieldName { get; set; }
    
                public string FieldType { get; set; }
    
        
    
                public SearchField DefaultValue { get; set; }
    
            }
    
            public class DisplayData
    
            {
    
                public string QueryName { get; set; }
    
                public string ItemName { get; set; }
    
                public FieldDescription[] FieldNames { get; set; }
    
                public Dictionary<string  , object="">[] Values { get; set; }
    
            }
    
          
    
        }
    
        
    
    
    

    The code that you will use is

    
    
        //In Startup
    
        services.AddFactoryGenerated();
    
        app.UseDefaultFiles();
    
        app.UseStaticFiles();
    
    

       The code that is generated is

    
        //ApplicationDbContext : too much lines - see project
    
        //Controllers : too much lines - see project
    
    

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

    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

    Friday Links 436

  • Troy Hunt:6Sustaining Performance Under Extreme Stress
  • mapbox/pixelmatch: The smallest, simplest and fastest JavaScript pixel-level image comparison library
  • tauri-apps/tauri: Framework agnostic toolchain for building highly secure native apps that have tiny binaries and are very fast.
  • Learn and use Composition in JavaScript and TypeScript – DEV
  • Data Modeling and Partitioning for Relational Workloads | Azure Cosmos DB Blog
  • Microservices vs. Monoliths: An Operational Comparison The New Stack
  • Writing production systems the wrong way, on purpose – Ayende @ Rahien
  • Feature Rejection: sending an email alert from RavenDB – Ayende @ Rahien
  • Handling SPA Fallback Paths in a Generic ASP.NET Core Server – Rick Strahl’s Web Log
  • Adding an endpoint graph to your ASP.NET Core application: Visualizing ASP.NET Core 3.0 endpoints using GraphvizOnline – Part 2
  • ekonbenefits/impromptu-interface: Static interface to dynamic implementation (duck casting). Uses the DLR combined with Reflect.Emit.
  • anuraghazra/github-readme-stats: Dynamically generated stats for your github readmes
  • nwtgck/actions-comment-run: Execute any script in a GitHub issue comment
  • peaceiris/actions-label-commenter: Label Commenter Action – Label triggered GitHub Actions for posting a template message. After commenting, it can automatically close or reopen issues. Of course, it also can manage pull requests.
  • Byte Down: Making Netflix s Data Infrastructure Cost-Effective | by Netflix Technology Blog | Jul, 2020 | Netflix TechBlog
  • matiassingers/awesome-readme: A curated list of awesome READMEs
  • Checking homework and the 10x programmer – Ayende @ Rahien
  • Hacking the Admin SQLServerCentral
  • 10 Awesome JavaScript Libraries You Should Try Out in 2020
  • PostSharp Blog | Thinking beyond Roslyn source generators and aspect-oriented programming
  • 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.