Coding Faster With The dotNetTips Utility - November 2020 Update

My goal is to release quarterly updates to my NuGet packages and source code. This November 2020 update includes code I moved some code from my CLR open-source projects. It also includes over 28 new methods and types along with more unit testing and more benchmark tests. Below, I have documented some of the new methods along with a new type and some older methods too.

Calculating Total Size of Files in a Directory

 
The DirectoryInfo type in .NET does not have a method to return the total size of the files underneath that directory, so I added an extension method called GetSize(). I need this for some upcoming changes I need to do to my free app for .NET developers. Here is how to use it.
  1. var directory = new DirectoryInfo(Environment.GetFolderPath(  
  2.                                   Environment.SpecialFolder.Cookies));  
  3. var result = directory.GetSize(searchPattern: "*.cookie",   
  4.                                searchOPtion: SearchOption.AllDirectories);  

Checking that the User is an Administrator

 
In my free app for software engineers, I check to see if the user is running the app using admin rights, I use App.IsUserAdministrator(). In this app, I warn the user that the app will work better running under admin rights. Here is how I do that in the app.
  1. if (App.IsUserAdministrator() == false)  
  2. {   
  3.     this.WriteUserMessage(new DevMessage { Message =   
  4.                           Resources.UserMessageCouldNotRunAsAdmin,   
  5.                           Type = MessageType.Important });  
  6. }  

Checking to See if the Current Process is Already Running

 
Since C# apps do not have an easy way to prevent two instances of the same app from running (like VB.NET projects do) I needed that check for my free app for software engineers. So I use App.IsRunning(). In my app, if the app is already running, I just shut down the app that is loading by using App.Kill().
 
Based on my benchmark testing, App.IsRunning() has a performance mean of 377,618.047 ns.
 

Checking to See if a Process is Running

 
In my free app for software engineers, when the app starts, I check to see if Visual Studio is running and if it is, I warn the user that they should close it before using the app. I use the App.IsProcessRunning() method as shown below.
  1. App.IsProcessRunning("devenv");  
Based on my benchmark testing, this method has a performance mean of 220,639.168 ns.
 

Copying a File Asynchronously

 
The File type in .NET does not support any async methods. So, I created FileHelper.CopyFileAysnc() that uses the async methods from FileStream. Here is an example on how to use it.
  1. var result = await FileHelper.CopyFileAsync(file: fileToCopy, destinationFolder: this._tempPath)  
  2. .ConfigureAwait(true);  
CopyFileAysnc() returns the file size as a long.
 

Downloading File from Web Asynchronously

 
If you need to download a file from the web asynchronously, then you can use FileHelper.DownloadFileFromWebAsysc() that will store it in a file location of your choice. Here is an example of how to use it.
  1. var fileToDownload = @"https://dotnettips.com/dotnettips.png";  
  2. await FileHelper.DownloadFileFromWebAsync(new Uri(fileToDownload),   
  3.   Path.Combine(this._tempPath.FullName, "dotNetTips.Com.logo.png"));  

Ensuring a Host is Available

 
One of the things I mention in my Defensive Programming book and conference session is to periodically check to ensure that a host, such as www.google.com, is available before sending a request. If the host is unavailable, it can cause exceptions in the application. This also allows you to disable buttons in the click such as “Send” until the host is available again. I have been coding like this since the very early days of .NET.
 
I created a method called NetworkHelper.IsHostAvailable() to ping the host. Here is an example on how you can use it to check Google.
  1. var result = NetworkHelper.IsHostAvailable("www.google.com", timeout: 500);  
  2. var result = NetworkHelper.IsHostAvailable("8.8.4.4", timeout: 500);  
In my unit test, using IsHostAvaialble() to check www.googe.com took around 70 milliseconds.
 

