Giter Site home page Giter Site logo

lombok.net's Introduction

Lombok.NET

This library is to .NET what Lombok is to Java. It generates constructors and other fun stuff using Source Generators for those classes you specify special attributes for. Check out the examples for more info.

Installation

At least Visual Studio 17.3 (or any JetBrains Rider version) is required for projects using this library. The generators generate code compliant with C# 10. You can install Lombok.NET either via NuGet

Install-Package Lombok.NET

Or via the .NET Core command-line interface:

dotnet add package Lombok.NET

Building and Debugging

To debug a generator, simply set a breakpoint and debug a test. This project uses Verify for snapshot testing.

Features

Usage

Demo

This demonstrates the generating of the With pattern. Simply apply an attribute and the library will do the rest. Remember you are not bound to using fields, but can also use properties and supply the appropriate MemberType value to the attribute's constructor.

LombokNetDemo

Constructors

Supported types: Classes, Structs (AllArgsConstructor only)

[AllArgsConstructor]
public partial class Person {
    private string _name;
    private int _age;
}

By supplying the AllArgsConstructor attribute and making the type partial, you allow the Source Generator to create a constructor for it containing all of the classes private fields.
If you wish to modify this behavior and would instead like to have a constructor generated off of public properties, you can specify this in the attribute's constructor, e.g.:

[AllArgsConstructor(MemberType = MemberType.Property, AccessTypes = AccessTypes.Public)]
public partial class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

The default is Field for the MemberType and Private for the AccessType.
It is crucial to make the type partial, otherwise the Source Generator will not be able to generate a constructor and will throw an exception.

If you only wish to have a constructor generated containing the required fields or properties, Lombok.NET offers the RequiredArgsConstructor attribute. Fields are required if they are readonly, properties are required if they don't have a set accessor.
There is also a NoArgsConstructor attribute which generates an empty constructor.

With Methods

Supported types: Classes

For modifying objects after they were created, a common pattern using With... methods is used. Lombok.NET will generate these methods for you based on members in your class. Here's an example:

[AllArgsConstructor]
[With]
public partial class Person {
    private string _name;
    private int _age;
}

class Program {
    public static void Main() {
        var person = new Person("Steve", 22);
        person = person.WithName("Collin");
        
        Console.WriteLine(person.Name); // Prints "Collin"
    }
}

With methods will only be generated for properties with a setter and fields without the readonly modifier. If you would like Lombok.NET to also generate With methods for inherited members, use [With(IncludeInheritedMembers = true)].

Singletons

Supported types: Classes

Apply the Singleton attribute to a partial class and Lombok.NET will generate all the boilerplate code required for making your class a thread-safe, lazy singleton. It will create a property called Instance in order to access the singleton's instance. Note that the type needs to have a parameterless constructor.
Example:

[Singleton]
public partial class PersonRepository {
}

public class MyClass {
    public MyClass() {
        var personRepository = PersonRepository.Instance;
    }
}

Lazy

Supported types: Classes, Structs

Apply the Lazy attribute to a partial class or struct and Lombok.NET will generate a Lazy<T> property which can be used to create an instance of the object lazily. Note that the type needs to have a parameterless constructor. Example:

[Lazy]
public partial class HeavyInitialization {
    private HeavyInitialization() {
        Thread.Sleep(1000);
    }
}

public class Program {
    public Program() {
        var lazy = HeavyInitialization.Lazy;
        if(Random.Shared.Next() == 2) {
            var value = lazy.Value;
            // do something with value
        }
    }
}

ToString

Supported types: Classes, Structs, Enums

To generate a descriptive ToString method to your type, make it partial and add the [ToString] attribute to it. By default, it will include private fields in the ToString method, but this is customizable in the attribute's constructor.

[ToString]
public partial class Person {
    private string _name;
    private int _age;
}

When applying this attribute to an enum, Lombok.NET will create an extension class with a ToText method. This is due to the fact that enums can't be partial, thus an extension method is needed and the extension method will not be found if it is called ToString.

If you have sensitive data in your objects which should not be contained in the ToString method, you can apply the [Masked] attribute to the property or field containing sensitive data. This will cause the value to be replaced by four asterisks (****) in the ToString method.

Properties

Supported types: Classes, Structs

