Giter Site home page Giter Site logo

flunt's Introduction

Flunt

Flunt is a fluent way to use Notification Pattern with your entities, concentrating every change you made and easy accessing it when you need.

Package Version Downloads
Flunt NuGet Nuget

Dependencies

.NET Standard 2.0

You can check supported frameworks here:

https://docs.microsoft.com/pt-br/dotnet/standard/net-standard

Instalation

This package is available through Nuget Packages: https://www.nuget.org/packages/Flunt

Nuget

Install-Package Flunt

.NET CLI

dotnet add package Flunt

How to use

public class Customer : Notifiable<Notification>
{
  ...
}

var customer = new Customer();
customer.AddNotification("Name", "Invalid name");

if(customer.IsValid)
  ...

Just check our Wiki for more details and samples of how to use Flunt in your applications.

Extensions

Mods

About the Art

All logo, icons, colors and fonts were provided with love by Gregory Buso

flunt's People

Contributors

andrebaltieri avatar betorolim1 avatar diegoromario avatar douglasangeli avatar douglasoliveirabh avatar gabrielgdomingos avatar gunn3r71 avatar hugodantas avatar igorrozani avatar jhonattan111 avatar manacespereira avatar mstryoda avatar silvacaio avatar tiago-ilha avatar tiagopariz 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  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

flunt's Issues

Pacote NuGet desatualizado

A versão atual do NuGet, apesar de ser a mesma do projeto - 1.0.2, está com um problema nos métodos HasMinLen e HasMaxLen. Ambos estão sem a verificação string.IsNullOrEmpty no pacote NuGet.

Flunt fields being tracked by swashbuckle

Valid and Invalid fields are being tracked by Swashbuckle automatic documentation and marked as required

required

my model

public class FinishCreditCardOrderCommand: Notifiable
    {
        public Guid UserId { get; set; }
        public IList<CartItem> ListOfItems { get; set; } = new List<CartItem>();
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Document { get; set; }
        public string Email { get; set; }

        public string CardHolderName { get; set; }
        public string CardNumber { get; set; }
        public string LastTransactionNumber { get; set; }

        public string PaymentNumber { get; set; }
        public DateTime PaidDate { get; set; }
        public DateTime ExpireDate { get; set; }
        public decimal Total { get; set; }
        public decimal TotalPaid { get; set; }
        public string Payer { get; set; }
        public string PayerDocument { get; set; }
        public string PayerEmail { get; set; }


        public void Validate() { }
   }

Minimizing impact of Contract class changes

The problem

Current changes in the Contract class have caused crashes in Flunt extendable packages such as Flunt.Br.

The solution

In view of the continuity of the operation of these packages, I make the following suggestion:

  
    //Add this basic class
    public partial class Contract : Contract<bool> { };


    public partial class Contract<T> : Notifiable<Notification>
    {
        public Contract<T> Requires()
        {
            return this;
        }

        public Contract<T> Join(params Notifiable<Notification>[] items)
        {
            if (items == null) return this;
            foreach (var notifiable in items)
            {
                if (notifiable.IsValid == false)
                    AddNotifications(notifiable.Notifications);
            }

            return this;
        }
    }

justification

Since T is not a state of Contract, there would be no major implications of maintaining a base class.

Mapear Entidade implementa Notifiable

Boa noite.

Sou um pouco inexperiente.

Ao tentar mapear, no DbContext (EF Core), uma classe que Herda/Implementa Notifiable, recebo a seguinte notificação:

The entity type 'Notification' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'.

Nas configurações do DbSet então adiciono:

modelBuilder.Entity<Notifiable>().HasNoKey();

E então recebo outra notificação:

The entity type 'Cliente' cannot be mapped to a table because it is derived from 'Notifiable'. Only base entity types can be mapped to a table.

Como você faz para resolver essa questão ao usar o EF Core?

HasMaxLen conflict with ""

What I want: User can add OR not a value, but if ADD, cannot be higher than some length... so for example:

.HasMaxLen(ZipCode, 10, "ZipCode", "ZipCode can't be longer than 10.")

The issue: If user don't add Anything and Field is Empty (ZipCode = "") - Flunt generates a Notification anyway. I'm sending always " " (with a space in middle) to avoid the exception...

Make Contract be generic, instead of by injection.

