Categories
How To How To

How to [Smartly] add Braces in C#

If you need a SQL object correctly quoted by the [ and ] braces.

		/// <summary>
		///     Add the left [ and right ] braces if they're not already on the string.
		///     <para>An empty or whitepsace string throws <see cref="ArgumentEmptyException"/>.</para>
		/// </summary>
		/// <param name="self"></param>
		/// <returns></returns>
		/// <exception cref="ArgumentEmptyException"></exception>
		[DebuggerStepThrough]
        [NotNull]
        [Pure]
        public static String SmartBraces( [NotNull] this String? self ) {
            self = self.Trimmed();

            if ( String.IsNullOrEmpty( self ) ) {
	            throw new ArgumentEmptyException( nameof( self ) );
            }

			if ( self.StartsWith( "[", StringComparison.Ordinal ) && self.EndsWith( "]", StringComparison.Ordinal ) ) {
	            self = self[ 1..^1 ]?.Trim();
            }

            if ( String.IsNullOrEmpty( self ) ) {
	            throw new ArgumentEmptyException( nameof( self ) );
			}

			return $"{'['}{self}{']'}";
        }

		/// <summary>Trim the ToString() of the object; returning null if null, empty, or whitespace.</summary>
		/// <param name="self"></param>
		/// <returns></returns>
		[DebuggerStepThrough]
		[CanBeNull]
		[Pure]
		public static String? Trimmed<T>( [CanBeNull] this T self ) =>
			self switch {
				null => default( String? ),
				String s => s.Trim().NullIfEmpty(),
				var _ => self.ToString()?.Trim().NullIfEmpty()
			};


		/// <summary>Returns null if <paramref name="self" /> is <see cref="String.IsNullOrEmpty" />.</summary>
		/// <param name="self"></param>
		/// <returns></returns>
		[CanBeNull]
		[DebuggerStepThrough]
		[Pure]
		public static String? NullIfEmpty( [CanBeNull] this String? self ) => String.IsNullOrEmpty( self ) ? null : self;


//Note: All attributes can be removed.

Categories
How To

Boolean Parsing Constants in C#


		/// <summary>
		/// N, 0, no, false, fail, failed, failure, bad
		/// </summary>
		[NotNull]
		[ItemNotNull]
		public static readonly String[] FalseStrings = {
			"N", "0", "no", "false", Boolean.FalseString, "fail", "failed", "failure", "bad"
		};

		/// <summary>
		/// Y, 1
		/// </summary>
		[NotNull]
		public static readonly Char[] TrueChars = {
			'Y', '1'
		};

		/// <summary>
		/// Y, 1, yes, true, Success, good, Go, Positive, Continue
		/// </summary>
		[NotNull]
		[ItemNotNull]
		public static readonly String[] TrueStrings = {
			"Y", "1", "yes", "true", Boolean.TrueString, nameof( Status.Success ), "good", nameof( Status.Go ), nameof( Status.Positive ), nameof( Status.Continue ), nameof(Status.Okay)
		};

Categories
How To

