5 extensions for the .NET ecosystem

Table of Contents

These are 5 extensions that we all should normally have in our projects, especially when we work on projects that will evolve over time. We use these extensions internally and normally reuse them in almost all projects.

I have many extensions and helpers that I could share, even from well-known libraries, and I know that you can help many of you in their day to day, if they haven’t already been added. For the moment I will be sharing these, and depending on the support I will be sharing others.

Stay tuned at @luismatosluna

Extensions

DateTimeToString

This time, I bring you two (2) extensions instead of one (1).

The first extension converts a DateTime data type to text, but mentions of how long (days, months, years) the date has been in relation to the current date. This extension is especially useful when working with a news feed or a list of articles, and you want to show the user when the article was published.

...
        public static string DateTimeToString(this DateTime value)
        {
            if (value == null)
                return string.Empty;

            if (value.Date == DateTime.Now.Date)
                return "Today";

            var numDays = (DateTime.Now.Date - value.Date).Days;
            if (numDays > 0 && numDays < 8)
            {
                if (numDays == 1)
                    return "Yesterday";
                else
                    return value.DayOfWeek.ToString();
            }

            if (numDays > 8 && numDays < 30)
            {
                return "One month ago";
            }


            if (numDays < 365)
            {
                return numDays + " days ago";
            }
            else
            {
                int years = numDays / 365;
                return (years == 1)? years + " year ago" : years + " years ago";
            }
        }
...

// USE:
var date = new DateTime(2020, 5, 1, 8, 30, 52);
Console.WriteLine(date.DateTimeToString());

// OUTPUT:
2 years ago

The second extension is very similar to the first, but in this case it only returns in text if it was ‘Today’ or ‘Yesterday’, otherwise it will return the date in text. This extension is often used in the same way in news feeds, but it is a bit more simple, defined and minimalist for the end user.

...
        public static string DateTimeToString2(this DateTime value)
        {
            if (value == null)
                return string.Empty;

            if (value.Date == DateTime.Now.Date)
                return "Today";

            var numDays = (DateTime.Now.Date - value.Date).Days;
            if (numDays > 0 && numDays < 8)
            {
                if (numDays == 1)
                    return "Yesterday";
                else
                    return value.DayOfWeek.ToString();
            }

            return value.ToString("MMM dd, yyyy").ToUpper();
        }
...

// USE:
var date = new DateTime(2020, 5, 1, 8, 30, 52);
Console.WriteLine(date.DateTimeToString2());

// OUTPUT:
MAY 1, 2020

JustNumberFormat

This extension is very simple yet powerful. With this extension, you remove all characters from a text string that are not numeric. Very useful for when you want to get the phone number clean of characters, for example.

...
        public static string JustNumberFormat(this string value)
        {
            return string.Join("", value.ToCharArray().Where(Char.IsDigit));
        }
...

// USE:
string phone = "+1 (712) 412-5236";
Console.WriteLine(phone.JustNumberFormat());

// OUTPUT:
17124125236

ValidateEmail

You are probably using a library or have your own library to validate emails, but if it is true, doing it with an extension is much cleaner. With this extension, you can validate emails in a simple and easy way.

...
    public static bool ValidateEmail(this string value)
    {
            if (value == null)
            {
                return false;
            }

            if (!(value is string valueAsString))
            {
                return false;
            }

            // only return true if there is only 1 '@' character
            // and it is neither the first nor the last character
            int index = valueAsString.IndexOf('@');

            return
                index > 0 &&
                index != valueAsString.Length - 1 &&
                index == valueAsString.LastIndexOf('@');
    }
...

// USE:
string email1= "myemail.com";
Console.WriteLine(email1.ValidateEmail());

string email2= "myemail@server.com";
Console.WriteLine(email2.ValidateEmail());

// OUTPUT:
false
true

RunSafe

This extension is wonderful. When you need to run a task safely, you can do it with this extension and let you write your try {} catch {} blocks.

...
	public static async Task RunSafe(this Task task, Action<Exception> onError = null, CancellationToken token = default(CancellationToken))
	{
		Exception exception = null;

		try
		{
			if (!token.IsCancellationRequested)
			{
				await Task.Run(() => {
					task.Start();
					task.Wait();
				});
			}
		}
		catch (TaskCanceledException)
		{
			Console.WriteLine("Task Cancelled"); 
		}
		catch (AggregateException e)
		{
			var ex = e.InnerException;
			while (ex.InnerException != null)
				ex = ex.InnerException;
				exception = ex;
		}
		catch (Exception e)
		{
			exception = e;
		}
		finally
		{
			//AfterTaskRun?.Invoke(null, task);
		}

		if (exception != null)
		{
			//TODO: Log to Insights
			Console.WriteLine(exception); 
			onError?.Invoke(exception);
		}
	}
...

// USE:
var task = new Task(() => { Console.WriteLine("Hi!"); });
await task.RunSafe(() => Console.WriteLine("An error occured!"));

// OUTPUT:
Hi!

Conclusion

I hope you find these extensions useful. And also, why not, share your extensions on the networks. You can tag me at @luismatosluna on Twitter.

If this article has a lot of support, I’ll be sharing some Xamarin.Forms extensions, .NET MAUI extensions, and much more. See you next time.

Share this content!

Facebook
Twitter
LinkedIn
Telegram
WhatsApp