Then:

public class CustomerContract : Contract<Customer>
{
    public CustomerContract()
    {
        Contract
            .Requires()
            .HasMinLen(customer => customer.FirstName, 3, "FirstName", "First Name should have at least 3 chars")
            .HasMaxLen(customer => customer.FirstName, 3, "FirstName", "First Name should not have more than 3 chars")
            .HasMinLen(customer => customer.LastName, 3, "LastName", "Last Name should have at least 3 chars")
            .HasMaxLen(customer => customer.LastName, 3, "LastName", "Last Name should not have more than 3 chars");
    }
}

Change property names

Some names on Notifiable.cs are no intuitive, we`re gonna change to:

// From
bool Invalid 
bool Valid
// To
bool IsNotValid 
bool IsValid

Add extension to HttpClient

Add support to get content of requests with 400 status from HttpClient and convert it to a notification list

Erro ao adicionar notifcações com automapper

Estou tendo o seguinte cenário:

Utilizo o automapper para fazer o parse de um dto para o dominio utilizando o :

CreateMap<CreateCouponCommand, Coupon>() .ConstructUsing(source => new Coupon(source.Description, source.OffPercentual, source.ValidAt));

Dentro do construtor do meu domínio eu utilizo o AddNotifications, dessa forma :

`

     public Coupon(string description, int offPercentual, long validAt)
      {
          Id = Guid.NewGuid();
          CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
          IsInvalidated = false;
          Description = description;
          OffPercentual = offPercentual;
          ValidAt = validAt;

       AddNotifications(
            new Contract()
            .IsNotEmpty(Id, "Id")
            .IsLowerOrEqualsThan(Description, 250, "Description")
            .IsNotNull(ValidAt, "ValidAt")
            .IsNotNull(Establishment, "Establishment")
            .IsNotNull(CreatedAt, "CreatedAt")
        );
    }`

Porém ao verificar se existe alguma notificação (Mesmo forçando o erro) no próximo step do código esta notificação esta se perdendo, ou seja debugando percebo que ele insere a notificação quando esta construindo meu domínio, mas após o mapeamento com automapper essas notificações deixam de existir.

Testei fazendo um mapeamento 'na mão' e ele funciona de forma correta, mas ao utilizar o automapper me ocorre este problema.

Added support for type on Notification

Add a new method to add notifications by passing its type and message.

public void AddNotification(Type property, string message)
{
    _notifications.Add(new Notification(property?.Name, message));
}

How to use

AddNotification(typeof(Name), "Message");

Validar CNPJ e CPF

Notei que é usado métodos como IsEmail ou IsURL, acham válido aplicar a validação do IsCpF ou IsCNPJ ?

Add extension for ASP.NET

Add support to convert notifications to ModelState and provide native support for ASP.NET applications

Licença

Olá vocês poderiam adicionar uma Licença a este código?

IsNullOrEmpty Validation Contract

This validation is adding notification if its false and not adding else.
Example :
`

    public class Name : ValueObject
    {
    
    public string FirstName { get; private set; }

    public string LastName { get; private set; }

    public Name(string firstName, string lastName)
    {   
        AddNotifications(new Contract().Requires().IsNullOrEmpty(firstName, "Nome", "Nome Inválido"));
        
        FirstName = firstName;
        LastName = lastName;
    }
}`

Name name = new Name("", "Poe");

Console Output :

----- Test Execution Summary -----

PaymentContext.Tests.StudentTests.TestMethod1:
Outcome: Passed

Total tests: 1. Passed: 1. Failed: 0. Skipped: 0

if you changue the Method name to IsNotNullOrEmpty and do the inverse with IsNotNullOrEmpty fix everything.

Interface IValidatabe was removed?

For use Fail Fast Validation pattern, the 1.0.5 version available the interface IValidatable.

  public interface ICommand : IValidatable
  { }

On the 2.x.x version this interface is been removed?

Documentação

Achei a documentação vaga...
Ja implementei as classes de Notification e notifiable e passei para que meu Value object herdar de notfiable mas mesmo quando tento usar o AddNotification ele nao reconhece o método, teria como acionar mais informações nas documentações e exemplos?

Dúvida

Se eu executar o código abaixo:

public class Customer : CustomNotifiable
{
...
}

public class Seller: CustomNotifiable
{
...
}

var seller= new Seller();
var customer = new Customer();

AddNotification(new CustomNotification("Chave", "Valor"));

Como a biblioteca identifica de qual objeto está adicionando essa notificação?

Abs

Notifications estão nulas após recuperar uma entidade Notifiable do MongoDB com Mongo Drive

Boa noite,

Me encontrei na situação de que aparentemente o MongoDrive não passa pelo construtor da classe ao recupera-la do banco de dados, e com isso, não é criada a propriedade Notifications de Notifiable.

Com isso, algumas regras de negócio que devem ser validadas posterior à criação do objeto, ao ser recuperado do banco, geram erro.

Acredito que o ideal seria retirar o readonly da propriedade privada _notifications para podermos inicializa-la caso esteja nula.

ps.: No meu sistema, as classes de domínio são as que eu também persisto no banco, e por ser dominio rico, algumas regras de negócio estão falhando por este motivo.

att,
Bruno Gouvêa Roldão

Notification Types

Balta,

Very usefull class.

Wouldn't be nice to have 3 types of notifications (Success, Alert, Error) so we could use the list of notifications to alert to end-users?

  • Notification Type could be Optional.
  • By default, ERROR type is set if not provided.
  • Review Invalid() Method to filter Error Type olny.

Change package structure

For a better organization we need to split Flunt into two packages, Flunt.Notification and Flunt.Validation, as well as separe it on distinct projects/tests.

Removed sealed from Notification class

Current Flunt version do not permit to extend Notification class because it is sealed.
The reason for that is to provide a unified way to show your notifications, but I understand most of you want to add new features to this class.

Well, on version 2 it`ll be removed!

