Jack’s Top 10 String Extension Methods

String Extension Methods in C# .NET can make life so much easier.

String Extension Methods Add Functionality
Extension Method

String Extension Methods in C# .NET can make life so much easier. Everyday functions that used to require extended syntax with a return value are a thing of the past. Now with Microsoft Visual Studio, we can just add a using to our Extensions collection and have full use of them from our Share Library.What is a String Extension Method?

An extension method is simply an additional method. It is a way of attaching additional functionality to a type which is available to you throughout your code without need to instantiate another class.

There’s plenty of best practices for extension methods. A great article is here on Microsoft’s site.

ToBoolean() Extension Method

Probably my most used and handiest is a simple one. There are so many times when we receive text, whether in a JSON payload or in a view that we need to see if it is a legitimate boolean value.

Here is a simple implementation of ToBoolean()

    /// <summary>
    /// Convert a string to a boolean
    /// Yasgar Technology Group, Inc.
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool ToBoolean(this string value)
    {
        if (value == null) { return false; }
        if (value.Trim().ToLower() == "true" || value == "1" || value == "yes")
        { return true; }
        else
        { return false; }
    }

This is a simple implementation that does a quick compare against a set of strings.

IsNumericInteger() Extension Method

Often, during a view post back, I need to determine if a particular value is numeric that was accepted in a text box. While I usually try to validate this type of input using javascript, there are many ways that people can bypass that validation. I use this specific one to validate that this value is indeed an integer and not a decimal.

   /// <summary>
    /// Return bool whether the value in the string is a numeric integer
    /// Yasgar Technology Group, Inc. - www.ytgi.com
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool IsNumericInteger(this string value)
    {
        return long.TryParse(value, out long _tempvalue);
    }

Here is a simple sample implementation that does a quick TryParse() to see if it is a pass or fail.

IsNumericDecimal() Extension Method

Often there are numeric fields that you’re receiving via a post back or JSON or XML payload. This is a quick way to determine if it’s a decimal fit or not. Remember, that integers will pass this test as well. So use the IsNumericInteger() extension method if you want to determine if the numeric value has a decimal in it.

    /// <summary>
    /// Return bool whether the value in the string is a numeric decimal
    /// Yasgar Technology Group, Inc. - www.ytgi.com
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool IsNumericDecimal(this string value)
    {
        return decimal.TryParse(value, out decimal _tempvalue);
    }

ToDateFromCCYYMMDD() Extension Method

There are often cases where dates are passed around in CCYYMMDD format, such as 20220329. This is a preferred method for me when I need to transfer a date as a query string parameter argument and don’t want the mess of a full DateTime. This extension method converts that string to a DateTime object.

    /// <summary>
    /// Convert a string in CCYYMMDD format to a valid date
    /// Yasgar Technology Group, Inc. - www.ytgi.com
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static DateTime ToDateFromCCYYMMDD(this string value)
    {
        if (!string.IsNullOrWhiteSpace(value))
        {
            if (value == "99999999")
            {
                return DateTime.MaxValue;
            }
            else
            {
                string _value = value.Trim();
                if (_value.IsNumericInteger() && _value.Trim().Length == 8)
                {
                        int.TryParse(_value.Substring(0, 4), out int year);
                        int.TryParse(_value.Substring(4, 2), out int month);
                        int.TryParse(_value.Substring(6, 2), out int day);

                        DateTime datItem = new DateTime(year, month, day);
                        return datItem;
                }
            }
        }

        return DateTime.MinValue;

    }

Notice that I check for the “99999999” string. This is a very popular marker for “no expiration” date, especially in mainframe data.

ToDateFromString() Extension Method

