Coding Faster With The dotNetTips Utility - September 2020 Update

After the last quarterly release of my open-source projects and NuGet packages, I’ve added more methods for my projects, and ones for use where I work. I’ve decided to release a min-quarter version (2020.9.20.01) so my team at work can use them and so I can use them in the app that I’ve released for .NET developers. Below are the links to the source and NuGet packages.

Converting Delimited String to an Array

 
If you have a delimited string that you need to convert to an array, then the extension method is called DelimitedStringToArray() and is easy to use. Just give it a string and the string delimiter (defaults to a comma) and it will return the array as shown below.
  1. var inputString = "Microsoft .NET, Visual Studio, Azure";  
  2. var result = inputString.DelimitedStringToArray();  
Output
 
Here is the result of the code above using DelimitedStringToArray();
 
Coding Faster With The dotNetTips Utility - September 2020 Update
 

Shuffling an Immutable Array

 
I’ve added a few new extension methods called Shuffle<T> to shuffle an IEnumerable<T> or ImmutableArray<T>. Also, IEnumberable<T> .Shuffle is overloaded to return a given number of items instead of the entire collection.
  1. var people = RandomData.GeneratePersonCollection<PersonProper>(10).ToImmutable();  
  2. var shuffledPeople = people.Shuffle();  

Removing Null Items from an Array

 
Usually, when operating over an array, you don’t want to process items that are null especially since that could cause exceptions. To make sure there aren’t any, just use the ClearNulls() extension method.
  1. var people = RandomData.GeneratePersonCollection<PersonProper>(count);  
  2. people.Add(null);  
  3. var result = people.ClearNulls());  

Combining Directory Paths

 
There is already a method available from System.IO.Path called Combine, but I wanted to also add the ability to create the directory at the same time. So I created a method in my PathHelper class called CombinePaths(). This method works exactly like the Path.Combine() one but there is a parameter called createIfNotExists that if set to true will create the path. Instead of returning a string like Path.Combine() does, it returns DirectoryInfo to it makes it easier to perform tasks on the directory.
  1. var basePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);  
  2. var paths = $"{basePath},CombinePaths,Test1,Test2,Test3";  
  3. var tempPath = PathHelper.CombinePaths(createIfNotExists: true,   
  4. paths.DelimitedStringToArray());  
Output
 
Here is the result of CobinePaths() from my unit tests.
 
Coding Faster With The dotNetTips Utility - September 2020 Update
 

ThrowingExceptions the Easy Way

 
While digging around in the .NET Core source code, I saw that in many of the projects, they encapsulated throwing exceptions in a single class. I’ve never seen this done before and after thinking about it, it makes sense. Let's face it, many of the exceptions we throw,use the same error messages over and over again, or not set it at all. In my projects, I usually just put these common messages in the resource file. So all of the methods below in the new ExceptionThrower class have a default message and since it’s in the resource file, it can be translated into different languages.
 
At the same time, I got frustrated with .NET Core since some of the exception types have the message parameter first and others it was the paramName and even some like InvalidOperationException do not have a paramName at all! So, I made sure that all the methods in ExceptionThrower are consistent.
 
All methods are overloaded to accept,
  1. paramName
  2. message &paramName
  3. message &innerException
