WithUnity.Tools 2.0.3

dotnet add package WithUnity.Tools --version 2.0.3                
NuGet\Install-Package WithUnity.Tools -Version 2.0.3                
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="WithUnity.Tools" Version="2.0.3" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add WithUnity.Tools --version 2.0.3                
#r "nuget: WithUnity.Tools, 2.0.3"                
#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 WithUnity.Tools as a Cake Addin
#addin nuget:?package=WithUnity.Tools&version=2.0.3

// Install WithUnity.Tools as a Cake Tool
#tool nuget:?package=WithUnity.Tools&version=2.0.3                

#WithUnity.Tools provides:

  1. The Result class allows fluent validation.
  2. The Result class has optional logging, using the Log class. When logging, the ReflectiveTools class allows logging of the call stack. You can use the Log class and the ReflectiveTools class independently.
  3. When using Fody.NullGuard, the MayBe struct allows parameters to expect null.
  4. The ValueProperty class contains read-only properties, allowing you to add transparent validation for the property. You can choose to throw InvalidCastException if the data is invalid or use Result<ValueProperty<T>> Create(T rawData); if you prefer fluent validation. Implicit casts to and from the ValueProperty can make its use completely transparent.
  5. The tools include a few examples of ValueProperty, FileExtension EmailAddress, Unicode16 string. These examples are transparent to the user using implicit casts and throw the InvalidCast exception.

Example usage of Result, Maybe and a ValueProperty implementation.

/* Copyright 2015-2020 Robin Murison

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
using NullGuard;
using System;

namespace WithUnity.Tools.ValueProperties
{
    /// <summary>
    /// A Value Property for validating email addresses.
    /// </summary>
    /// <remarks>
    ///     This is provided with minimal validataion for an EmailAddress. You may want to create your own variant with different validation.
    /// </remarks>
    public sealed class EmailAddress : ValueProperty<EmailAddress, string>
    {
        /// <summary>
        /// Trims any white space and validates an email address
        /// </summary>
        /// <param name="emailAddressValue"></param>
        /// <remarks>
        /// This verifies:  
        ///     that the email is not <see langword="null"/>;
        ///     that email is at leaset 3 characters long;
        ///     that the email does not start with an @ sign;
        ///     that the email does not end with an @ sign;
        ///     that the email contains 1 and only 1 @ sign;
        /// </remarks>
        public static Result<string> ValidateEmailAddress(MayBe<string> emailAddressValue)
        {
            return (emailAddressValue.HasValue ? Result.Ok<string>(emailAddressValue.Value) : Result.Fail<string>("Null email Address"))
                .Ensure(ema => ema.Length == ema.Trim().Length, "Email Address needs trimming")
                .Ensure(ema => 3 <= ema.Length, "The email address is too short")
                .Ensure(ema => 0 < ema.IndexOf("@", StringComparison.InvariantCulture), "No preceding name before @ sign in EmailAddress")
                .Ensure(ema => ema.IndexOf("@", StringComparison.InvariantCulture) != (ema.Length - 1), "No domain name after @ sign in EmailAddress")
                .Ensure(ema => ema.Split('@').Length == 2, @"There are {ema.Split('@').Length - 1} @ signs. Should be 1.");
        }

        /// <summary>
        /// The main constructor for validating email addresses. This is used by implicit casts, when expecting a valid EmailAddress and throwing an exception on failure is a reasonable thing to do.
        /// </summary>
        /// <param name="emailAddressValue"></param>
        /// <param name="validateAndThrowOnFailure">Validates the email address and throws InvalidCastException when true. Does nothing when false</param>
        /// <exception cref="InvalidCastException">This is thrown if the string passed in is not a valid email with the appropriate error.</exception>
        /// <remarks>
        /// This verifies:  
        ///     that the email is not <see langword="null"/>;
        ///     that email is at leaset 3 characters long;
        ///     that the email does not start with an @ sign;
        ///     that the email does not end with an @ sign;
        ///     that the email contains 1 and only 1 @ sign;
        /// </remarks>
        private EmailAddress(MayBe<string> emailAddressValue, bool validateAndThrowOnFailure = true) : base(emailAddressValue)
        {
            if (validateAndThrowOnFailure)
            {
                ValidateEmailAddress(emailAddressValue).OnFailure(error => { throw new InvalidCastException(error); });
            }
        }

        /// <summary>
        /// Use CreateEmailAddress for more concise error handling in cases where you are suspicious of the email source such as it comes from user input.
        /// </summary>
        /// <param name="emailAddressValue"></param>
        /// <returns>Result&lt;EmailAddress&gt;</returns>
        /// <remarks>
        /// This verifies:  
        ///     that the email is not <see langword="null"/>;
        ///     that email is at leaset 3 characters long;
        ///     that the email does not start with an @ sign;
        ///     that the email does not end with an @ sign;
        ///     that the email contains 1 and only 1 @ sign;
        /// </remarks>
        public static Result<EmailAddress> CreateEmailAddress(MayBe<string> emailAddressValue)
        {
            return ValidateEmailAddress(emailAddressValue).OnSuccess<string, EmailAddress>(v => new EmailAddress(v, false));
        }

        /// <summary>
        /// Implicit conversion for simpler readability to MayBe&lt;String&gt;. Only use this implicit cast when expecting a valid EmailAddress and throwing an exception is a reasonable thing to do.
        /// </summary>
        /// <param name="possibleEmail"></param>
        /// <exception cref="InvalidCastException">This is thrown if the string passed in is not a valid email with the appropriate error.</exception>
        /// <remarks>This implicitly casts a sting parameter to a MayBe&lt;string&gt; parameter and then use that implicit operator with the MayBe&lt;string&gt; parameter.
        /// </remarks>
        public static implicit operator EmailAddress([AllowNull]string possibleEmail)
        {
            return new EmailAddress(new MayBe<string>(possibleEmail));
        }

        /// <summary>
        /// Implicit conversion from May&lt;Be&gt; string to be more explicit about whether the string is null. Only use this implicit cast when expecting a valid EmailAddress and throwing an exception is a reasonable thing to do.
        /// </summary>
        /// <param name="possibleEmail"></param>
        /// <exception cref="InvalidCastException">This is thrown if the string passed in is not a valid email with the appropriate error.</exception>
        public static implicit operator EmailAddress(MayBe<string> possibleEmail)
        {
            return new EmailAddress(possibleEmail);
        }

        /// <summary>
        /// The Valid EmailAddress value
        /// </summary>
        public string EmailAddressValue
        {
            get
            {
                return Value.Value;
            }
        }

        /// <summary>
        /// Note: by the time this is called all checks for null and 
        /// NoValue have already been called so we just deal with the equality of valid objects.
        /// </summary>
        /// <param name="other"></param>
        /// <returns>whether the two are equal</returns>
        protected override bool EqualsCore(string other)
        {
            return Value.Equals(other);
        }

        /// <summary>
        /// ValueProperty inner GetHash routine
        /// </summary>
        /// <returns>an Integer hash of the  emailaddress class</returns>
        public override int GetHashCode()
        {
            return Value.GetHashCode();
        }
    }
}

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.

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.3 388 11/15/2021
1.2.1 279 10/14/2021
1.0.2 316 10/4/2021
1.0.2-beta 378 9/27/2021

With Unity Tools
Removed unused UnicodeString16 ValueProperty.