Daily Archives: May 8, 2021
C# || How To Convert A String To Byte Array & Byte Array To String Using C#
The following is a module with functions which demonstrates how to convert a string to a byte array and a byte array to a string using C#.
1. String To Byte Array
The example below demonstrates the use of ‘Utils.Extensions.GetBytes‘ to convert a string to a byte array. The optional parameter allows to specify the encoding.
1 2 3 4 5 6 7 8 |
// String To Byte Array using Utils; var text = $"My Programming Notes!"; var bytes = text.GetBytes(); // Do something with the byte array |
2. Byte Array To String
The example below demonstrates the use of ‘Utils.Extensions.GetString‘ to convert a byte array to a string. The optional parameter allows to specify the encoding.
1 2 3 4 5 6 7 8 9 |
// Byte Array To String using Utils; var text = $"My Programming Notes!"; var bytes = text.GetBytes(); var str = bytes.GetString(); // Do something with the string |
3. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 8, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Extensions { /// <summary> /// Decodes all bytes in the specified byte array into a string /// </summary> /// <param name="bytes">The byte array containing the sequence of bytes to decode</param> /// <param name="encode">The type of encoding to be used. Default is UTF8Encoding</param> /// <returns> A byte array containing the results of encoding</returns> public static string GetString(this byte[] bytes, System.Text.Encoding encode = null) { if (encode == null) { encode = new System.Text.UTF8Encoding(); } return encode.GetString(bytes); } /// <summary> /// Encodes the characters in the specified string into a sequence of bytes /// </summary> /// <param name="str">The string containing the characters to encode</param> /// <param name="encode">The type of encoding to be used. Default is UTF8Encoding</param> /// <returns> A byte array containing the results of encoding</returns> public static byte[] GetBytes(this string str, System.Text.Encoding encode = null) { if (encode == null) { encode = new System.Text.UTF8Encoding(); } return encode.GetBytes(str); } } }// http://programmingnotes.org/ |
4. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 8, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using Utils; public class Program { static void Main(string[] args) { try { var text = $"My Programming Notes!"; var bytes = text.GetBytes(); var str = bytes.GetString(); Display(str); Display($"{str == text}"); } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C# || How To Save, Open & Read File As A Byte Array & Memory Stream Using C#
The following is a module with functions which demonstrates how to save, open and read a file as a byte array and memory stream using C#.
1. Read File – Byte Array
The example below demonstrates the use of ‘Utils.Methods.ReadFile‘ to read a file as a byte array.
1 2 3 4 5 6 |
// Byte Array var path = $@"path-to-file\file.extension"; var fileByteArray = Utils.Methods.ReadFile(path); // Do something with the byte array |
2. Read File – Memory Stream
The example below demonstrates the use of ‘Utils.Methods.ReadFile‘ to read a file as a memory stream.
1 2 3 4 5 6 |
// Memory Stream var path = $@"path-to-file\file.extension"; using (var fileMS = new System.IO.MemoryStream(Utils.Methods.ReadFile(path))) { // Do something with the stream } |
3. Save File – Byte Array
The example below demonstrates the use of ‘Utils.Methods.SaveFile‘ to save the contents of a byte array to a file.
1 2 3 4 5 6 |
// Byte Array var path = $@"path-to-file\file.extension"; byte[] bytes; Utils.Methods.SaveFile(path, bytes); |
4. Save File – Memory Stream
The example below demonstrates the use of ‘Utils.Methods.SaveFile‘ to save the contents of a memory stream to a file.
1 2 3 4 5 6 |
// Memory Stream var path = $@"path-to-file\file.extension"; System.IO.MemoryStream fileMS; Utils.Methods.SaveFile(path, fileMS.ToArray()); |
5. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 8, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Methods { /// <summary> /// Reads a file at the given path into a byte array /// </summary> /// <param name="filePath">The path of the file to be read</param> /// <param name="shareOption">Determines how the file will be shared by processes</param> /// <returns>The contents of the file as a byte array</returns> public static byte[] ReadFile(string filePath, System.IO.FileShare shareOption = System.IO.FileShare.None) { byte[] fileBytes; using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, shareOption)) { fileBytes = new byte[fs.Length]; fs.Read(fileBytes, 0, fileBytes.Length); } return fileBytes; } /// <summary> /// Saves a file at the given path with the contents of the byte array /// </summary> /// <param name="filePath">The path of the file to be saved</param> /// <param name="fileBytes">The byte array containing the file contents</param> /// <param name="shareOption">Determines how the file will be shared by processes</param> public static void SaveFile(string filePath, byte[] fileBytes, System.IO.FileShare shareOption = System.IO.FileShare.None) { using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, shareOption)) { fs.Write(fileBytes, 0, fileBytes.Length); } } } }// http://programmingnotes.org/ |
6. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 8, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; public class Program { static void Main(string[] args) { try { var path = $@"path-to-file\file.extension"; var fileByteArray = Utils.Methods.ReadFile(path); Utils.Methods.SaveFile(path, fileByteArray); } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C# || How To Validate An Email Address Using C#
The following is a module with functions which demonstrates how to determine if an email address is valid using C#.
This function is based on RFC2821 and RFC2822 to determine the validity of an email address.
1. Validate Email – Basic Usage
The example below demonstrates the use of ‘Utils.Email.IsValid‘ to determine if an email address is valid.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
// Validate Email var addresses = new List<string>() { "\"much.more unusual\"@example.com", "<< admin@mailserver1 >>", "user@com", "A@b@[email protected]" }; foreach (var email in addresses) { Console.WriteLine($"Email: {email}, Is Valid: {Utils.Email.IsValid(email)}"); } // expected output: /* Email: [email protected], Is Valid: True Email: [email protected], Is Valid: True Email: [email protected], Is Valid: False Email: name@[email protected], Is Valid: False Email: [email protected], Is Valid: True Email: [email protected], Is Valid: True Email: [email protected], Is Valid: True Email: [email protected], Is Valid: True Email: [email protected], Is Valid: True Email: [email protected], Is Valid: True Email: "much.more unusual"@example.com, Is Valid: False Email: "[email protected]"@example.com, Is Valid: False Email: << [email protected] >>, Is Valid: False Email: << admin@mailserver1 >>, Is Valid: False Email: << #!$%&\'*+-/=?^_`{}|[email protected] >>, Is Valid: False Email: [email protected], Is Valid: True Email: user@com, Is Valid: False Email: [email protected], Is Valid: False Email: [email protected], Is Valid: False Email: A@b@[email protected], Is Valid: False */ |
2. Validate Email – Additional Options
The example below demonstrates the use of ‘Utils.Email.IsValid‘ to determine if an email address is valid with additional validation options.
Supplying options to verify an email address uses the default validity rules, in addition to the provided validation options.
This allows you to add custom rules to determine if an email is valid or not. For example, the misspelling of common email domains, or known spam domains.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
// Verify Email Using Default Rules With Additional Options var addresses = new List<string>() { }; // Additional options var options = new Utils.Email.Options() { InvalidDomains = new[] { // IEnumerable of invalid domains. Example: gmail.com "aichyna.com", "gawab.com", "gold2world.biz", "front14.org", "bumpymail.com", "pleasantphoto.com", "spam.la" }, InvalidTopLevelDomains = new string[] { // IEnumerable of invalid top level domains. Example: .com "comm", "nett", "c0m" }, InvalidSecondLevelDomains = new List<string>() { // IEnumerable of invalid second level domains. Example: gmail "yah00", "ynail" } }; foreach (var email in addresses) { Console.WriteLine($"Email: {email}, Is Valid: {Utils.Email.IsValid(email, options)}"); } // expected output: /* Email: [email protected], Is Valid: False Email: [email protected], Is Valid: False Email: [email protected], Is Valid: False Email: [email protected], Is Valid: True Email: [email protected], Is Valid: False */ |
3. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 8, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Linq; using System.Collections.Generic; namespace Utils { public static class Email { /// <summary> /// Based on RFC2821 and RFC2822 to determine the validity of an /// email address /// </summary> /// <param name="emailAddress">The email address to verify</param> /// <param name="options">Additional email restrictions</param> /// <returns>True if the email address is valid, false otherwise</returns> public static bool IsValid(string emailAddress, Email.Options options = null) { if (string.IsNullOrWhiteSpace(emailAddress) || emailAddress.Length > 100) { return false; } var optionsPattern = options == null ? string.Empty : options.Pattern; // https://www.jochentopf.com/email/characters-in-email-addresses.pdf var pattern = "^[^a-zA-Z0-9]|[^a-zA-Z0-9]$" + // First and last characters should be between a-z, A-Z, or 0-9. @"|[\000-\052]|[\074-\077]" + // Invalid characers between oct 000-052, and oct 074-077. "|^((?!@).)*$" + // Must contain an '@' character. "|(@.*){2}" + // Must not contain more than one '@' character. "|@[^.]*$" + // Must contain at least one '.' character after the '@' character. "|~" + // Invalid '~' character. @"|\.@" + // First character before the '@' must not be '.' character. @"|@\." + // First character after the '@' must not be '.' character. @"|;|:|,|\^|\[|\]|\\|\{|\}|`|\t" + // Must not contain various invalid characters. @"|[\177-\377]" + // Invalid characers between oct 177-377. @"|\/|\.\.|^\.|\.$|@@"; // Must not contain ' / ', '..', '@@' or end with '.' character. pattern += string.IsNullOrWhiteSpace(optionsPattern) ? string.Empty : $"|{optionsPattern}"; var regex = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); var match = regex.Match(emailAddress); if (match.Success) { //System.Diagnostics.Debug.Print("Email address '" + emailAddress + "' contains invalid char/string '" + match.Value + "'."); return false; } return true; } public class Options { private Dictionary<string, object> data { get; set; } = new Dictionary<string, object>(); public Options() { var properties = new string[] { nameof(InvalidDomains), nameof(InvalidTopLevelDomains), nameof(InvalidSecondLevelDomains), nameof(Pattern) }; foreach (var prop in properties) { data.Add(prop, null); } } /// <summary> /// Invalid domains. Example: gmail.com /// </summary> public IEnumerable<string> InvalidDomains { get { return GetData<IEnumerable<string>>(nameof(InvalidDomains)); } set { SetData(nameof(InvalidDomains), value); ResetPattern(); } } /// <summary> /// Invalid top level domains. Example: .com /// </summary> public IEnumerable<string> InvalidTopLevelDomains { get { return GetData<IEnumerable<string>>(nameof(InvalidTopLevelDomains)); } set { SetData(nameof(InvalidTopLevelDomains), value); ResetPattern(); } } /// <summary> /// Invalid second level domains. Example: gmail /// </summary> public IEnumerable<string> InvalidSecondLevelDomains { get { return GetData<IEnumerable<string>>(nameof(InvalidSecondLevelDomains)); } set { SetData(nameof(InvalidSecondLevelDomains), value); ResetPattern(); } } public string Pattern { get { if (GetData<object>(nameof(Pattern)) == null) { var options = new List<string>(); if (InvalidTopLevelDomains != null) { options.AddRange(InvalidTopLevelDomains.Select(domain => FormatTld(domain))); } if (InvalidSecondLevelDomains != null) { options.AddRange(InvalidSecondLevelDomains.Select(domain => FormatSld(domain))); } if (InvalidDomains != null) { options.AddRange(InvalidDomains.Select(domain => FormatDomain(domain))); } SetData(nameof(Pattern), string.Join("|", options)); } return GetData<string>(nameof(Pattern)); } } private T GetData<T>(string key) { return (T)data[key]; } private void SetData(string key, object value) { data[key] = value; } private void ResetPattern() { SetData(nameof(Pattern), null); } private string FormatTld(string domain) { if (string.IsNullOrWhiteSpace(domain)) { return domain; } return AddPeriodSlash(AddPeriod(AddDollar(domain))); } private string FormatSld(string domain) { if (string.IsNullOrWhiteSpace(domain)) { return domain; } return AddAt(domain); } private string FormatDomain(string domain) { if (string.IsNullOrWhiteSpace(domain)) { return domain; } return AddPeriodSlash(AddAt(domain)); } private string AddDollar(string domain) { if (!domain.EndsWith("$")) { domain = $"{domain}$"; } return domain; } private string AddAt(string domain) { if (!domain.StartsWith("@")) { domain = $"@{domain}"; } return domain; } private string AddPeriod(string domain) { if (!domain.StartsWith(".")) { domain = $".{domain}"; } return domain; } private string AddPeriodSlash(string domain) { var index = domain.LastIndexOf("."); if (index > -1) { domain = domain.Insert(index, @"\"); } return domain; } } } }// http://programmingnotes.org/ |
4. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 8, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using System.Collections.Generic; public class Program { static void Main(string[] args) { try { // Verify email var addresses = new List<string>() { "\"much.more unusual\"@example.com", "<< admin@mailserver1 >>", "user@com", "A@b@[email protected]" }; foreach (var email in addresses) { Display($"Email: {email}, Is Valid: {Utils.Email.IsValid(email)}"); } Display(""); // Verify email using the default rules with additional options var addresses2 = new List<string>() { }; // Additional options var options = new Utils.Email.Options() { InvalidDomains = new[] { // IEnumerable of invalid domains. Example: gmail.com "aichyna.com", "gawab.com", "gold2world.biz", "front14.org", "bumpymail.com", "pleasantphoto.com", "spam.la" }, InvalidTopLevelDomains = new string[] { // IEnumerable of invalid top level domains. Example: .com "comm", "nett", "c0m" }, InvalidSecondLevelDomains = new List<string>() { // IEnumerable of invalid second level domains. Example: gmail "yah00", "ynail" } }; foreach (var email in addresses2) { Display($"Email: {email}, Is Valid: {Utils.Email.IsValid(email, options)}"); } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C# || How To Validate A Phone Number Using C#
The following is a module with functions which demonstrates how to validate a phone number using C#.
Not only does this function check formatting, but follows NANP numbering rules by ensuring that the first digit in the area code and the first digit in the second section are 2-9.
1. Validate Phone Number
The example below demonstrates the use of ‘Utils.Methods.IsValidPhoneNumber‘ to determine if a phone number is valid.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
// Validate Phone Number var numbers = new List<string>() { "(123) 456-7890", "(123)456-7890", "123-456-7890", "123.456.7890", "1234567890", "+31636363634", "075-63546725", "(657) 278-2011", "(657)278-2011", "(657)2782011", "6572782011", "+6572782011", "657-278-2011", "657 278 2011", "657.278.2011", "1657.278.2011", "+6572782011", "16572782011", "657-2782011" }; // Display results foreach (var number in numbers) { Console.WriteLine($"Number: {number}, Is Valid: {Utils.Methods.IsValidPhoneNumber(number)}"); } // expected output: /* Number: (123) 456-7890, Is Valid: False Number: (123)456-7890, Is Valid: False Number: 123-456-7890, Is Valid: False Number: 123.456.7890, Is Valid: False Number: 1234567890, Is Valid: False Number: +31636363634, Is Valid: False Number: 075-63546725, Is Valid: False Number: (657) 278-2011, Is Valid: True Number: (657)278-2011, Is Valid: True Number: (657)2782011, Is Valid: True Number: 6572782011, Is Valid: True Number: +6572782011, Is Valid: True Number: 657-278-2011, Is Valid: True Number: 657 278 2011, Is Valid: True Number: 657.278.2011, Is Valid: True Number: 1657.278.2011, Is Valid: True Number: +6572782011, Is Valid: True Number: 16572782011, Is Valid: True Number: 657-2782011, Is Valid: True */ |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 8, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Methods { /// <summary> /// Not only checks formatting, but follows NANP numbering rules /// by ensuring that the first digit in the area code and the first /// digit in the second section are 2-9. /// </summary> /// <param name="phoneNumber">The phone number to verify</param> /// <returns>True if the phone number is valid, false otherwise</returns> public static bool IsValidPhoneNumber(string phoneNumber) { if (string.IsNullOrWhiteSpace(phoneNumber)) { return false; } var pattern = @"^[\+]?[{1}]?[(]?[2-9]\d{2}[)]?[-\s\.]?[2-9]\d{2}[-\s\.]?[0-9]{4}$"; var options = System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase; return System.Text.RegularExpressions.Regex.IsMatch(phoneNumber, pattern, options); } } }// http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 8, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using System.Collections.Generic; public class Program { static void Main(string[] args) { try { var numbers = new List<string>() { "(123) 456-7890", "(123)456-7890", "123-456-7890", "123.456.7890", "1234567890", "+31636363634", "075-63546725", "(657) 278-2011", "(657)278-2011", "(657)2782011", "6572782011", "+6572782011", "657-278-2011", "657 278 2011", "657.278.2011", "1657.278.2011", "+6572782011", "16572782011", "657-2782011" }; foreach (var number in numbers) { Display($"Number: {number}, Is Valid: {Utils.Methods.IsValidPhoneNumber(number)}"); } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.