I have changed many of my open-source assemblies to use the new ExceptionThrower class. Here is an example of how I use it.
  1. if (input == null || input.Length == 0)  
  2. {  
  3.    ExceptionThrower.ThrowArgumentNullException("Input cannot be null or has a   
  4.    length of 0.", nameof(input));  
  5. }  
Complete List of Methods
  • ThrowArgumentException
  • ThrowArgumentInvalidException
  • ThrowArgumentNullException
  • ThrowArgumentOutOfRangeException
  • ThrowArgumentReadOnlyCollectionException
  • ThrowDirectoryNotFoundException
  • ThrowInvalidOperationException
I will add more exceptions to this class as I need or is as requested.
 

Adding a List to a List& Remove Duplicates

 
Usually, when I am writing code and dealing with a collection, I want to make sure that the same item isn’t in the collection twice. For example, if somehow a shopping order gets added to the collection twice it could cause all types of issues, all bad. So for many years, I’ve been using an extension method called AddIfNotExists(). In this version, I’ve added even more methods to make this easier for more types and options.
 
Here is an example on how I use it from the unit tests.
  1. var people = RandomData.GeneratePersonCollection<PersonProper>(20).ToArray();  
  2. var newPeople = RandomData.GeneratePersonCollection<PersonProper>(10).ToArray();  
  3. people = people.AddIfNotExists(newPeople);  
Output
 
Coding Faster With The dotNetTips Utility - September 2020 Update
 

Choosing a Random Item from a Collection

 
The new Shuffle() methods randomize an entire collection but there might be times you just might want one item. So, I created PickRandom<T>, and below is an example of how to use it.
  1. var people = RandomData.GeneratePersonCollection<PersonProper>(10)  
  2. .ToDictionary(p =>p.Id);  
  3. var result = people.PickRandom();  

Downloading a String from an Url

 
If you just need to download a string from a URL endpoint, then you can use WebHelper.DownloadString(). I use it all the time to download JSON from APIs. There is also an async version of this method. It also injects a value into a header called CLIENTID. I believe I added that for a project I was working on a long time ago that I was using to know what app was calling my endpoint. Here is an example of how to use it.
  1. var result = WebHelper.DownloadString(new Uri("https://www.google.com/"),   
  2. clientId: "UNITTEST2");  
Output
 
Here the results if I just call google.com.
 
Coding Faster With The dotNetTips Utility - September 2020 Update
 

Retrieving List of All HTTP Header Names

 
There are many times when I wonder what HTTP header names are available so I can use it or make sure I don’t think of one that already exists. So, I created a new static property in WebHelper called HttpHeaderNames. This could also be used for validation.
  1. var result = WebHelper.HttpHeaderNames;  
Output
 
Below are the HTTP header names as defined in .NET Core.
 
Coding Faster With The dotNetTips Utility - September 2020 Update
 

Safely Converting XML String to XDocument

 
This month, the team I work with and myself have been scrambling to fix current and legacy apps to adhere to the new security standards being imposed by the company we work for. Even though these apps, in production, should already be using proper security, unfortunately, most of them aren’t. One of the violations we are dealing with is XML injection attacks.
 
The security team’ssuggested solution is “Encode user inputs, use DtdProcessing settings to prevent CDATA tag”. Since I hate duplicate code, for my teammates I created a new method in XmlHelper called StringToXDocument(). This method uses the proper settings to prevent XML injection attacks and it’s also overloaded to use anXmlResolver.
 
Below is an example of how to use it.
  1. var result = XmlHelper.StringToXDocument(xml);  
Output
 
Here is an example of the output using the XML Visualizer in Visual Studio.
 
Coding Faster With The dotNetTips Utility - September 2020 Update
 

Randomizing a Collection One Time or Forever

 
Recently, while working on a new version of my dotNetTips Utility Dev App (free for developers), I modified it to retrieve messages that I display where I will be speaking next and more from a project I wrote in Azure. While hooking that up in my client app, I decided to create an easier way to randomly choose items from a collection that can also loop forever. So, I’ve added a new class called CollectionRandomizer<T>.
 
This class requires a collection when initialized. By default, it randomizes the collection and then allows retrieving items until it reaches the end of the list. To retrieve an item out of CollectionRandomizer<T>, just use the GetNext() method. When creating the class you can also set the repeat parameter to true. It will re-randomize the list when it gets to the end of the list and will continue doing this, well forever. This is what works perfectly in my app.
 
This is an example of how to create the type.
  1. private CollectionRandomizer<Ad> _adRandomizer;  
  2. this._adRandomizer = new CollectionRandomizer<Ad>(ads, repeat: true);  
This is how to retrieve an item out of the collection.
  1. var ad = this._adRandomizer?.GetNext();  
To check if there are items still in the collection to process, you can use the HasRemainingItems property.
 
This class has been fully tested, so if you need anything like this, I hope you give it a try. I’d like to thank my teammate Kristine Tran for being my second pair of eyes when writing this code.
 

Summary

 
I hope you will check out these methods or any of the others in the assemblies.If you have any comments or suggestions, please comment below. I’m always looking for new things to these open-source projects!


McCarter Consulting
Software architecture, code & app performance, code quality, Microsoft .NET & mentoring. Available!