pvWay.MethodResultWrapper.nc6 2.0.0

dotnet add package pvWay.MethodResultWrapper.nc6 --version 2.0.0
NuGet\Install-Package pvWay.MethodResultWrapper.nc6 -Version 2.0.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="pvWay.MethodResultWrapper.nc6" Version="2.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add pvWay.MethodResultWrapper.nc6 --version 2.0.0
#r "nuget: pvWay.MethodResultWrapper.nc6, 2.0.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install pvWay.MethodResultWrapper.nc6 as a Cake Addin
#addin nuget:?package=pvWay.MethodResultWrapper.nc6&version=2.0.0

// Install pvWay.MethodResultWrapper.nc6 as a Cake Tool
#tool nuget:?package=pvWay.MethodResultWrapper.nc6&version=2.0.0

Method Result Wrapper Core DotNet 6 by pvWay

Provides a generic wrapper that returns whether or not a method succeeded or failed carrying the method result on success or a list of notifications in case of failure.

Interfaces

Interfaces are defined in the LoggerService.Abstractions nuGet

MethodResult interfaces

public interface IMethodResult
{
    /// <summary>
    /// At least one notification has a severity
    /// greater or equal to Error
    /// </summary>
    bool Failure { get; }

    /// <summary>
    /// No notification or all notifications severity
    /// are lower than Error
    /// </summary>
    bool Success { get; }

    SeverityEnum Severity { get; }

    /// <summary>
    /// Bulk string made of the concatenation
    /// of the notifications separated by new
    /// lines
    /// </summary>
    string ErrorMessage { get; }

    IEnumerable<IMethodResultNotification> Notifications { get; }

    void AddNotification(string message, SeverityEnum severity);
    void AddNotification(IMethodResultNotification notification);

    /// <summary>
    /// Will throw new Exception(ErrorMessage)
    /// </summary>
    void Throw();
}

public interface IMethodResult<out T> : IMethodResult
{
    T? Data { get; }
}

public interface IMethodResultNotification
{
    SeverityEnum Severity { get; }
    string Message { get; }
}

ILoggerService interface

The LoggerService.Abstractions nuGet also provides the ILoggerService interface.

This interface provides both sync and async methods with serveral signatures including (1) simple message, (2) list of messages, (3) MethodResult object (see above) (4) Exception

  • Each log row is also qualified by a Severity level from Debug to Fatal and enables also some interesting meta data like (1) UserId, (2) CompanyId, (3) Topic (4) MachineName

  • The service will also capture MemberName, FilePath and LineNumber

Features

MethodResult plain class (see MethodResult <T> generic class below)

  • MethodResult (implementing IMethodResult) is a class that
  • returns whether or not a method succeeded, has fatals, errors or warnings
  • the returned object provides
    • a boolean property named Failure that will be set when at least on notification has a severity of error or fatal
    • a boolean property named Success that is simply equals to !Failure
    • a list of notifications (message and severity)
    • an ErrorMessage string (list of notifications separated by new lines)
    • a method that allows to throw an exception
  • Constructors

public class MethodResult : IMethodResult
{
    private readonly ICollection<IMethodResultNotification> _notifications;

    private class Notification : IMethodResultNotification
    {
        public SeverityEnum Severity { get; }
        public string Message { get; }

        public Notification(SeverityEnum severity, string message)
        {
            Severity = severity;
            Message = message;
        }

        public override string ToString()
        {
            return $"{Severity}:{Message}";
        }
    }

    /// <summary>
    /// Successful constructor
    /// </summary>
    public MethodResult()
    {
        _notifications = new List<IMethodResultNotification>();
    }

    /// <summary>
    /// Wraps the result of a previous MethodResult
    /// by copying all its notifications (message and severity).
    /// Not really useful for the non generic MethodResult class
    /// but makes sense when using the generic version of the class
    /// </summary>
    /// <param name="res"></param>
    public MethodResult(IMethodResult res)
        : this()
    {
        foreach (var notification in res.Notifications)
        {
            AddNotification(notification);
        }
    }

    /// <summary>
    /// Instantiates a MethodResult object with one
    /// notification (message and severity)
    /// </summary>
    /// <param name="message"></param>
    /// <param name="severity"></param>
    public MethodResult(string message, SeverityEnum severity) :
        this()
    {
        AddNotification(message, severity);
    }