How to convert any object to a Boolean value in C#

        /// <summary>
        ///     <para>Returns true if <paramref name="value" /> is a true, 'Y', "yes", "true", "1", or '1'.</para>
        ///     <para>Returns false if <paramref name="value" /> is a false, 'N', "no", "false", or '0'.</para>
        ///     <para>A null will return false.</para>
        /// </summary>
        /// <param name="value"></param>
        [Pure]
        public static Boolean ToBoolean<T>( [CanBeNull] this T value ) {
            switch ( value ) {
                case null: return false;

                case Boolean b: return b;

                case Char c: return c.In( ParsingConstants.TrueChars );

                case Int32 i: return i >= 1;

                case String s when String.IsNullOrWhiteSpace( s ): return false;

                case String s: {
                    var clean = s.Trimmed();

                    if ( clean is null ) {
                        return false;
                    }

                    if ( clean.In( ParsingConstants.TrueStrings ) ) {
                        return true;
                    }

                    if ( Boolean.TryParse( clean, out var result ) ) {
                        return result;
                    }

                    break;
                }
            }

            var t = value.ToString();

            if ( !String.IsNullOrWhiteSpace( t ) ) {
                t = t.Trim();

                if ( t.In( ParsingConstants.TrueStrings ) ) {
                    return true;
                }

                if ( t.In( ParsingConstants.FalseStrings ) ) {
                    return false;
                }

                if ( Boolean.TryParse( t, out var rest ) ) {
                    return rest;
                }
            }

            return false;
        }

        [DebuggerStepThrough]
        [Pure]
        public static Boolean? ToBooleanOrNull<T>( [CanBeNull] this T value ) {
            switch ( value ) {
                case null: return default( Boolean? );

                case Boolean b: return b;

                case Char c: return c.In( ParsingConstants.TrueChars );

                case Int32 i: return i >= 1;

                case String s when String.IsNullOrWhiteSpace( s ): return default( Boolean? );

                case String s: {
                    var trimmed = s.Trimmed();

                    if ( trimmed is null ) {
                        return default( Boolean? );
                    }

                    if ( trimmed.In( ParsingConstants.TrueStrings ) ) {
                        return true;
                    }

                    if ( trimmed.In( ParsingConstants.FalseStrings ) ) {
                        return default( Boolean? );
                    }

                    if ( Boolean.TryParse( trimmed, out var result ) ) {
                        return result;
                    }

                    break;
                }
            }

            var t = value.ToString();

            if ( String.IsNullOrWhiteSpace( t ) ) {
                return default( Boolean? );
            }

            t = t.Trim();

            if ( t.In( ParsingConstants.TrueStrings ) ) {
                return true;
            }

            if ( t.In( ParsingConstants.FalseStrings ) ) {
                return default( Boolean? );
            }

            return Boolean.TryParse( t, out var rest ) ? rest : default( Boolean? );
        }

                public static Boolean ToBooleanOrThrow<T>( [CanBeNull] this T value ) =>
            value.ToBooleanOrNull() ?? throw new FormatException( $"Unable to convert {nameof( value ).SmartQuote()} [{value}] to a boolean value." );

		/// <summary>Trim the ToString() of the object; returning null if null, empty, or whitespace.</summary>
		/// <param name="self"></param>
		/// <returns></returns>
		[DebuggerStepThrough]
		[CanBeNull]
		[Pure]
		public static String? Trimmed<T>( [CanBeNull] this T self ) =>
			self switch {
				null => default( String? ),
				String s => s.Trim().NullIfEmpty(),
				var _ => self.ToString()?.Trim().NullIfEmpty()
			};


		/// <summary>Returns null if <paramref name="self" /> is <see cref="String.IsNullOrEmpty" />.</summary>
		/// <param name="self"></param>
		/// <returns></returns>
		[CanBeNull]
		[DebuggerStepThrough]
		[Pure]
		public static String? NullIfEmpty( [CanBeNull] this String? self ) => String.IsNullOrEmpty( self ) ? null : self;

		/// <summary>
		/// N, 0, no, false, fail, failed, failure, bad
		/// </summary>
		[NotNull]
		[ItemNotNull]
		public static readonly String[] FalseStrings = {
			"N", "0", "false", Boolean.FalseString, "fail", "failed", "stop", nameof( Status.Bad ), nameof( Status.Failure ), nameof( Status.No ),
			nameof( Status.Negative )
		};

		/// <summary>
		/// Y, 1
		/// </summary>
		[NotNull]
		public static readonly Char[] TrueChars = {
			'Y', '1'
		};

		/// <summary>
		/// Y, 1, yes, true, Success, good, Go, Positive, Continue
		/// </summary>
		[NotNull]
		[ItemNotNull]
		public static readonly String[] TrueStrings = {
			"Y", "1", "yes", "true", Boolean.TrueString, nameof( Status.Success ), "good", nameof( Status.Go ), nameof( Status.Positive ), nameof( Status.Continue ), nameof(Status.Okay)
		};


Categories
How To

How to get the Description Attribute in C#

		[CanBeNull]
		public static String? GetDescription<T>( [CanBeNull] this T e ) where T : IConvertible {
			if ( e is not Enum ) {
				return default( String? );
			}

			var type = e.GetType();

			foreach ( Int32 val in Enum.GetValues( type ) ) {
				if ( val != e.ToInt32( CultureInfo.InvariantCulture ) ) {
					continue;
				}

				var ename = type.GetEnumName( val );

				if ( ename is null ) {
					continue;
				}

				var memInfo = type.GetMember( ename );

				if ( memInfo[0].GetCustomAttributes( typeof( DescriptionAttribute ), false ).FirstOrDefault() is DescriptionAttribute descriptionAttribute ) {
					return descriptionAttribute.Description;
				}
			}

			return default( String? );
		}

Categories
How To