BoolValidationContract

Shoudn't be the crontrary?

On BoolValidationContract IsFalse adds notification if it is true and IsTrue adds notification if is false. Isn't supposed to be the contrary?

Como usar contract com tipo long?

Bom dia!

Estou tentando aplicar o Flunt em meus projetos, porém eu tenho vários dados com tipo long, como usar o flunt com long?

Why Notification class is sealed?

Is there a reasonable design requirement for the Notification.cs class to be sealed?

I ask this because I am using Flunt in a project that I need to have my own implementation.

Is there a problem with that?

Implement CI/CD

  • Push to dev
  • Merge with main
  • Start GitHub Actions
  • Execute unit tests
  • Generate package
  • Public to NuGet.org

Regex pattern de URL não reconhece URLs locais

Tenho um cenário onde estou armazenando URLs que apontam para o meu storage no meu banco.
Porém, quando trabalhando localmente, as URLs não são aceitas pelo regex do método IsUrl, conforme pode ser verificado em:

https://regex101.com/r/ugUqs5/1

Caso o comportamento seja intencional, qual poderia ser a melhor maneira para lidar com esse "efeito colateral"?
-> Talvez algo como checar o environment ou modo de depuração e aplicar uma validação ou outra?

Code review

  • Notifiable + (Tests)
  • Notification + (Tests)
  • BoolValidationContract + (Tests)
  • Contract + (Tests)
  • DateTimeValidationContract + (Tests)
  • DecimalValidationContract + (Tests)
  • DoubleValidationContract + (Tests)
  • FloatValidationContract + (Tests)
  • GuidValidationContract + (Tests)
  • IntValidationContract + (Tests)
  • ListValidationContract + (Tests)
  • LongValidationContract + (Tests)
  • ObjectValidationContract + (Tests)
  • StringValidationContract + (Tests)
  • TImeSpanValidationContract + (Tests)

AreEquals and AreNotEquals seems to do opposite validation

Following the course from balta.io and using a code line as follows:

.AreEquals(0, subscription.Payments.Count, "Student.Subscription.Payments", "Esta assinatura não possui pagamentos."));

subscription.Payments.Count is 1 in this context.

So it should add a notification, does not? (I understand they are different, so add a notification). It's not adding one.
It only worked when I changed the condition to .AreNotEquals.

Flunt x Nhibernate

Boa tarde André!
Estou usando o Flunt e me deparei com uma questão.

Ao utilizar o Nhibernate, ele exige que os métódos Invalid, Valid e Notifications sejam virtual. Existe alguma maneira de eu contornar essa situação?

Obrigado

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.