    /// <summary>
    /// Failure constructor that instantiates a MethodResult
    /// object with one notification. The notification message
    /// is built by recursively walking down the exception
    /// and its inner exceptions (using the extension method
    /// e.GetDeepMessage()). The stack trace is also added at
    /// the end of the message. By default the Severity is
    /// considered as Fatal but you select the one of your choice
    /// </summary>
    /// <param name="e"></param>
    /// <param name="severity"></param>
    public MethodResult(Exception e, SeverityEnum severity = SeverityEnum.Fatal)
        : this(e.GetDeepMessage(), severity)
    {
    }

    /// <summary>
    /// Same as the single message constructor but this time
    /// passing a list of messages. This creates one notification
    /// for each message in the list. All notifications get the
    /// same severity
    /// </summary>
    /// <param name="messages"></param>
    /// <param name="severity"></param>
    public MethodResult(IEnumerable<string> messages, SeverityEnum severity) :
        this()
    {
        foreach (var message in messages)
        {
            AddNotification(message, severity);
        }
    }

    public void AddNotification(string message, SeverityEnum severity)
    {
        AddNotification(new Notification(severity, message));
    }

    public void AddNotification(IMethodResultNotification notification)
    {
        _notifications.Add(notification);
    }

    /// <summary>
    /// At least one notification has a severity
    /// greater or equal to Error
    /// </summary>
    public bool Failure => _notifications
        .Any(n => n.Severity >= SeverityEnum.Error);

    /// <summary>
    /// No notification or all notifications severity
    /// are lower than Error
    /// </summary>
    public bool Success => !Failure;

    /// <summary>
    /// returns the highest severity from the list of notifications
    /// </summary>
    public SeverityEnum Severity =>
        _notifications.Any()
            ? _notifications.Max(x => x.Severity)
            : SeverityEnum.Ok;

    public IEnumerable<IMethodResultNotification> Notifications =>
        _notifications;

    public void Throw()
    {
        throw new Exception(ErrorMessage);
    }

    public string ErrorMessage => ToString();

    public override string ToString()
    {
        var str = string.Empty;
        foreach (var notification in _notifications)
        {
            if (!string.IsNullOrEmpty(str))
                str += Environment.NewLine;
            str += notification.ToString();
        }
        return str;
    }

    public static MethodResult Ok => new();
        
}

MethodResult <T> generic class inheriting of MethodResult

  • MethodResult<T> (implementing IMethodResult<T>) is a generic class that inherits from MethodResult plain class (see above)
  • returns whether or not a method succeeded, has fatals, errors or warnings
  • the returned object provides
    • a Data object property (of type T) that is set when the method has succeeded
    • a boolean property named Failure that will be set when at least on notification has a severity of error or fatal
    • a boolean property named Success that is simply equals to !Failure
    • a list of notifications (message and severity)
    • an ErrorMessage string (list of notifications separated by new lines)
    • a method that allows to throw an exception
  • Constructors

namespace MethodResultWrapper.Nc6;

public class MethodResult<T> : MethodResult, IMethodResult<T>
{
    public T? Data { get; }

    /// <summary>
    /// Successful constructor that carries
    /// the result of the called method in the
    /// property Data of type T
    /// </summary>
    /// <param name="data"></param>
    public MethodResult(T? data)
    {
        Data = data;
    }

    public static IMethodResult<T> Null => new MethodResult<T>(default(T));

    /// <summary>
    /// Wraps the result of a previous MethodResult
    /// by copying all its notifications (message and severity).
    /// Not really useful for the non generic MethodResult class
    /// but makes sense when using the generic version of the class
    /// </summary>
    /// <param name="methodResult"></param>
    public MethodResult(IMethodResult methodResult) :
        base(methodResult)
    {
    }

    /// <summary>
    /// Instantiates a MethodResult object with one
    /// notification (message and severity)
    /// </summary>
    /// <param name="message"></param>
    /// <param name="severity"></param>
    public MethodResult(string message, SeverityEnum severity)
        : base(message, severity)
    {
    }