This is a variation on the ToDateFromCCYYMMDD() extension method. You might ask why I would have an extension method that probably does the same thing as DateTime.TryParse()? Well, simple, I’ve worked with lots of data where they have dates like “99999999” and “99/99/9999” which I want to handle properly.

    /// <summary>
    /// Convert a string in MM/DD/CCYY format to a valid date
    /// Yasgar Technology Group, Inc. - www.ytgi.com
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static DateTime ToDateFromString(this string value)
    {
        if (!string.IsNullOrWhiteSpace(value))
        {
            if ((value == "99999999") || (value == "99/99/9999"))
            {
                return DateTime.MaxValue;
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(value))
                {
                    DateTime.TryParse(value, out DateTime _value);
                    return _value;
                }
                else
                {
                    return DateTime.MinValue;
                }
            }
        }

        return DateTime.MinValue;

    }

Notice it does use the standard DateTime.TryParse(), but only after it checks for funky dates. You may also want to put in checks for dates that are popular in your environment, such as the old SQL Server minimum date of “1/1/1753”

Trim(int MaxLength) (Accepting a maximum length)

This extension method accepts an integer specifying the maximum length of the returned string. I use this method all the time, especially when stuffing data into old data tables where data needs to be truncated. To be honest, I find it hard to believe that after all this time, it’s still not an overload in the framework.

    /// <summary>
    /// Trim a string down to a particular size
    /// Yasgar Technology Group, Inc. - www.ytgi.com
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string Trim(this string value, int p_MaxLength)
    {
        try
        {
            if (value != null)
            {
                return value.Substring(0, Math.Min(p_MaxLength, value.Length));
            }
            else
            {
                return string.Empty;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

Remember, you should never just randomly trim data without assessing whether it is going to cause data corruption. Important data should not be truncated with a method like this unless you’re logging the activity somewhere.

RemoveSpecialChars(bool p_DashOkay = false, bool p_HashOkay = false)

This is one of my favorite extension methods, not only because I use it so often when validating data, but because it’s proven to be so versatile that I haven’t had to modify very much over the years. This method accepts two parameters to allow you to keep dashes and hash signs in the return if you want. They both default to false if you don’t set them.

        /// <summary>
        /// Remove special characters from a string with option to 
        /// retain Dashes and Hash signs
        /// Yasgar Technology Group, Inc. - www.ytgi.com
        /// </summary>
        /// <param name="value"></param>
        /// <param name="dashOkay"></param>
        /// <param name="hashOkay"></param>
        /// <returns></returns>
        public static string RemoveSpecialChars(this string value, 
                                                bool dashOkay = false, 
                                                bool hashOkay = false)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                if (value != null)
                {
                    if (dashOkay && hashOkay)
                    {
                        foreach (char c in value)
                        {
                            if ((c >= '0' && c <= '9') || 
                                (c >= 'A' && c <= 'Z') || 
                                (c >= 'a' && c <= 'z') || 
                                c == '-' || 
                                c == '#' || 
                                c == ' ')
                            {
                                sb.Append(c);
                            }
                        }
                    }
                    else if (dashOkay && hashOkay == false)
                    {
                        foreach (char c in value)
                        {
                            if ((c >= '0' && c <= '9') || 
                                (c >= 'A' && c <= 'Z') || 
                                (c >= 'a' && c <= 'z') || 
                                c == '-' || c == ' ')
                            {
                                sb.Append(c);
                            }
                        }
                    }
                    else if (dashOkay == false && hashOkay)
                    {
                        foreach (char c in value)
                        {
                            if ((c >= '0' && c <= '9') || 
                                (c >= 'A' && c <= 'Z') || 
                                (c >= 'a' && c <= 'z') || 
                                c == '#' || c == ' ')
                            {
                                sb.Append(c);
                            }
                        }
                    }
                    else if (!dashOkay && !hashOkay)
                    {
                        foreach (char c in value)
                        {
                            if ((c >= '0' && c <= '9') || 
                                (c >= 'A' && c <= 'Z') || 
                                (c >= 'a' && c <= 'z') || 
                                c == ' ')
                            {
                                sb.Append(c);
                            }
                        }
                    }

                }

                return sb.ToString();

            }
            catch (Exception)
            {
                throw;
            }
        }

RemoveSpaces(bool StripInternal = false)

The standard Trim() extension method in the .NET framework will remove spaces from the beginning and end, but does it remove spaces inside the string? No, of course not. But there are times when that is needed and I have just the method read for it. It also trims the front and back as well, so no need to do an extra Trim() on it.

    /// <summary>
    /// Strip spaces from a string
    /// Yasgar Technology Group, Inc. - www.ytgi.com
    /// </summary>
    /// <param name="value"></param>
    /// <param name="StripInternal">strip spaces from within the string</param>
    /// <returns></returns>
    public static string RemoveSpaces(this string value, bool StripInternal = false)
    {
        if (!string.IsNullOrWhiteSpace(value))
            if (StripInternal)
            {
                return new string(value.ToCharArray()
                                    .Where(c => !Char.IsWhiteSpace(c))
                                    .ToArray());
            }
            else
            {
                return value.Trim();
            }
        else
        {
            return string.Empty;
        }
    }

ToDecimal() Extension Method

If you need to retrieve a decimal value from a string, you can use this extension method. It will actually return a nullable decimal (decimal?). It will be null if the value could not be coerced into a decimal. This one could be used in place of the IsNumericDecimal() method if you need to retrieve the value and not simply pass it on if it validates. There is the extra step to check whether the return value is null though.

    /// <summary>
    /// Convert a string to a Decimal, return null if fails
    /// Yasgar Technology Group, Inc. - www.ytgi.com
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static decimal? ToDecimal(this string value)
    {
        if (decimal.TryParse(value, out decimal decItem))
        { return decItem; }
        else
        { return null; }

    }

These are two powerful extension methods that I group together. They come in so handy for encrypting and decrypting values on the fly. While it’s probably not the greatest plan to use this for an encryption strategy, I often use them while data is in flight. For instance, I parse a text file and save it to a staging database table for later processing. If there is Protected Health Information (PHI), or even Personally Identifiable Information (PII), then I’ll use this method to protect it from prying eyes before it winds up in its final resting place.

Both of these extension methods make use of the CRijndael namespaces in the framework.

ToProperCase()

How often do we need to convert a standard text string to proper or title case. All the time! So this is a solution for your needs!

using System.Globalization;
using System.Threading;

        /// <summary>
        /// Convert a string to Proper case 
        /// based on the current thread culture
        /// Yasgar Technology Group, Inc. - www.ytgi.com
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string ToProperCase(this string text)
        {
            if (text != null)
            {
                CultureInfo _cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo textInfo = _cultureInfo.TextInfo;
                // Send in the text as lower case to allow the method to
                // make all the decisions
                return textInfo.ToTitleCase(text.ToLower());
            }
            else
            {
                return text;
            }
        }

If you love Extension Methods, take a look at some other posts I have about others:

OrderBy Extension for Linq Queries

Knock out 1/1/0001 Dates in MVC

Extension Method to Convert Types

Stay tuned for more extension methods that I’ve used for years coming soon!

Storing .NET NuGet Packages in GitHub

I can’t believe that I didn’t write this post two years ago when I figured this out. I apologize to everyone that had to figure this out on their own.

When I first tried to create NuGet packages from my apps and upload them, I wasn’t using Jenkins. But no matter, the concepts were the hard part, not the application that was doing the creation and uploading (push).

Scenario

Your doing software development and have one or more components that you want to re-use in many projects. Whether it’s a collection of extensions or models for an API. The goal is to have a versioned download that other developers can grab which is versioned and easily added to their application. I won’t bore you here with why this is a good idea, even when many corporate developers argue about what a pain it is to use NuGet packages for this.

The main concern is that you don’t want this proprietary code to be publicly available on NuGet.org. The three choices that I’ve worked with are File Share, Azure Artifacts and GitHub Packages. I’m not going to discuss Azure Artifact here, because they actually are a little easier, because if your using Azure Devops, then the authentication is coordinated, where as in GitHub, it’s not so easy.

I spent many hours trying get this to work. After a few hours, I actually got a NuGet package to build and then it would upload to GitHub. Then the next day I would try it and it would fail again. I opened a ticket with GitHub and had a few email exchanges. The last email basically said “If you figure it out, let us know how you did it.” Well, I have to admit that I never did, as much as I don’t like the saying that “It’s not my job”, I’m not being paid to educate GitHub support staff.

GitHub Support: “If you figure it out, let us know how you did it.”

Anyway, enough with the small talk, let’s get down to it.

Concepts

I need to state that this solution applies to all versions of .NET Core and .NET 5.x versions that I’ve been using for a few years. If you’re trying to do this with older .NET Framework versions, then some of this may not apply.

There are three major things you’ll have to be aware of when creating a NuGet package.

Your Project File

The default project file in .NET Core or .NET 5.x is not sufficient to create a NuGet package, unless you hard code all the data in the {ApplicationName}.nuspec file covered below. I recommend embellishing the csproj file.

There are several things that a NuGet package requires, id (PackageId) , title, etc. being a few. You need to make sure that all this data is in your csproj file. I have a sample below:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>library</OutputType>
    <TargetFramework>net5.0</TargetFramework>
    <PackageId>YTG-Framework-V2</PackageId>
    <Version>2.1.1</Version>
    <Authors>Jack Yasgar</Authors>
    <Company>Yasgar Technology Group, Inc.</Company>
    <PackageDescription>Shared resources for all Yasgar Technology Group applications</PackageDescription>
    <RepositoryUrl>https://github.com/YTGI/YTG-Framework-V2</RepositoryUrl>
    <Description>Shared framework methods and objects used throughout the enterprise.</Description>
    <Copyright>@2021 - Yasgar Technology Group, Inc</Copyright>
    <AssemblyVersion>2.1.1.0</AssemblyVersion>
    <FileVersion>2.1.1.0</FileVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.3" />
    <PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="3.1.3" />
  </ItemGroup>
</Project>

Almost every line in this file is important. The “MOST” important one is the “Version” key highlighted. When you first get your upload (nuget push) to work, it will work fine, but it will get an exception the second time of you don’t increment the version. The NuGet upload process ignores the “AssemblyVersion” and “FileVersion”.

{ApplicationName}.nuspec

This is the file that the nuget packager actually looks at to create a NuGet package. The file has a variable base syntax that will pull data from the csproj file, hence my recommendation that you use the csproj file as the source of truth. You have the option of hard coding values in here if you wish. Why use the variables you ask? Because, if you use the csproj file as the source of truth, then your {ApplicationName}.nuspec can have the same content in every project you have. I think that makes this process simpler if you plan to have several NuGet packages.

<?xml version="1.0" encoding="utf-8"?>
<package >
  <metadata>
    <id>$packageid$</id>
    <version>$version$</version>
    <title>$title$</title>
    <authors>$author$</authors>
    <owners>$author$</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <license type="expression">MIT</license>
    <projectUrl>$repositoryurl$</projectUrl>
    <description>$packagedescription$</description>
    <releaseNotes>Release</releaseNotes>
    <copyright>$copyright$</copyright>
    <tags>Utilities Extensions</tags>
  </metadata>
</package>

As you can see above in my live example, the only thing you might want to adjust is the <tags> entry. All the rest will pull from the project file as variables.

Now for the next tricky part. Here’s where your existing knowledge may hurt you. If you said to yourself that you don’t need a NuGet.config file in your project, your right, if you just want to fetch packages. But if your creating packages on Azure Pipelines or GitHub Actions, you’ll need it. If you’re creating your package on Jenkins, then you can just have a reusable NuGet.config in the C:\Users\{serviceid}\AppData\Roaming\NuGet folder. {serviceid} is the service account that Jenkins is running as, often LocalSystem, which means the {serviceid} = “Default”.

Okay, so now our project is ready for for a NuGet package build. So how do we get it pushed up. Well, that’s different depending on your environment. I’ll show you a few.

Command Line

First thing is to make sure your NuGet package gets created. You can do that in the CLI (Command Prompt):

dotnet pack {yourprojectfolder}\{yourprojectname}.csproj --configuration Release --output nupkgs

This should build your project and put the NuGet package in a folder called “nupkgs”. If this doesn’t work, you need to review all the messages and review the above configuration steps. Remember, this process is not concerned that you’re in a hurry.

If you wind up with a .nupkg file in the folder, then pat yourself on the back, you’re most of the way there. Here’s where I ended up opening a ticket with GitHub, because I had a nupkg, but I couldn’t get it to upload consistently. It turned out that I, and GitHub support, didn’t understand the different credentials.

I and GitHub support didn’t understand the different credentials.

In your NuGet.confg, there are two different sections.

packageSourceCredentials

	<packageSourceCredentials>
		<github>
			<add key="Username" value="JYasgarYTGI" />
			<add key="ClearTextPassword" value="ghp_asdsfsfjAbunchofBScharacters" />
		</github>
	</packageSourceCredentials>

and apikeys

	<apikeys>
		<add key="https://nuget.pkg.github.com/YTGI/index.json" value="awholebunchofbullshit==" />
	</apikeys>

The “packageSourceCredentials” are exactly what they say, it is the credentials to READ the nuget packages. So that’s where I got sidetracked, it has nothing to do with uploading the package after it’s created.

In order to actually PUSH (upload) a file, you need to have apikeys credentials. It DOES NOT use your regular GitHub access in the “packageSourceCredentials ” to upload packages. That means you have to have another section in your nuget.config file that give you access to push files. This is the ef’d up thing, it is often the exact same credentials, but just in a different place.

RECOMMENDATION: You should create a different account that has is very generic to create API access. This will mitigate the issue of a developer leaving the team that has all the tokens under their account for push access.

GitHub Token

In order to get the proper credentials to use for push (uploading) the nuget package, you should log in as your generic (DevOps) account in GitHub if you have one. If not, use your current account. MAKE SURE YOU GO INTO THE “Settings” FROM YOUR ACCOUNT ICON IN THE UPPER RIGHT CORNER and not the “Settings” on the account or project menu.

Once you’re in there, click “Personal access tokens” and click “Generate new token”.

Give your new token a name, select the expiration days, I suggest 90, but “No expiration” is your decision.

Select the following options:

  • workflow
  • write:packages
  • read:packages
  • delete:packages
  • admin:org
  • admin:write:org
  • admin:read:org
  • user:user:email

Make sure you copy and SAVE the token, because you will never be able to see it again!

You can encode the password that needs access to push the NuGet package with the following command. Please note that if you don’t put the -ConfigFile entry, then it will update the version of the NutGet.config file in the C:\users folder and NOT the version in your project config. This causes the issue were it works when you do it, but all downstream deployments fail, i.e.: Jenkins, Azure etc.

The command to add this to your project nuget.confg file is:

nuget setApiKey ghp_{theapikeyprovidedbyGitHub} -source https://nuget.pkg.github.com/YTGI/index.json -ConfigFile nuget.config

I’m going to repeat that you must notice the -Configfile param. If you don’t add it, the command will update the nuget.config in our current user \roaming\nuget folder, which is not what you want if this project is being deployed from a different device, i.e. Jenkins or Azure.

GitHub NuGet Push

The PUSH process is the following:

nuget push %WORKSPACE%\nupkgs*.nupkg -ConfigFile "{yourprojectfolder}\nuget.config" -src https://nuget.pkg.github.com/{yourgithuborgname}/index.json -SkipDuplicate

Notice the -SkipDuplicate argument in the above CLI command. It will cause the push (upload) command to ignore the fact that you’re trying to upload a duplicate version instead of raising an error that will fail a build. Just keep in mind that if you forget to change your version in the csproj file, your change will not show up. It is against convention to make changes to an existing version, as that could cause real problems for consuming applications. If you made a mistake, or left something out and you want to get rid of the version you just built, you’ll need to go into GitHub packages, Versions and delete the version you just built to upload it again with the same version number.

If this command works, then you have setup your nuget.config file correctly and you’re good to go.

NOTE: It will sometimes take up to a minute or so for the package to show up in the GitHub Packages list, so be patient and don’t assume it didn’t work until you give it some time.