New String Extensions

 
Here are more string extensions that I’ve added in this release.
  • FromBase64(): Converts a Base64 string to string.
  • Extract(): Extracts a string from a beginning and end value.
  • ToTitleCase(): Converts a string to title case (capitalize the first letter of each word).
  • Parse<T>(): Parses a string to a type.
  • ToBase64(): Converts a string to a Base64 string.
  • ComputeHash(): Computes a hash from a string value. Formats supported are: HMAC, MACMD5, HMACSHA1, HMACSHA256, HMACSHA384, HMACSHA512, MD5, SHA1, SHA256, SHA384 and SHA512. Based on my benchmark testing, using SHA256 with this method has a performance mean of 11,159.774 ns.

Retrieving Computer Information

 
For information that I use to log issues or information, I created a type called ComputerInfo() that returns common information. Here is just some of the information from my system.
  1. ComputerCulture:eng,  
  2. ComputerUICulture:eng  
  3. FrameworkDescription:.NET Core3.1.9  
  4. FrameworkVersion:{_Build:9,_Major:3,_Minor:1,_Revision:-1}  
  5. HasShutdownStarted:false,  
  6. IPAddress:123.456.7.8  
  7. Is64BitOperatingSystem:true  
  8. Is64BitProcess:true  
  9. IsUserInteractive:true  
  10. LogicalDrives:[C:\\]  
  11. MachineName:DESKTOP-ABCDEF,  
  12. OSDescription:Microsoft Windows 10.0.19041  
  13. OsMemoryPageSize:4096  
  14. PhysicalMemoryInUse:49057792  
  15. ProcessorCount:4,  
  16. SystemDirectory:C:\\WINDOWS\\system32,  
  17. UserDomainName:DESKTOP- AA2FHJ  
  18. UserName:david  

Retrieving Environment Variables

 
The values in the Windows environment variables can be very useful to retrieve information about the user and system.You can use App.GetEnviromentVariables() to retrieve this information. Below is an example of just some of the data from my system.
  1. USERPROFILE:C:\Users\david  
  2. USERNAME:david  
  3. CommonProgramFiles:C:\Program Files\Common Files  
  4. USERDOMAIN:DESKTOP-ABCDEF  
  5. PROCESSOR_REVISION:8e09  
  6. ProgramFiles(x86):C:\Program Files (x86)  
  7. VisualStudioEdition:Microsoft Visual Studio Enterprise 2019  
  8. SystemDrive:C:  
  9. VSLS_SESSION_KEEPALIVE_INTERVAL:0  
  10. SESSIONNAME:Console  
  11. USERDOMAIN_ROAMINGPROFILE:DESKTOP-C22DAVET  
  12. CommonProgramFiles(x86):C:\Program Files (x86)\Common Files  
  13. ALLUSERSPROFILE:C:\ProgramData  
  14. HOMEDRIVE:C:  
  15. COMPUTERNAME:DESKTOP-ABCDEF  
  16. PUBLIC:C:\Users\Public  
  17. VSAPPIDNAME:devenv.exe  
  18. ProgramFiles:C:\Program Files  
  19. PROCESSOR_ARCHITECTURE:AMD64  
  20. windir:C:\WINDOWS  
  21. NUMBER_OF_PROCESSORS:4  
  22. ProgramData:C:\ProgramData  
  23. TMP:C:\Users\david\AppData\Local\Temp  
  24. TEMP:C:\Users\david\AppData\Local\Temp  
  25. VisualStudioDir:C:\Users\david\Documents\Visual Studio 2019  
  26. HOMEPATH:\Users\david  
  27. OS:Windows_NT  
  28. LOCALAPPDATA:C:\Users\david\AppData\Local  
  29. APPDATA:C:\Users\david\AppData\Roaming  
  30. VisualStudioVersion:16.0  
  31. SystemRoot:C:\WINDOWS  
  32. PROCESSOR_IDENTIFIER:Intel64 Family 6 Model 142 Stepping 9, GenuineIntel  

Retrieving the .NET Framework Description

 
When you are logging information when an exception is thrown, it might be useful to log the .NET Framework description that the app is running under. To do this, you can use App.FrameworkDescripion. Here is an example of the output.
 
.NET Core 3.1.9
 

Retrieving Application Executing Folder

 
If you need to retrieve the location of where the current executable is running from you can use App.ExecutingFolder(). This is an example of the result from my unit test project.
 