Generating properties from fields while using them as backing fields is possible using the [Property] attribute. Example:

public partial class MyViewModel {
    
    [Property]
    private int _result;
}

This will create the following property:

public int Result {
    get => _result;
    set => _result = value;
}

Property change pattern

Supported types: Classes

All of the boilerplate code surrounding ÌNotifyPropertyChanged/ÌNotifyPropertyChanging can be generated using a conjunction of the [NotifyPropertyChanged]/[NotifyPropertyChanging] and the [Property] attributes.
The [NotifyPropertyChanged] attribute will implement the INotifyPropertyChanged interface and the PropertyChanged event. It will also create a method called SetFieldAndRaisePropertyChanged which sets a backing field and raises the event. The event as well as the method can be used in your ViewModels to implement desired behavior.
If you would like to take it a step further, you can also use the [Property] attribute on backing fields while passing the PropertyChangeType parameter to generate properties off of backing fields which will include the raising of the specific event in their setters. Here's an example:

[NotifyPropertyChanged]
public partial class CustomViewModel {

    private int _result;
    
    public int Result {
        get => _result;
        set => SetFieldAndRaisePropertyChanged(out _result, value);
    }
    
    // -- OR --
    
    [Property(PropertyChangeType = PropertyChangeType.PropertyChanged)]
    private int _result;
}

public class Program {

    public static void Main() {
        var vm = new CustomViewModel();
        vm.PropertyChanged += (sender, args) => Console.WriteLine("A property was changed");
        
        vm.Result = 42;
    }
}

If you are using the ReactiveUI library (e.g. when using Avalonia), you can also specify the PropertyChangeType.ReactivePropertyChange to leverage ReactiveUI's property change handling.

To be able to generate the properties with the property change-raising behavior, the class must have the [NotifyPropertyChanged] or [NotifyPropertyChanging] (depending on desired behavior) attribute placed above it.

Serialization

Supported types: Classes, Structs

To be able to perform binary serialization and deserialization on a type, apply the [Serialization] attribute. This will generate the following methods:

  • void Serialize(string path)
  • Task SerializeAsync(string path, CancellationToken cancellationToken)
  • void Deserialize(string path)
  • Task DeserializeAsync(string path)

If deserialization functionality is not needed, use [Serialization(IncludeDeserialization = false)]. Similarly, to serialize properties instead of fields, use [Serialization(MemberType = MemberType.Property)].

Lombok.NET will serialize the object including its inherited members. Serialization is only supported for the following data types:

  • short (Int16)
  • int (Int32)
  • long (Int64)
  • ushort (UInt16)
  • uint (UInt32)
  • ulong (UInt64)
  • byte (Byte)
  • sbyte (SByte)
  • float (Single)
  • double (Double)
  • decimal (Decimal)
  • string (String)
  • char (Char)
  • bool (Boolean)

Async overloads

Supported types: Abstract Classes, Interfaces, Methods

If you want to have async overloads for every method in your interface, you can add the [AsyncOverloads] attribute to it. This also works for abstract classes:

[AsyncOverloads]
public partial interface IRepository<T> {
    T GetById(int id);
    
    void Save(T entity);
}

This will add the following methods to your interface:

Task<T> GetByIdAsync(int id, CancellationToken cancellationToken = default);
Task SaveAsync(T entity, CancellationToken cancellationToken = default);

For abstract classes, it will do the same for every abstract method. The inheriting class will be forced to implement the async versions as well. This may also be achieved by using the [Async] attribute.

Async methods

If you would like to create a simple async version of your method, you can add the [Async] attribute to it:

public partial class MyViewModel {

    [Async]
    public int Square(int i) {
        return i * i;
    }
}

This will add the following method:

public Task<int> SquareAsync(int i) => Task.FromResult(Square(i));

This works for classes and structs, however it must be partial.

Freezable pattern

Supported types: Classes and structs

The [Freezable] attribute can be used to generate the freezable pattern for types. For example:

[Freezable]
partial class Person
{
	[Freezable]
	private string _name;

	private int _age;
}

This would generate the methods Freeze(), Unfreeze(), TryFreeze(), and TryUnfreeze() and a property to check the freeze status, IsFrozen, as well as the property Name for the _name field. When trying to set the Name property, the setter will check if the type is currently frozen and throw an InvalidOperationException if this is the case.
The attribute must be set on both the fields which should be aware of the type's freeze status as well as the type itself. Readonly fields will be ignored.
If an instance should not be able to be unfrozen, it is possible to specify [Freezable(IsUnfreezable = false)] on the type.

