Category: .NET Core

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  “);
}

AOP Methods–Problems in running and solving

The problems that I have encountered were:

1.  The ThisAssembly  RoslynGenerator that I use should not be put as reference in the nuget. I have fixed this by adding

<PackageReference Include=”ThisAssembly.AssemblyInfo” Version=”1.0.0″ ReferenceOutputAssembly=”false” />

2. I have problems generating code to async code with Task . The problem was that I have added logging ( very basic – Console.WriteLine) and the order of the logging was errating. I figured out that I should must use the async /await and then my template was modified as

strAwait = “”
strAsync =””
if mi.IsAsync == true
     strAwait = ” await “
     strAsync  = ” async “
end

public {{strAsync}} {{mi.ReturnType}} {{mi.NewName}} ({{mi.parametersDefinitionCSharp }} {{separator}} 

//more code

{{
     if mi.ReturnsVoid == false
}}
     return
{{
     end
}}
{{  strAwait }}

{{mi.Name}}({{ mi.parametersCallCSharp }});

And this is worth noting.

AOP Methods–Code

The code is not so much different from SkinnyControllers : Implement ISourceGenerator , putting the Generator attribute on the class

[Generator]
    public partial class AutoActionsGenerator : ISourceGenerator

inspecting the classes if they have the common attribute , generating code with Scriban

The problem was : How can the AOPMethods can

  1. differentiate between the private function that must be made public
  2. generate the code for a similar public function, with same parameters (and maybe more) , but with different name ?

So I decide to go the route of convention: The programmer will declare the private function that he wants to autmatically make public ( and add templating code ) with a prefix or a suffix . This will be declared into the attribute of the class – and that will be all.

For example , I have this method

public  string FullName()
{
            
     return FirstName + ” ” + LastName;
}

That I want to monitor ( add logs, info and so on ) . I will make it private and start with pub

private string pubFullName()
{
            
     return FirstName + ” ” + LastName;
}

Then , on the class , I will declare the pub prefix

[AutoMethods(template = TemplateMethod.CallerAtttributes, MethodPrefix =”pub”, MethodSuffix =”bup”)]

And the following will be generated

public string FullName(
[CallerMemberName] string memberName = “”,
[CallerFilePath] string sourceFilePath = “”,
[CallerLineNumber] int sourceLineNumber = 0)
{
     try
     {
         Console.WriteLine(“–pubFullName start “);
         Console.WriteLine(“called class :” + memberName);
         Console.WriteLine(“called file :” + sourceFilePath);
         Console.WriteLine(“called line :” + sourceLineNumber);

        return

    pubFullName();
     }
     catch (Exception ex)
     {
         Console.WriteLine(“error in pubFullName:” + ex.Message);
         throw;
     }
     finally
     {
         Console.WriteLine(“——–pubFullName end”);
     }

}

The caller attributes templates can be found at  AOP_With_Roslyn\AOPMethods\AOPMethods\templates\CallerAtttributes.txt

//——————————————————————————
// <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>
//——————————————————————————
using System;
using System.CodeDom.Compiler;
using System.Runtime.CompilerServices;

namespace {{NamespaceName}} {

    /// <summary>
     /// Generates code from  {{ClassName}}
     /// </summary>
   [GeneratedCode(“AOPMethods”, “{{version}}”)]
   [CompilerGenerated]
   partial class {{ClassName}}{
    /*
     public int id(){
     System.Diagnostics.Debugger.Break();
     return 1;
     }
     */
     {{~ for mi in Methods ~}}
         {{
             separator = “”
             if(mi.NrParameters > 0)
                 separator = “,”
             end
             strAwait = “”
             strAsync =””
             if mi.IsAsync == true
                 strAwait = ” await “
                 strAsync  = ” async “
             end
         }}
         public {{strAsync}} {{mi.ReturnType}} {{mi.NewName}} ({{mi.parametersDefinitionCSharp }} {{separator}} 
         [CallerMemberName] string memberName = “”,
         [CallerFilePath] string sourceFilePath = “”,
         [CallerLineNumber] int sourceLineNumber = 0){
             try{
                 Console.WriteLine(“–{{mi.Name}} start “);
                 Console.WriteLine(“called class :”+memberName );
                 Console.WriteLine(“called file :”+sourceFilePath );
                 Console.WriteLine(“called line :”+sourceLineNumber );
             {{
                 if mi.ReturnsVoid == false
             }}
                 return
             {{
                 end
             }}
             {{  strAwait }}

            {{mi.Name}}({{ mi.parametersCallCSharp }});
             }
             catch(Exception ex){
                 Console.WriteLine(“error in {{mi.Name}}:” + ex.Message);
                 throw;
             }
             finally{
                 Console.WriteLine(“——–{{mi.Name}} end”);
             }

         }

     
     {{~ end ~}}   
    
   }
}             

You can add logging , security, anything else that is a vertical to the business

AOP Methods–Introduction

As I have done with Roslyn for SkinnyControllers , I said – what about generating public methods at compile time ?

For example, what if this method

private string pubFullName()
{

return FirstName + ” ” + LastName;

}

 

is transformed into this

public string FullName(
[CallerMemberName] string memberName = “”,
[CallerFilePath] string sourceFilePath = “”,
[CallerLineNumber] int sourceLineNumber = 0)
{
try
{
Console.WriteLine(“–pubFullName start ” + _cc);
Console.WriteLine(“called class :” + memberName);
Console.WriteLine(“called file :” + sourceFilePath);
Console.WriteLine(“called line :” + sourceLineNumber);

return pubFullName();
}
catch (Exception ex)
{
Console.WriteLine(“error in pubFullName:” + ex.Message);
throw;
}
finally
{
Console.WriteLine(“——–pubFullName end”);

}
}

automatically, based on a template ? And all methods will have this ?

Enter AOP Methods : https://www.nuget.org/packages/AOPMethodsGenerator/  and https://www.nuget.org/packages/AOPMethodsCommon/

The first one is the generator. The second one is containing the attribute that tells to transform.

AutoActions for Skinny controllers–custom template

Now I want to let the user make his own template. For this, I have enriched the attribute AutoActionsAttribute with a

public string CustomTemplateFileName { get; set; }

 

The code was pretty easy, just reading from GeneratorExecutionContext . AdditionalFiles instead of reading from the template in the dll

 

switch (templateId)
{

case TemplateIndicator.None:
	context.ReportDiagnostic(DoDiagnostic(DiagnosticSeverity.Info, $"class {myController.Name} has no template "));
	continue;
case TemplateIndicator.CustomTemplateFile:

	var file = context.AdditionalFiles.FirstOrDefault(it => it.Path.EndsWith(templateCustom));
	if (file == null)
	{
		context.ReportDiagnostic(DoDiagnostic(DiagnosticSeverity.Error, $"cannot find {templateCustom} for  {myController.Name} . Did you put in AdditionalFiles in csproj ?"));
		continue;
	}
	post = file.GetText().ToString();
	break;

default:
	using (var stream = executing.GetManifestResourceStream($"SkinnyControllersGenerator.templates.{templateId}.txt"))
	{
		using var reader = new StreamReader(stream);
		post = reader.ReadToEnd();

	}
	break;
}

 

There are 2 small catches

1 see the EndsWith  ? The GeneratorExecutionContext . AdditionalFiles  gives you the full path

2. the additional files should be registered in the .csproj

<ItemGroup>
<AdditionalFiles Include=”Controllers\CustomTemplate1.txt” />
</ItemGroup>

 

Now the user can define his own template for the controller like this


[AutoActions(template = TemplateIndicator.CustomTemplateFile, FieldsName = new[] { "*" } ,CustomTemplateFileName = "Controllers\\CustomTemplate1.txt")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public partial class CustomTemplateController : ControllerBase
    {
        private readonly RepositoryWF repository;

        public CustomTemplateController ()
        {
            //do via DI
            repository = new RepositoryWF();
        }

    }

And this is all ! ( ok. some documentation should be involved)

AutoActions for Skinny controllers–code improvements and more docs

I realized that this code

Assembly.GetExecutingAssembly();

was executing for each controller. So I decided to move to a class variable and attribute once.

Also, I may want to have all fields – so I decided to express via a special field *

The code modifications were, thanks to Linq, pretty small:

bool All = fields.Contains(“*”);

var memberFields = myController
     .GetMembers()
     .Where(it => All || fields.Contains(it.Name))

Also,  modified the documents to show most errors and their problems:

error CS0260: Missing partial modifier on declaration of

Failed to load API definition.
Fetch error undefined /swagger/v1/swagger.json

Any open source project becomes a marathon, not a sprint.

AutoActions for Skinny controllers-documentation improvements

One improvement is to move  Initialize in other partial class. . It was difficult every time I need to activate the debugger

public void Initialize(GeneratorInitializationContext context)
         {

            context.RegisterForSyntaxNotifications(() => new SyntaxReceiverFields());
             //in development
             //Debugger.Launch();
         }

Second was to improve the Nuget package description. I have added

<Version>2020.11.28.2108</Version>
    <Authors>Andrei Ignat</Authors>
    <PackageTags>RoslynCodeGenerators C# CSharp SkinnyControllers</PackageTags>
    <PackageProjectUrl>https://github.com/ignatandrei/AOP_With_Roslyn</PackageProjectUrl>
    <RepositoryUrl>https://github.com/ignatandrei/AOP_With_Roslyn</RepositoryUrl>
    <RepositoryType>GIT</RepositoryType>

     <PackageLicenseExpression>MIT</PackageLicenseExpression>
      <Copyright>MIT</Copyright>

Third was to improve documentation. I was adding a readme.txt.

<ItemGroup>
   <None Include=”../readme.txt”>
     <Pack>True</Pack>
     <PackagePath></PackagePath>
   </None>
</ItemGroup>

Fourth – automatic builds. You can see them at https://github.com/ignatandrei/AOP_With_Roslyn/actions

AutoActions for Skinny controllers–second template

The second template was pretty easy. All the date was inside the class definition :

class ClassDefinition
     {
         public string ClassName;
         public string NamespaceName;
         public Dictionary<string,MethodDefinition[]> DictNameField_Methods;
         public string version = ThisAssembly.Info.Version;   
     }
     class MethodDefinition
     {
         public string Name { get; set; }
         public string FieldName { get; set; }
         public string ReturnType;
         public bool ReturnsVoid;
         //name, type
         public Dictionary<string, ITypeSymbol> Parameters;

        public string parametersDefinitionCSharp => string.Join(“,”, Parameters.Select(it => it.Value.ContainingNamespace + “.” + it.Value.Name + ” ” + it.Key).ToArray());
         public string parametersCallCSharp => string.Join(“,”, Parameters.Select(it => it.Key).ToArray());

        public int NrParameters
         {
             get
             {
                 return Parameters?.Count ?? 0;
             }
         }

    }

so the only thing that I needed is to modify the template definition

I was having one problem: I have hardcoded the names in the first stage- so I have had problems with duplicate names: . As an example, it was:

namespace {{NamespaceName}} {
   [GeneratedCode(“SkinnyControllersGenerator”, “{{version}}”)]
   [CompilerGenerated]
   partial class WeatherForecastController{

and now it is

namespace {{NamespaceName}} {
   [GeneratedCode(“SkinnyControllersGenerator”, “{{version}}”)]
   [CompilerGenerated]
   partial class {{ClassName}}{

Besides this, the SCRIBAN documentation is pretty self explanatory to male the second template ready

AutoActions for Skinny controllers- templating-part2

Now I want to add templates to my controller  generators . But this feature changed the whole perspective about the project. Why ? Because a template do not apply just to a field – but to the whole controller. So instead of having attributes on the field

[AutoActions]

private readonly RepositoryWF repository;

I will have attributes on the controller

[AutoActions(template = TemplateIndicator.AllPost,FieldsName =new[] { “repository” })]

[ApiController]

[Route(“[controller]/[action]”)]

public partial class WeatherForecastController : ControllerBase

I was thinking out about this modification. It is better , because now we can see also the route – if the routing is not well, the actions are not working ( if it is not a pure REST , then the route must have [action])

The code- oh, the code. It is a mostly complete refactoring of the code . The fact that I have organized into methods – processClass, processFields have make the pain less … but anyway – you will find the modifications here: https://github.com/ignatandrei/AOP_With_Roslyn/commit/eba37f0c7b1aadb56e40b52af57afedc9925eb5a .

And SCRIBAN performed well – no big problems. I have just made a template that makes the actions POST, named AllPost.

Deployed also on NuGet

AutoActions for Skinny controllers–user customization

The generation of controllers actions is now very rude:

  1. Http Method: if the method has no arguments, I assume GET . Else it is POST
  2. What is generated in the Action Body is hard-coded. What if the user wants something special ?
  3. The answer from the Action is hardcoded to the answer that the method returns. What if we want something different ?

So some customization should be involved. I need

  1. a template engine – I choose https://github.com/lunet-io/scriban , to make a change from Razor Pages
  2. a decision – choose a template for each action. This should / could be implemented by the programmer – as is the person who  knows best how to do generate from his actions. However, this should be implemented . 

So, first question : how the programmer specifies the decision ( and this decision could be different for each class / field instance) ? This is quite a problem. The programmer should make either a simple decision for their public functions ( like REST API ), either a complicated one – like for doing HttpGet[{id}] or Level 3 REST API ( read above). So , basic, the programmer should indicate a function that depends on

  1. Name of the public method
  2. Return Type
  3. Parameters of the function

and return different template. The template is taking as parameters the same things  – and return how the Action will look like.

And now I have seen the light . The function and the template are taking the same arguments. And what is great in programming are pointers. So , the light version of pointers in this case is an enum . I will use an enum , put into https://www.nuget.org/packages/SkinnyControllersCommon/ , in order to indicate the template ,

The programmer will improve SkinnyControllersCommon with a new enum and a new template, put a PR , and voila!  – new version of template for all programmers!

The implementation next time

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.