How to check the return Status in C#

	public static class StatusExtensions {

		static StatusExtensions() {
			if ( Status.Good.IsBad() ) {
				throw new InvalidOperationException( "Someone blinked." );
			}

			if ( Status.Failure.IsGood() ) {
				throw new InvalidOperationException( "Someone blinked." );
			}

			if ( Status.Success.IsBad() ) {
				throw new InvalidOperationException( "Someone blinked." );
			}

			if ( !Status.Unknown.IsUnknown() ) {
				throw new InvalidOperationException( "Someone blinked." );
			}
		}

		[Pure]
		[MethodImpl( MethodImplOptions.AggressiveInlining )]
		public static Boolean Failed( this Status status ) => status <= Status.Failure;

		[Pure]
		[MethodImpl( MethodImplOptions.AggressiveInlining )]
		public static Boolean IsBad( this Status status ) => status.Failed();

		[Pure]
		[MethodImpl( MethodImplOptions.AggressiveInlining )]
		public static Boolean IsUnknown( this Status status ) => status == Status.Unknown || !status.IsBad() && !status.IsGood();

		[Pure]
		[MethodImpl( MethodImplOptions.AggressiveInlining )]
		public static Boolean Succeeded( this Status status ) => status >= Status.Success;

		[Pure]
		[MethodImpl( MethodImplOptions.AggressiveInlining )]
		public static Boolean IsGood( this Status status ) => status.Succeeded();

		[Pure]
		[NotNull]
		public static String Symbol( this Status status ) => status.GetDescription() ?? Symbols.Null;

		[Pure]
		[MethodImpl( MethodImplOptions.AggressiveInlining )]
		public static Status ToStatus( this Boolean status ) => status ? Status.Success : Status.Failure;

	}

Categories
How To

How to Return Status in C#

I use the design pattern of returning a Status. Example:

	public enum Status : Int16 {

		[Description( Symbols.SkullAndCrossbones )]
		Fatal = Exception - 1,

		[Description( Symbols.Exception )]
		Exception = Error - 1,

		[Description( Symbols.Error )]
		Error = Warning - 1,

		[Description( Symbols.Warning )]
		Warning = Skip - 1,

		[Description( Symbols.Fail )]
		Skip = Timeout - 1,

			[Description( Symbols.Timeout )]
			Timeout = Stop - 1,

				[Description( Symbols.StopSign )]
				Stop = Halt - 1,

					[Description( Symbols.StopSign )]
					Halt = Negative - 1,

						[Description( Symbols.FailBig )]
						Negative = No - 1,

							[Description( Symbols.Fail )]
							No = Bad - 1,

								[Description( Symbols.Fail )]
								Bad = Failure - 1,

									[Description( Symbols.BlackStar )]
									Failure = -1,

										[Description( Symbols.Unknown )]
										Unknown = 0,

									[Description( Symbols.WhiteStar )]
									Success = 1,

									[Description( Symbols.WhiteStar )]
									Okay = Success,

								[Description( Symbols.CheckMark )]
								Good = Success + 1,

							[Description( Symbols.CheckMark )]
							Yes = Good + 1,

						[Description( Symbols.CheckMark )]
						Positive = Yes + 1,

					[Description( Symbols.CheckMark )]
					Continue = Positive + 1,

				[Description( Symbols.CheckMark )]
				Go = Continue + 1,

			[Description( Symbols.CheckMark )]
			Proceed = Go + 1,

		[Description( Symbols.CheckMark )]
		Advance = Proceed + 1,

		[Description( Symbols.CheckMark )]
		Flawless = Advance + 1
	}

Categories
How To

How to return null if a String is null or Empty in C#

        /// <summary>Returns null if <paramref name="self" /> is <see cref="String.IsNullOrEmpty" />.</summary>
        /// <param name="self"></param>
        /// <returns></returns>
        [CanBeNull]
        [DebuggerStepThrough]
        [Pure]
        public static String? NullIfEmpty( [CanBeNull] this String? self ) => String.IsNullOrEmpty( self ) ? null : self;


Categories
How To

How to Trim whitespace from a String in C#

        /// <summary>Trim the ToString() of the object; returning null if null, empty, or whitespace.</summary>
        /// <param name="self"></param>
        /// <returns></returns>
        [DebuggerStepThrough]
        [CanBeNull]
        [Pure]
        public static String? Trimmed<T>( [CanBeNull] this T self ) =>
            self switch {
                null => default( String? ),
                String s => s.Trim().NullIfEmpty(),
                var _ => self.ToString()?.Trim().NullIfEmpty()
            };

Categories
How To

How to convert a Guid to BigInteger in C#

        [DebuggerStepThrough]
        [Pure]
        public static BigInteger ToBigInteger( this Guid self ) => new( self.ToByteArray() );

Categories
C#

Easy Pattern to implement IDisposable

Here is my C# implementation for an easy way to implement the IDisposable pattern in your classes.

Just override DisposeManaged() and/or DisposeNative() when needed.