Decorator Pattern

Supported types: Abstract Classes, Interfaces

Lombok.NET also provides an option to generate the boilerplate code when it comes to the decorator pattern. Simply apply the Decorator attribute to an abstract class or an interface and let the Source Generator do the rest.

[Decorator]
public interface IVehicle {
    void Drive();
    int GetNumberOfWheels();
} 

This will add the following class to your namespace:

public class VehicleDecorator {

    private readonly IVehicle _vehicle;
    
    public VehicleDecorator(IVehicle vehicle) {
        _vehicle = vehicle;
    }
    
    public virtual void Drive() {
        _vehicle.Drive();
    }
    
    public virtual int GetNumberOfWheels() {
        return _vehicle.GetNumberOfWheels();
    }
} 

Please let me know if there is any other functionality you would like to see in this library. I am happy to add more features.

lombok.net's People

Contributors

collinalpert avatar lukewire129 avatar simoncropp avatar view12138 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lombok.net's Issues

[NotifyPropertyChanging] Question & Issue

I'm looking at this package and have two questions about [NotifyPropertyChanging].

  1. As the class author, how do I implement validation of the properties? I don't see how that can be done. I have the same question about another source generator I found.

  2. When I do use [NotifyPropertyChanging], the build fails with errors like this:
    Missing XML comment for publicly visible type or member 'TestClass.SetFieldAndRaisePropertyChanging<T>(out T, T, string)'
    This happens for the properties too. If I document the field, that documentation is not carried over to the generated property.

Please advise. Thanks!

Unity Support

Doesn't work with Unity 2021.3.1f1 (and probably with any other version).
Will you consider supporting it?

Missing XML comment for publicly visible type or member

Describe the bug
When the documentation file generation feature was enabled (<GenerateDocumentationFile>True</GenerateDocumentationFile>) on the project, the generated code caused the compiler to report a warning Compiler Warning (level 4) CS1591

To Reproduce

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <GenerateDocumentationFile>True</GenerateDocumentationFile>
    </PropertyGroup>
</Project >

Screenshots
image
image

Environment info

  • .NET version: 8.0
  • Lombok.NET version: 2.3.0

Make SourceGeneratorAttributes generated by code generator

Hi, This is a nice project!
However, Could you please move SourceGeneratorAttributes into SourceGenerator?

This will make it purely an analyzer package.
The analyzer is not runtime-limited.
And they will work on .Net Framework 4.0 and .Net Framework 3.5.

Like this:

context.RegisterPostInitializationOutput(context => context.AddSource(
    "ToStringAttribute.g.cs",
    $$"""
    namespace Lombok.NET;

    /// <summary>
    /// Tells Lombok.NET to generate a ToString implementation for this type. For enums, a ToText method will be added.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum)]
    internal sealed class ToStringAttribute : Attribute
    {
        // members
    }
    """));
Work on old platform

image

Async and AsyncOverload

Does it make sense to generate an async method with "CancellationToken token = default"?

A synchronous one without it and the async one with abort option.

Multiple Constructor Attributes like standard lombok

I like the approach to specify in the AllArgsConstructor attribute what properties one wants to have included, but for simplicity it would be nice if the AllArgsConstructor would work like the Java Lombok and we had extra Attributes for RequiredArgsConstructor, for the private fields and NoArgsConstructor as well.

The generator dosen't work when the class with same name

This is a very common scenario when I have different versions of the API and class with the same name but different namespaces, and when Lombok.NET generates the same filename, the generate code will be overwritten or the build fails.

e.g.
Controllers/v1/CommonController.cs

namespace MyWebApi.v1;

[ApiController]
[Route("api/[controller]/[action]")]
[RequiredArgsConstructor]
[Obsolete]
public partial class CommonController : ControllerBase
{
        private readonly ICommonService commonService;
}

Controllers/v2/CommonController.cs

namespace MyWebApi.v2;

[ApiController]
[Route("api/[controller]/[action]")]
[RequiredArgsConstructor]
public partial class CommonController : ControllerBase
{
        private readonly ICommonService commonService;
}