C:\\src\\GitHub\\dotNetTips.Utility.Core\\src\\Unit Tests\\dotNetTips.Utility.Standard.Tests\\bin\\Debug\\netcoreapp3.1
 

Retrieving Application Information

 
To easily retrieve common application information, you can use App.AppInfo(). It’s very simple to use.
  1. var info = App.AppInfo;  
Here is an example of the results from my unit tests.
 
Coding Faster With The dotNetTips Utility
 

Retrieving & Changing Culture

 
When .NET or you need to know the current culture and localization information to format data based on the users' location, that is all held in the CultureInfo type. To make retrieving this information you can use App.CurrentCulture() or App.CurrentUICulture(). Below is an example of just some of the information for CurrentCulture.
 
Coding Faster With The dotNetTips Utility
 
Once when working on a project, one of the requirements was that the user could on-the-fly change the culture that the current thread is running under. If you need to change the culture, you can do it using the methods below.
  1. App.ChangeCulture("aa");  
  2. App.ChangeUICulture("af");  

Using Common Control Characters

 
When creating or checking stings, there are a lot of common control characters that we use. To make using them easier, I created a static class called ControlChars. Here are its current values.
  1. At = '@'  
  2. Back = '\b'  
  3. Backslash = '\\'  
  4. Colon = ':'  
  5. Comma = ','  
  6. Cr = '\r'  
  7. CR = '\r'  
  8. CRLF = "\r\n"  
  9. Dot = '.'  
  10. DoubleQuote = "''"  
  11. EndAngleBracket = '>'  
  12. EndComment = ')'  
  13. EndSquareBracket = ']'  
  14. FormFeed = '\f'  
  15. ForwardSlash = '/'  
  16. LF = '\n'  
  17. NewLine = "\r\n"  
  18. NullChar = '\0'  
  19. Quote = '\"'  
  20. SingleQuote = '\''  
  21. Space = ' '  
  22. StartAngleBracket = '<'  
  23. StartComment = '('  
  24. StartSquareBracket = '['  
  25. Tab = '\t'  
  26. Underscore = '_'  
  27. VerticalTab = '\v'  
Since all these values is a constant, it could improve performance.
 

Temporary File Manager

 
Many apps, client and server, need to create temporary files to process data but far too many apps, even Visual Studio, do not clean up all the files they generated. So, to make creating these files easy and maintain those files, I created the TempFileManager type in the dotNetTips.Utility.Core.Windows NuGet package! I created this class a long time ago for a project written in the .NET Framework (Clr) and now I have moved it to .NET Core and made some enhancements. Below are examples of how to use it.
 

Creating a Temporary File

 
Creating a single temporary file is easy. Below is an example,
  1. using (var tfm = new TempFileManager())  
  2. {  
  3.     var cachefile = tfm.CreateFile();  
  4.   
  5.     //Process file code  
  6. }  
TempFileManager implements IDisposable to ensure the files are deleted when not in use anymore. So, make sure to always use the using statement.
 

Creating Multiple Temporary Files

 
Creating multiple files at the same time is easy too.
  1. using (var tfm = new TempFileManager())  
  2. {  
  3.     var result = tfm.CreateFiles(10);  
  4.   
  5.     foreach (var file in result)  
  6.     {  
  7.         // Process file  
  8.     }  
  9.  }  
All the temporary files are creating in the C:\Users\<current user>\AppData\Local\Temp folder as shown below.
 
Coding Faster With The dotNetTips Utility
 

Other Useful Methods

 
Here are the other methods in the class.
  • DeleteAllFiles(): Deletes the files being tracked and their names are removed from the list.
  • DeleteFile(): Deletes a single file and removes it from the list.
  • FilesList(): Returns a list of all the files being tracked.
If you find TempFileManager useful, please let me know if there is anything, I can add to make it more useful to you.
 

Summary

 
There are other minor changes to this release too including more unit tests and more benchmarking tests. 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 for these open-source projects!


Recommended Free Ebook
Similar Articles
McCarter Consulting
Software architecture, code & app performance, code quality, Microsoft .NET & mentoring. Available!