    /// <summary>
    /// Same as the single message constructor but this time
    /// passing a list of messages. This creates one notification
    /// for each message in the list. All notifications get the
    /// same severity
    /// </summary>
    /// <param name="messages"></param>
    /// <param name="severity"></param>
    public MethodResult(IEnumerable<string> messages, SeverityEnum severity)
        : base(messages, severity)
    {
    }

    /// <summary>
    /// Failure constructor that instantiates a MethodResult
    /// object with one notification. The notification message
    /// is built by recursively walking down the exception
    /// and its inner exceptions (using the extension method
    /// e.GetDeepMessage()). The stack trace is also added at
    /// the end of the message. By default the Severity is
    /// considered as Fatal but you select the one of your choice
    /// </summary>
    /// <param name="e"></param>
    /// <param name="severity"></param>
    public MethodResult(Exception e, SeverityEnum severity = SeverityEnum.Fatal)
        : base(e, severity)
    {
    }

}

Usage

using PvWay.LoggerService.Abstractions.nc6;
using PvWay.LoggerService.nc6;
using pvWay.MethodResultWrapper.nc6;

namespace MethodResultWrapperDemo.Nc6;

internal static class Program
{
    private static async Task Main( /*string[] args*/)
    {
        var ls  = PvWayLoggerService.CreateConsoleLoggerService();
        var userStore = new UserStore();

        var getFirstName = await GetUserFirstNameAsync(
            ls, userStore, "pierre@pvWay.com");
        if (getFirstName.Failure)
        {
            Console.WriteLine("oops... something went wrong");
            Console.WriteLine(getFirstName.ErrorMessage);
        }
        else
        {
            var firstName = getFirstName.Data;
            Console.WriteLine("everything went fine");
            Console.WriteLine($"user first name is {firstName}");
        }
    }

    private static async Task<IMethodResult<string>> GetUserFirstNameAsync(
        ILoggerService ls, IUserStore userStore,
        string userName)
    {
        // let's call the GetUser Method and see its result
        // the method returns a IMethodResult<IUser?> object
        var getUser = await GetUserAsync(ls, userStore, userName);
        if (getUser.Failure)
        {
            // something bad happened
            // let's log this and return a
            // MethodResult object that will carry
            // the notifications collected by the getUser method
            await ls.LogAsync(getUser);
            return new MethodResult<string>(getUser);
        }

        // the user was found
        // let's get the user object from the getUser.Data
        var user = getUser.Data; // this returns an IUser

        var firstName = user!.FirstName;

        // let's call the MethodResult success constructor
        // by passing the expected data type object (here 
        // a string)
        return new MethodResult<string>(firstName);
    }

    private static async Task<IMethodResult<IUser>> GetUserAsync(
        ILoggerService ls, IUserStore userStore,
        string userName)
    {
        try
        {
            var user = await userStore.GetUserAsync(userName);
            if (user != null)
            {
                // the user was found
                // let's call the MethodResult success constructor
                // by passing the expected data type object (here 
                // a IUser object)
                return new MethodResult<IUser>(user);
            }

            // the user was not found...
            // this is a Business (non technical error)
            // let's construct a failure MethodResult object
            // with the Error (business error) severity
            var err = new MethodResult<IUser>(
                $"User {userName} not found", SeverityEnum.Error);

            // let's log this (business) error
            await ls.LogAsync(err);

            // let's return the MethodResult to the caller
            return err;
        }
        catch (Exception e)
        {
            // something raised an exception...
            // for example the data base might not be up
            // let's log this fatal error
            await ls.LogAsync(e);
            // let's construct and return a failure MethodResult
            // with the Fatal (technical error) severity
            // and the exception.
            return new MethodResult<IUser>(e);
        }
    }
}



internal interface IUser
{
    string FirstName { get; }
}

internal interface IUserStore
{
    Task<IUser?> GetUserAsync(string userName);
}

internal class UserStore : IUserStore
{
    public Task<IUser?> GetUserAsync(string userName)
    {
        Console.WriteLine($"searching for user with username {userName}");
        throw new Exception();
        // return null;
    }
}
}```

Happy coding !
Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.0.0 183 8/25/2023
1.0.2 2,107 2/4/2022
1.0.1 242 2/4/2022
1.0.0 229 2/4/2022

Now based on pvWay.LoggerService nuGet