My suggestions:

  1. the generated filename use the AssemblyQualifiedName for class
  2. add property like [RequiredArgsConstructor(FileName = "V1_CommonController.g.cs")] in all Lombok.NET attributes

Generated decorator doesn't pass parameters to methods

For example, i have an interface

public interface IMathOperation
{
    int Execute(int val);
}

and i want to decorate implementation of it, but i can't because generated code is wrong:

public class MathOperationDecorator : IMathOperation
{
    private readonly IMathOperation _mathOperation;
    public MathOperationDecorator(IMathOperation mathOperation)
    {
        _mathOperation = mathOperation;
    }

    public virtual int Evaluate(int val)
    {
        return _mathOperation.Evaluate();
    }
}
  • .NET version: .Net SDK 7.0.404
  • Lombok.NET version: 2.2.1

ToString, support for masking sensitive data

When dealing with various dto's and other classes that contains data, we are often faced with sensitive data like passwords. I would like to be able to put an annotation on those fields which then ensures that they are not included fully in any ToString methods, but instead masked in some way.

Describe the solution you'd like
A possible solution could be:

[ToString]
public partial class CreateProfileRequest {
    public string Name{get;set;}
    [Masked]
    public string Password{get;set;}
}

Which should then generate a ToString method that would output something like:

{Name="MyName", Password="*********"}

Describe alternatives you've considered
Currently for logging to serilog, I'm using destructurama:
https://github.com/destructurama/attributed
This has a method callec [LogMasked] which takes parameters like PreserveLength=true|false, ShowFirst=3, ShowLast=2 which can affect how the masking is added

Besides the mentioned annotations above, it would be good to also have ways to exclude specific properties from the ToString method

Lombok can't find Microsoft.CodeAnalysis.dll

I cloned the repository. When I Build dotnet gives me a warning that leads to the failure of lombok.net. This also applies to trying to use the NuGet package. I get the following error:


Severity	Code	Description	Project	File	Line	Suppression State
Warning	CS8032	An instance of analyzer Lombok.NET.DecoratorGenerator cannot be created from C:\Workspace\Lombok.net\Lombok.NET\Lombok.NET\bin\Debug\netstandard2.0\Lombok.NET.dll : 
Could not load file or assembly 'Microsoft.CodeAnalysis, Version=4.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. 
The system cannot find the file specified..	Lombok.NET.Test	C:\Workspace\Lombok.net\Lombok.NET\Lombok.NET.Test\CSC	1	Active

and I get this warning for every generator. This causes no source code to be generated there for giving errors for all the tests.

image

How are you getting the package to work?

Doesn't work

Hi,

I installed with NuGet Lombok.NET into my project.

I created the minimal code from the example:

using Lombok.NET;
using System;

namespace com.clinckart.TackITEasy.Lombok
{
    [AllArgsConstructor]
    [With]
    [ToString]
    public partial class Person
    {
        [Property]
        private string _name;
        [Property]
        private int _age;
    }
    class Program
    {
        public static void Main()
        {
            var person = new Person("Steve", 22);
            person = person.WithName("Collin");

            Console.WriteLine(person.Name); // Prints "Collin"
        }
    }
}

But VS says that the constructor is not existing and Person doesn't contains definition of WithName and Name.

Any idea what is wrong ?

Thanks

Lombok.Net with .net framework

I am developing a .net framework project and your library would help me cleanup a lot of boilerplate in my code. However I think that it only works with .net core projects.

Things I tried:

  • created a .net core console app and added lombok.net with nugget. Annotations [AllArgsConstructor] and [With] are working perfectly.
  • created a .net framework console app and imported lombok.net. The annotations are recognized but I cannot create objects using the generated constructor or object copies using [With]

Is the library compatible with .net framework or is it only compatible with .net core? I am using Rider 2022.1.1
Thanks in advance!

An instance of analyzer cannot be created

Thanks for building this, it looks like a must-have already. Unfortunately I am not able to use it. When adding the NuGet package to a .NET 6.0 console application, I get the following warnings:

Warning CS8032 An instance of analyzer Lombok.NET.AllArgsConstructorGenerator cannot be created from C:\Users\MyName\.nuget\packages\lombok.net\0.3.0\analyzers\dotnet\cs\Lombok.NET.dll: Could not load file or assembly 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified..