The embedded code shown below is pulled directly from my GitHub gist here.
If any formatting is ‘off’ or links don’t work, contact the WordPress.com complaint department. :/

// Copyright © Protiguous. All Rights Reserved.
//
// This entire copyright notice and license must be retained and must be kept visible in any binaries, libraries, repositories, or source code (directly or derived) from our binaries, libraries, projects, solutions, or applications.
//
// All source code belongs to Protiguous@Protiguous.com unless otherwise specified or the original license has been overwritten by formatting. (We try to avoid it from happening, but it does accidentally happen.)
//
// Any unmodified portions of source code gleaned from other sources still retain their original license and our thanks goes to those Authors.
// If you find your code unattributed in this source code, please let us know so we can properly attribute you and include the proper license and/or copyright(s).
//
// If you want to use any of our code in a commercial project, you must contact Protiguous@Protiguous.com for permission, license, and a quote.
//
// Donations, payments, and royalties are accepted via bitcoin:1Mad8TxTqxKnMiHuZxArFvX8BuFEB9nqX2 and PayPal:Protiguous@Protiguous.com
//
// ====================================================================
// Disclaimer: Usage of the source code or binaries is AS-IS.
// No warranties are expressed, implied, or given.
// We are NOT responsible for Anything You Do With Our Code.
// We are NOT responsible for Anything You Do With Our Executables.
// We are NOT responsible for Anything You Do With Your Computer.
// ====================================================================
//
// Contact us by email if you have any questions, helpful criticism, or if you would like to use our code in your project(s).
// For business inquiries, please contact me at Protiguous@Protiguous.com.
//
// Our software can be found at "https://Protiguous.Software/&quot;
// Our GitHub address is "https://github.com/Protiguous&quot;.
//
// File "ABetterClassDispose.cs" last formatted on 2020-11-07.
#nullable enable
namespace Librainian.Utilities {
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
/// <summary>
/// <para>A class for easier implementation the proper <see cref="IDisposable" /> pattern.</para>
/// <para>Implement overrides on <see cref="DisposeManaged" />, and <see cref="DisposeNative" /> as needed.</para>
/// <code></code>
/// </summary>
/// <remarks>ABCD (hehe).</remarks>
/// <copyright>Created by Protiguous.</copyright>
public abstract class ABetterClassDispose : IDisposable {
private Int32 _hasDisposedManaged;
private Int32 _hasDisposedNative;
private Int32 _hasSuppressedFinalize;
public Boolean HasDisposedManaged {
[MethodImpl( MethodImplOptions.AggressiveInlining )]
[DebuggerStepThrough]
get => Interlocked.CompareExchange( ref this._hasDisposedManaged, 0, 0 ) == 1;
[MethodImpl( MethodImplOptions.AggressiveInlining )]
[DebuggerStepThrough]
set {
if ( this.HasDisposedManaged ) {
return; //don't allow the setting to be changed once it has been set.
}
Interlocked.Exchange( ref this._hasDisposedManaged, value ? 1 : 0 );
}
}
public Boolean HasDisposedNative {
[MethodImpl( MethodImplOptions.AggressiveInlining )]
[DebuggerStepThrough]
get => Interlocked.CompareExchange( ref this._hasDisposedNative, 0, 0 ) == 1;
[MethodImpl( MethodImplOptions.AggressiveInlining )]
[DebuggerStepThrough]
set {
if ( this.HasDisposedNative ) {
return; //don't allow the setting to be changed once it has been set.
}
Interlocked.Exchange( ref this._hasDisposedNative, value ? 1 : 0 );
}
}
public Boolean HasSuppressedFinalize {
[MethodImpl( MethodImplOptions.AggressiveInlining )]
[DebuggerStepThrough]
get => Interlocked.CompareExchange( ref this._hasSuppressedFinalize, 0, 0 ) == 1;
[MethodImpl( MethodImplOptions.AggressiveInlining )]
[DebuggerStepThrough]
set {
if ( this.HasSuppressedFinalize ) {
return; //don't allow the setting to be changed once it has been set.
}
Interlocked.Exchange( ref this._hasSuppressedFinalize, value ? 1 : 0 );
}
}
/// <summary>Can be changed to a property, if desired.</summary>
/// <returns></returns>
public Boolean IsDisposed => this.HasDisposedManaged && this.HasDisposedNative;
/// <summary>
/// <para>
/// Disposes of managed resources, then unmanaged resources, and then calls <see cref="GC.SuppressFinalize" /> for this object.
/// </para>
/// <para>Note: Calling <see cref="Dispose()" /> multiple times has no effect beyond the first call.</para>
/// </summary>
[DebuggerStepThrough]
public void Dispose() {
if ( !this.HasDisposedManaged ) {
try {
this.DisposeManaged(); //Any derived class should have overloaded this method and disposed of any managed objects inside.
}
catch ( Exception exception ) {
Debug.WriteLine( exception );
}
finally {
this.HasDisposedManaged = true;
}
}
if ( !this.HasDisposedNative ) {
try {
this.DisposeNative(); //Any derived class should overload this method.
}
catch ( Exception exception ) {
Debug.WriteLine( exception );
}
finally {
this.HasDisposedNative = true;
}
}
if ( this.IsDisposed && !this.HasSuppressedFinalize ) {
try {
GC.SuppressFinalize( this );
}
catch ( Exception exception ) {
Debug.WriteLine( exception );
}
finally {
this.HasSuppressedFinalize = true;
}
}
}
/// <summary>
/// Just calls <see cref="Dispose()" />. The parameter <paramref name="dispose" /> has no effect with this design.
/// </summary>
/// <param name="dispose"></param>
[DebuggerStepThrough]
public void Dispose( Boolean dispose ) => this.Dispose();
/// <summary>Override this method to dispose of any <see cref="IDisposable" /> managed fields or properties.</summary>
/// <example>
/// <code>using var bob = new DisposableType();</code>
/// </example>
[DebuggerStepThrough]
public virtual void DisposeManaged() { }
/// <summary>
/// Dispose of COM objects, handles, etc in this method.
/// </summary>
[DebuggerStepThrough]
public virtual void DisposeNative() =>
/*make this virtual so it is optional*/
this.HasDisposedNative = true;
/*
/// <summary>Set via <see cref="SetDisposeHint" /> to help find if an object has not been disposed of properly.</summary>
[CanBeNull]
private String? DisposeHint { get; set; }
*/
/*
/// <summary>Call at any time to set a debugging hint as to the creator of this disposable.</summary>
/// <param name="hint"></param>
[Conditional( "DEBUG" )]
public void SetDisposeHint( [CanBeNull] String? hint ) => this.DisposeHint = hint;
*/
}
}
// Copyright © Protiguous. All Rights Reserved.
//
// This entire copyright notice and license must be retained and must be kept visible in any binaries, libraries, repositories, or source code (directly or derived) from our binaries, libraries, projects, solutions, or applications.
//
// All source code belongs to Protiguous@Protiguous.com unless otherwise specified or the original license has been overwritten by formatting. (We try to avoid it from happening, but it does accidentally happen.)
//
// Any unmodified portions of source code gleaned from other sources still retain their original license and our thanks goes to those Authors.
// If you find your code unattributed in this source code, please let us know so we can properly attribute you and include the proper license and/or copyright(s).
//
// If you want to use any of our code in a commercial project, you must contact Protiguous@Protiguous.com for permission, license, and a quote.
//
// Donations, payments, and royalties are accepted via bitcoin:1Mad8TxTqxKnMiHuZxArFvX8BuFEB9nqX2 and PayPal:Protiguous@Protiguous.com
//
// ====================================================================
// Disclaimer: Usage of the source code or binaries is AS-IS.
// No warranties are expressed, implied, or given.
// We are NOT responsible for Anything You Do With Our Code.
// We are NOT responsible for Anything You Do With Our Executables.
// We are NOT responsible for Anything You Do With Your Computer.
// ====================================================================
//
// Contact us by email if you have any questions, helpful criticism, or if you would like to use our code in your project(s).
// For business inquiries, please contact me at Protiguous@Protiguous.com.
//
// Our software can be found at "https://Protiguous.Software/&quot;
// Our GitHub address is "https://github.com/Protiguous&quot;.
//
// File "ExampleUsingABetterClassDispose.cs" last formatted on 2020-11-07.
#nullable enable
namespace Librainian.Tests {
using System;
using System.IO;
using Utilities;
public class ExampleUsingABetterClassDispose : ABetterClassDispose {
private MemoryStream? _memoryStream = new MemoryStream();
private SysComObject? _sysComObject = new SysComObject();
public ExampleUsingABetterClassDispose() => this._sysComObject?.ReserveMemory();
public override void DisposeManaged() {
using ( this._memoryStream ) {
this._memoryStream = null;
}
base.DisposeManaged();
}
public override void DisposeNative() {
this._sysComObject?.ReleaseMemory();
this._sysComObject = null;
base.DisposeNative();
}
}
/// <summary>
/// A fake COM interface object.
/// </summary>
public class SysComObject {
public void ReleaseMemory() {
throw new NotImplementedException( "Not actual code." );
}
public void ReserveMemory() {
throw new NotImplementedException( "Not actual code." );
}
}
}