It repeats the same warning for the six analyzers.

The analyzer is not running and the code is not being generated. Nothing happens when I add the attributes.

Support for all release targets of .NET MAUI?

I'm currently exploring .NET MAUI, and as it is, this project works brilliantly, but only for the android portion of .NET MAUI. If I have time, I'll look through the code and see if I can send a pull request once I figure out how to fix it, but until then, I just felt it was best if you were aware. :)

In other words, this doesn't currently play well with other targets for a multi-target project, such as .NET MAUI. At least, not when creating such an app from the provided template for .NET MAUI.

Verbatim identifiers do not work with RequiredArgsConstructor

Code such as:

    [RequiredArgsConstructor]
    public partial class BeaconLight
    {
        private readonly BeaconLightSetEvent @event;

generates a constructor public BeaconLight(BeaconLightSetEvent new@event) which doesn't compile. The verbatim prefix @ needs to be at the start of the identifier, i.e. public BeaconLight(BeaconLightSetEvent @newevent).

Environment info

  • Lombok.NET version: 2.1.2

Very probably affects other functionality.

IntelliSense does not recognize generated constructors

Generated code with the NoArgsConstructor, AllArgsConstructor and RequiredArgsConstructor attributes does not get picked up by IntelliSense. The constructors can be used and the build passes without issues, however it would be nice if IntelliSense also recognized a presence of the generated constructors. This issue is observed in Visual Studio 2022 as well as Rider 2021.3.2.

Generator for enum values

I am working on a generator which is supposed to generate a static property or method called Values which would return an enum's members. This would alleviate the need of the reflection-based Enum.GetValues() approach and would also be statically typed.

However, I am running into design issues. Enums can't be partial which means the source generator couldn't simply plug in and add a static property. I also thought about extension method, but this would require a specific enum field and I want to add a static property on the enum type.

The best I can currently come up with is the following:

public enum Mood
{
  Happy,
  Sad,
  Mad
}

The generator would then produce the following code:

public static class MoodEnumeration
{
  public static Mood[] Values => new [] { Mood.Happy, Mood.Sad, Mood.Mad };
}

But from a users's standpoint, that design is less than ideal. Please leave a comment here if you are interested in this feature and if so, what design would work best for you.

NotifyPropertyChanged inheritance problems

When inheritance is involved using this attribute is not worth.

1. Sub-class hides higher class's PropertyChanged event.
Using the attribute on multiple class creates bugs because of hidden event

Edit: seems this wasn't true.

  1. Upper class's SetFieldAndRaisePropertyChanged is private
    Using the attribute on only upper class doesn't work because of private access

My proposal is making SetFieldAndRaisePropertyChanged method protected so that sub-classes can use it

Auto repair code instead of error

When I add a attrbute for a class without partial, Lombok can add keyword 'partial'.
If it can do that, I will don't need to concern about it, learn it.

Don't change field name in parameters list

Is your feature request related to a problem? Please describe.
Don't change field name in parameters list when the parameter name is the same as the field name. eg: name = newName;.

Describe the solution you'd like
when the parameter name is the same as field name, use this to assess field. eg: this.name = name;.

Describe alternatives you've considered

// source code
[AllArgsConstructor(MemberType = MemberType.{{memberType}})]
internal partial class TestClass
{
	private string name;
	private string _name;
	private string @string;
	private int _age;
}

// now <auto-generated/>
internal partial class TestClass
{
    internal TestClass(string newName, string name, string newString, int newAge)
    {
        name = newName;
        _name = name;
        @string = newString;
        _age = newAge;
    }
}

// new <auto-generated/>
internal partial class TestClass
{
    internal TestClass(string name1, string name2, string @string, int age)
    {
        name = name1;
        _name = name2;
        this.@string = @string;
        this.age = age;
    }
}

Feature Requests

Hi,
I am working with both Java and C#.
What I use in Lombok for Java is the following:

  • Generation of default and all-property Constructors (these you have in Lombok.Net)
  • Generation of ToString method with all properties (seems to be missing)
  • Generation of Properties from fields (did not see this either, but might not be so important in regular classes, but when thinking of WPF or Xamarin, raising an IPropertyChanged would be great)
  • Generation of Equals and GetHash methods.

Hope you find these ideas helpful.

In the meantime, I am down to writing the code myself :)
Thank you for your help.
Christophe

Generate Properties for Collections that Return a Copy

I haven't used this library yet, but I thought of something that could be very useful. There is a code violation thrown when properties return collections. This violation states that properties that return collections should return a copy/ clone of that collection.

It would be a great addition to this package to auto-generate properties that automatically return a copy/ clone of the collection from a private field.

Make the [With] attribute work for inherited members

Is your feature request related to a problem? Please describe.
I'd like to use this library to generate With methods for a class that inherits from a base class, however, I only get With methods generated for the members of the class I apply the attribute on.

This of course wouldn't be a problem if I owned the base class, but that is not the case as the base class comes from an external library.

Describe the solution you'd like
Optionally allow to generate With methods on inherited members.

I image it could be a property on the WithAttribute, something like:

[With(IncludeInheritedMembers = true)]
public class MyClass : ExternalBaseClass
{
    // ...
}

Describe alternatives you've considered
An alternative solution would be to apply the WithAttribute to the base class, but as mentioned before, that's not possible in my case.

Generator To Serialize/Deserialize Objects

It would be really nice to have a generator to serialize/deserialize objects to binary.

Example:

[Serializeable]
public partial class MyClass {}

that generates two methods, one for serialisation with a binarywriter and one for deserialisation with binaryreader

Builder

Is your feature request related to a problem? Please describe.
When creating objects which have multiple properties and constraints, like required values, the builder pattern is helpful so we don't need a constructor with a lot of parameters.

Describe the solution you'd like
The [Builder] attribute should generate a static method Builder() which returns an instance of a generate class SomeClassBuilder which has one method per property (eg, .Name("my name")) and a method build() that creates that runs all the checks and creates the final class calling its constructor. See the lombok documentation for details.

Describe alternatives you've considered
For now, an alternative is to generate the all args constructor.

Additional context
A simple implementation could be shipped without the need of all the caveats and features that the lombok implementation has.

@With need to return a copy of the object?

The @With in Lombok (Java) is returning a copy of the object if the provided property was changed

protected WithExample withName( String name) {
    return this.name == name ? this : new WithExample(name, age,....);
}

current .NET implementation is more like a Builder?
So ideally will like to have a new instance of the object with the new property set (and rest of the properties) This will help with immutable objects.

Maybe add [WithNew] if you consider original C# implementation as expected.
Also would be nice to have it working on Properties?

A lot of AsyncMethodMustBeInPartialClassOrStructAnalyzer Warnings

In my Project I am only using:

[NotifyPropertyChanged]

and

[Property]

Attributes. However, when compiling, I receive a lot of these warnings:

9>CSC : warning AD0001: Analyzer 'Lombok.NET.Analyzers.AsyncMethodMustBeInPartialClassOrStructAnalyzer' threw an exception of type 'System.TypeAccessException' with message 'Lombok.NET.AsyncAttribute could not be found in compilation.'.

Since I am not using any Async Attributes, I don't understand how this error appears? I can still build the project but the build output is filled with these..

Generator For freezable Pattern

Hi,

it would be really useful to have an attribute that marks an object as freezable, so there is a freeze method. if the object is frozen properties cant be changed anymore

Unable to use With..

This is my class, and when I do var modelSearch = new PostSearchRq();
there is no method With

Maybe I am doing smth wrong,
Thank you

using Lombok.NET;
using Newtonsoft.Json;


[AllArgsConstructor]
// [NoArgsConstructor]
[With]
public class PostSearchRq
{
  
    [JsonProperty("currency", Required = Required.Always)]
    public string Currency ;

    [JsonProperty("departure", Required = Required.Always)]
    public Departure Departure;

    [JsonProperty("arrival", Required = Required.Always)]
    public Arrival Arrival;

    [JsonProperty("occupancy", Required = Required.Always)]
    public Occupancy Occupancy ;


}

[AllArgsConstructor]
[NoArgsConstructor]
[With]
public class Arrival
{
    [JsonProperty("locationId", Required = Required.Always)]
    public string LocationId;

    [JsonProperty("returnDateTime", Required = Required.Always)]
    public DateTimeOffset ReturnDateTime;
}

[AllArgsConstructor]
[NoArgsConstructor]
[With]
public class Departure
{
    [JsonProperty("locationId", Required = Required.Always)]
    public string LocationId;

    [JsonProperty("dateTime", Required = Required.Always)]
    public DateTimeOffset DateTime ;
}

[AllArgsConstructor]
[NoArgsConstructor]
[With]
public class Occupancy
{
    [JsonProperty("adultsNo", Required = Required.Always)]
    public long AdultsNo ;

    [JsonProperty("childrenNo", Required = Required.Always)]
    public long ChildrenNo;

    [JsonProperty("childrenAges", Required = Required.Always)]
    public long[] ChildrenAges;
}

Generator doesn't work

When I use any QualifiedNameSyntax , the generator doesn't work,
e.g. [Lombok.NET.NoArgsConstructor] or [NET.NoArgsConstructor]

Cannot build when using constructor, can't create analyzer instance

Describe the bug
I've just found out about this project and was exited to use it, coming from Java, this is something I would really appreciate having in C# as well.

To my issue now, it seems I can't build my project, if I'm using the generated constructors (I'm using the [RequiredArgsConstructor] one),
weirdly enough, Intellisense itself doesn't give any error, and even navigates me to the generated constructor in /tmp/JetBrains.., only the build itself fails.

To Reproduce
Steps to reproduce the behavior:

  1. Create a new class with readonly field
  2. Add the [RequiredArgsConstructor] attribute
  3. Use the generated constructor
  4. Try to build

Expected behavior
I expect the project to build successfully.

Screenshots
This is the code:

[RequiredArgsConstructor]
public partial class AddPlayerToGameCallback : IBaseObjectCallback<IPlayer>
{
    private readonly GameManager _gameManager;
    
    public void OnBaseObject(IPlayer baseObject)
    {
        _gameManager.AddPlayer(baseObject);
    }
}
        // Add all players
        var callback = new AddPlayerToGameCallback(serviceProvider.GetService<GameManager>());
        Alt.ForEachPlayers(callback);

This is the .csproj, if its of any significance:

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

    <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
    </PropertyGroup>

    <ItemGroup>
      <PackageReference Include="AltV.Net.Async" Version="16.1.1" />
      <PackageReference Include="DiamondCrew.AltV.Core.Server" Version="1.2.0" />
      <PackageReference Include="Lombok.NET" Version="2.4.0" />
      <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
    </ItemGroup>

    <ItemGroup>
        <ProjectReference Include="..\DiamondCrew.AltV.TTT.Shared\DiamondCrew.AltV.TTT.Shared.csproj" />
    </ItemGroup>

    <ItemGroup>
      <Folder Include="Model\" />
    </ItemGroup>

</Project>

Environment info

  • .NET version: 6.0
  • Lombok.NET version: 2.4.0

Additional context
I'm also getting these errors in the build log:

2>CSC: Warning CS8032 : An instance of analyzer Lombok.NET.ConstructorGenerators.AllArgsConstructorGenerator cannot be created from /home/raj/.nuget/packages/lombok.net/2.4.0/analyzers/dotnet/cs/Lombok.NET.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=4.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified..
2>CSC: Warning CS8032 : An instance of analyzer Lombok.NET.ConstructorGenerators.NoArgsConstructorGenerator cannot be created from /home/raj/.nuget/packages/lombok.net/2.4.0/analyzers/dotnet/cs/Lombok.NET.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=4.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified..
..
..
2>TTTServer.cs(33,32): Error CS1729 : 'AddPlayerToGameCallback' does not contain a constructor that takes 1 arguments

Seems to be issue with all analyzers.
I'm using the latest JetBrains Rider.

Constructor access modifiers cannot be customized when using constructor generators

I have a internal class, bug I can't generte the public constructor.

// my code
[RequiredArgsConstructor]
internal partial class MyClass
{
    private readonly int myPropety;
}
// the generated code
internal partial class MyClass
{
    internal MyClass(int newMyPropety)
    {
        myPropety = newMyPropety;
    }
}

This is my solution

// my code
[RequiredArgsConstructor(ModifierType = ModifierType.Public)]
internal partial class MyClass
{
    private readonly int myPropety;
}
// the generated code
internal partial class MyClass
{
    public MyClass(int newMyPropety)
    {
        myPropety = newMyPropety;
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.