Daily Archives: May 12, 2021
C# || How To Append & Join A Date & Time Value Together Using C#
The following is a module with functions which demonstrates how to append and join a date and time value together using C#.
1. Append Date & Time
The example below demonstrates the use of ‘Utils.Extensions.SetTime‘ to append a date and time value together.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Append Date & Time using Utils var dteDate = Convert.ToDateTime("1/27/1991"); var time = Convert.ToDateTime("7:28:33 PM"); Console.WriteLine($"dteDate: {dteDate}"); // Append time to the date var result = dteDate.SetTime(time); Console.WriteLine($"Result: {result}"); // expected output: /* dteDate: 1/27/1991 12:00:00 AM Result: 1/27/1991 7:28:33 PM */ |
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Extensions { /// <summary> /// Appends a date and time value together /// </summary> /// <param name="date">The date portion</param> /// <param name="time">The time portion</param> /// <returns>The appended date and time value</returns> public static DateTime SetTime(this DateTime date, DateTime time) { return date.Date.Add(time.TimeOfDay); } } }// 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 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 dteDate = Convert.ToDateTime("1/27/1991"); var time = Convert.ToDateTime("7:28:33 PM"); Display($"dteDate: {dteDate}"); // Append time to the date var result = dteDate.SetTime(time); Display($"Result: {result}"); } 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 Generate Hourly Time Range With Minute Interval Using C#
The following is a module with functions which demonstrates how to generate an hourly time range with minute interval between a start and end time using C#.
The function demonstrated in this page generates a time value list containing the time from a starting hour to an ending hour, separated by a minute step. The starting and ending hour is an integer from 0 through 23 representing the 24 hour period of the day, and the minute step can be any minute interval, including decimal values.
The starting and ending hours can also be flipped, indicating that the results should be returned in descending order.
An optional parameter also exists which allows to tune the results. When the range is in ascending order, the parameter indicates that the results should exclude/include the entire ending hour. When the range is in descending order, the parameter indicates that the results should exclude/include the entire starting hour.
1. Ascending Time Range – Minute Interval – Default
The example below demonstrates the use of ‘Utils.DateRange.GetTimeRange‘ to get the time range with a minute interval in ascending order.
In this example, the default options are used, which excludes the full ending hour from the results.
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 |
// Ascending Time Range - Minute Interval - Default // Get an hour range from 12AM - 11PM, with a 15 and half minute interval var result = Utils.DateRange.GetTimeRange(0, 23, 15.5); foreach (var value in result) { Console.WriteLine($"Time: {value.Time}, String: {value.ToString()}"); } // expected output: /* Time: 1/1/0001 12:00:00 AM, String: 12:00:00 AM Time: 1/1/0001 12:15:30 AM, String: 12:15:30 AM Time: 1/1/0001 12:31:00 AM, String: 12:31:00 AM Time: 1/1/0001 12:46:30 AM, String: 12:46:30 AM Time: 1/1/0001 1:02:00 AM, String: 1:02:00 AM Time: 1/1/0001 1:17:30 AM, String: 1:17:30 AM Time: 1/1/0001 1:33:00 AM, String: 1:33:00 AM Time: 1/1/0001 1:48:30 AM, String: 1:48:30 AM .... .... .... .... Time: 1/1/0001 9:11:00 PM, String: 9:11:00 PM Time: 1/1/0001 9:26:30 PM, String: 9:26:30 PM Time: 1/1/0001 9:42:00 PM, String: 9:42:00 PM Time: 1/1/0001 9:57:30 PM, String: 9:57:30 PM Time: 1/1/0001 10:13:00 PM, String: 10:13:00 PM Time: 1/1/0001 10:28:30 PM, String: 10:28:30 PM Time: 1/1/0001 10:44:00 PM, String: 10:44:00 PM Time: 1/1/0001 10:59:30 PM, String: 10:59:30 PM */ |
2. Descending Time Range – Hourly Interval – Default
The example below demonstrates the use of ‘Utils.DateRange.GetTimeRange‘ to get the time range with a hourly interval in descending order.
In this example, the default options are used, which excludes the full starting hour from the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Descending Time Range - Hourly Interval - Default // Get an hour range from 10PM - 10AM, with a 2 hour interval var result = Utils.DateRange.GetTimeRange(22, 10, 120); foreach (var value in result) { Console.WriteLine($"Time: {value.Time}, String: {value.ToString(true)}"); } // expected output: /* Time: 1/1/0001 10:00:00 PM, String: 10 PM Time: 1/1/0001 8:00:00 PM, String: 8 PM Time: 1/1/0001 6:00:00 PM, String: 6 PM Time: 1/1/0001 4:00:00 PM, String: 4 PM Time: 1/1/0001 2:00:00 PM, String: 2 PM Time: 1/1/0001 12:00:00 PM, String: 12 PM Time: 1/1/0001 10:00:00 AM, String: 10 AM */ |
3. Ascending Time Range – Minute Interval – Include Full Hour
The example below demonstrates the use of ‘Utils.DateRange.GetTimeRange‘ to get the time range with a minute interval in ascending order.
In this example, the optional parameter is used, which includes the full ending hour from the results.
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 |
// Ascending Time Range - Minute Interval - Include Full Hour // Get an hour range from 12AM - 11PM, with a 15 and half minute interval var result = Utils.DateRange.GetTimeRange(0, 23, 15.5, true); foreach (var value in result) { Console.WriteLine($"Time: {value.Time}, String: {value.ToString()}"); } // expected output: /* Time: 1/1/0001 12:00:00 AM, String: 12:00:00 AM Time: 1/1/0001 12:15:30 AM, String: 12:15:30 AM Time: 1/1/0001 12:31:00 AM, String: 12:31:00 AM Time: 1/1/0001 12:46:30 AM, String: 12:46:30 AM Time: 1/1/0001 1:02:00 AM, String: 1:02:00 AM Time: 1/1/0001 1:17:30 AM, String: 1:17:30 AM Time: 1/1/0001 1:33:00 AM, String: 1:33:00 AM Time: 1/1/0001 1:48:30 AM, String: 1:48:30 AM .... .... .... .... Time: 1/1/0001 10:13:00 PM, String: 10:13:00 PM Time: 1/1/0001 10:28:30 PM, String: 10:28:30 PM Time: 1/1/0001 10:44:00 PM, String: 10:44:00 PM Time: 1/1/0001 10:59:30 PM, String: 10:59:30 PM Time: 1/1/0001 11:15:00 PM, String: 11:15:00 PM Time: 1/1/0001 11:30:30 PM, String: 11:30:30 PM Time: 1/1/0001 11:46:00 PM, String: 11:46:00 PM */ |
4. Descending Time Range – Hourly Interval – Include Full Hour
The example below demonstrates the use of ‘Utils.DateRange.GetTimeRange‘ to get the time range with a hourly interval in descending order.
In this example, the optional parameter is used, which includes the full starting hour from the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Descending Time Range - Hourly Interval - Include Full Hour // Get an hour range from 10PM - 10AM, with a 2 hour interval var result = Utils.DateRange.GetTimeRange(22, 10, 120, true); foreach (var value in result) { Console.WriteLine($"Time: {value.Time}, String: {value.ToString(true)}"); } // expected output: /* Time: 1/1/0001 10:59:00 PM, String: 10:59 PM Time: 1/1/0001 8:59:00 PM, String: 8:59 PM Time: 1/1/0001 6:59:00 PM, String: 6:59 PM Time: 1/1/0001 4:59:00 PM, String: 4:59 PM Time: 1/1/0001 2:59:00 PM, String: 2:59 PM Time: 1/1/0001 12:59:00 PM, String: 12:59 PM Time: 1/1/0001 10:59:00 AM, String: 10:59 AM */ |
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 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 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 class DateRange { public DateTime Time { get; set; } protected bool showSeconds = false; public string ToString(bool condensed = false) { var str = Time.ToShortTimeString(); if (condensed) { str = str.Replace(":00", string.Empty); } else if (showSeconds) { str = Time.ToString("h:mm:ss tt"); } return str; } /// <summary> /// Generates a time value list containing the time from 'Starting Hour' /// to 'Ending Hour' separated by 'Minute Step'. 'Starting Hour' and 'Ending Hour' /// should be an integer from 0 through 23 representing the hour of the day. /// </summary> /// <param name="startingHour">The starting hour from 0 through 23</param> /// <param name="endingHour">The ending hour from 0 through 23</param> /// <param name="minuteStep">The minute step</param> /// <param name="includeFullHour">If going in ascending direction, indicates /// the results should include the entire 'Ending Hour'. If going in descending /// direction, indicates the results should include the entire 'Starting Hour'</param> /// <returns>The time value list from 'Starting Hour' to 'Ending Hour'</returns> public static List<DateRange> GetTimeRange(int startingHour, int endingHour , double minuteStep, bool includeFullHour = false) { var result = new List<DateRange>(); var maxHour = 23; var minHour = 0; var maxMinute = 59; var minMinute = 0; var startingMinute = minMinute; var endingMinute = maxMinute; var showSeconds = (int)minuteStep != minuteStep; if (minuteStep < 0) { minuteStep = 1; } // Flip results if going in opposite direction if (startingHour > endingHour) { minuteStep *= -1; startingMinute = maxMinute; endingMinute = minMinute; startingHour = Math.Min(startingHour, maxHour); endingHour = Math.Max(endingHour, minHour); } else { startingHour = Math.Max(startingHour, minHour); endingHour = Math.Min(endingHour, maxHour); } if (!includeFullHour) { startingMinute = 0; endingMinute = 0; } var today = DateTime.Today; var startTime = today.SetTime(Convert.ToDateTime($"{startingHour.ToString("00")}:{startingMinute.ToString("00")}")); var endTime = today.SetTime(Convert.ToDateTime($"{endingHour.ToString("00")}:{endingMinute.ToString("00")}")); var currentTime = startTime; while (startingHour < endingHour ? currentTime <= endTime : currentTime >= endTime) { result.Add(new DateRange() { Time = new DateTime(1, 1, 1).SetTime(currentTime), showSeconds = showSeconds }); currentTime = currentTime.AddMinutes(minuteStep); } return result; } } public static class Extensions { /// <summary> /// Appends a date and time value together /// </summary> /// <param name="date">The date portion</param> /// <param name="time">The time portion</param> /// <returns>The appended date and time value</returns> public static DateTime SetTime(this DateTime date, DateTime time) { return date.Date.Add(time.TimeOfDay); } } }// 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 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 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 { // Get an hour range from 12AM - 11PM, with a 15 and half minute interval var result = Utils.DateRange.GetTimeRange(0, 23, 15.5); foreach (var value in result) { Display($"Time: {value.Time}, String: {value.ToString()}"); } Display(""); // Get an hour range from 10PM - 10AM, with a 2 hour interval var result2 = Utils.DateRange.GetTimeRange(22, 10, 120); foreach (var value in result2) { Display($"Time: {value.Time}, String: {value.ToString(true)}"); } Display(""); // Get an hour range from 12AM - 11PM, with a 15 and half minute interval var result3 = Utils.DateRange.GetTimeRange(0, 23, 15.5, true); foreach (var value in result3) { Display($"Time: {value.Time}, String: {value.ToString()}"); } Display(""); // Get an hour range from 10PM - 10AM, with a 2 hour interval var result4 = Utils.DateRange.GetTimeRange(22, 10, 120, true); foreach (var value in result4) { Display($"Time: {value.Time}, String: {value.ToString(true)}"); } } 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 Add & Use Custom Attributes To Class Properties Using C#
The following is a module with functions which demonstrates how to add and use custom attributes for class properties using C#.
The function demonstrated on this page is a generic extension method which uses reflection to get object property data transformed according to its custom attribute.
1. Custom Attribute
The example below demonstrates the use of ‘Utils.Extensions.GetPropertyData‘ to get object property data transformed according to its custom attribute.
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 |
// Custom Attribute using Utils // Create custom attribute class public class DateFormatAttribute : System.Attribute { public DateFormat Format { get; set; } } // An enum to describe the custom attribute options public enum DateFormat { Default, ToLongDateString, ToLongTimeString, ToShortDateString, ToShortTimeString } // Class that has a property that uses the custom attribute public class User { [DateFormatAttribute(Format = DateFormat.ToShortDateString)] public DateTime registered { get; set; } public string name { get; set; } } // Declare user var user = new User() { name = "Kenneth", registered = DateTime.Now }; // Get the properties with the processed attribute var result = user.GetPropertyData(); // Display Info foreach (var prop in result) { Console.WriteLine($"Property: {prop.Key}, Value: {prop.Value}"); } // expected output: /* Property: registered, Value: 5/12/2021 Property: name, Value: Kenneth */ |
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 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 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 class DateFormatAttribute : System.Attribute { public DateFormat Format { get; set; } } public enum DateFormat { Default, ToLongDateString, ToLongTimeString, ToShortDateString, ToShortTimeString } public static class Extensions { /// <summary> /// Returns an objects property data with the data transformed /// according to its attributes /// </summary> /// <returns>The objects property data</returns> public static Dictionary<string, object> GetPropertyData<T>(this T source) where T : class { var result = new Dictionary<string, object>(); var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public; var properties = source.GetType().GetProperties(flags); foreach (var prop in properties) { var key = prop.Name; var value = prop.CanRead ? prop.GetValue(source , prop.GetIndexParameters().Count() == 1 ? new object[] { null } : null) : null; // Get custom attributes for the property var customAttributes = Attribute.GetCustomAttributes(prop); foreach (var attribute in customAttributes) { if (attribute.GetType().Equals(typeof(DateFormatAttribute))) { var dateValue = System.Convert.ToDateTime(value); switch (((DateFormatAttribute)attribute).Format) { case DateFormat.ToLongDateString: value = dateValue.ToLongDateString(); break; case DateFormat.ToLongTimeString: value = dateValue.ToLongTimeString(); break; case DateFormat.ToShortDateString: value = dateValue.ToShortDateString(); break; case DateFormat.ToShortTimeString: value = dateValue.ToShortTimeString(); break; default: value = dateValue.ToString(); break; } } } result.Add(key, value); } return result; } } }// 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 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 { public class User { [DateFormatAttribute(Format = DateFormat.ToShortDateString)] public DateTime registered { get; set; } public string name { get; set; } } static void Main(string[] args) { try { var user = new User() { name = "Kenneth", registered = DateTime.Now }; // Get the properties with the processed attribute var result = user.GetPropertyData(); foreach (var prop in result) { Display($"Property: {prop.Key}, Value: {prop.Value}"); } } 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 Remove Excess Whitespace From A String Using C#
The following is a module with functions which demonstrates how to remove excess whitespace from a string, replacing multiple spaces into just one using C#.
1. Remove Excess Whitespace
The example below demonstrates the use of ‘Utils.Extensions.ToSingleSpace‘ to remove excess whitespace from a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Remove Excess Whitespace using Utils; var word = @" This document uses 3 other documents "; // Creates single space string var result = word.ToSingleSpace(); Console.WriteLine(result); // expected output: /* This document uses 3 other documents */ |
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Extensions { /// <summary> /// Removes excess whitespace from a string /// </summary> /// <param name="source">The source string</param> /// <returns>The modified source string</returns> public static string ToSingleSpace(this string source) { var pattern = @"\s\s+"; var result = System.Text.RegularExpressions.Regex.Replace(source, pattern, " ").Trim(); return result; } } }// 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 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 word = @" This document uses 3 other documents "; // Creates single space string var result = word.ToSingleSpace(); Display(result); } 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 Remove All Whitespace From A String Using C#
The following is a module with functions which demonstrates how to remove all whitespace from a string using C#.
1. Remove All Whitespace
The example below demonstrates the use of ‘Utils.Extensions.RemoveWhitespace‘ to remove all whitespace from a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Remove All Whitespace using Utils; var word = $@" This document uses 3 other documents "; // Remove whitespace from the string var result = word.RemoveWhitespace(); Console.WriteLine(result); // expected output: /* Thisdocumentuses3otherdocuments */ |
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Extensions { /// <summary> /// Removes all whitespace from a string /// </summary> /// <param name="source">The source string</param> /// <returns>The modified source string</returns> public static string RemoveWhitespace(this string source) { var pattern = @"\s"; var result = System.Text.RegularExpressions.Regex.Replace(source, pattern, string.Empty); return result; } } }// 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 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 word = $@" This document uses 3 other documents "; // Remove whitespace from the string var result = word.RemoveWhitespace(); Display(result); } 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 Remove Non Alphanumeric Characters From A String Using C#
The following is a module with functions which demonstrates how to remove and replace non alphanumeric characters from a string using C#.
1. Alphanumeric Characters
The example below demonstrates the use of ‘Utils.Extensions.ToAlphaNumeric‘ to create an alphanumeric string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Alphanumeric Characters using Utils; var word = @"This-document_uses-3#other@documents!!!"; // Creates single space string var result = word.ToAlphaNumeric(); Console.WriteLine(result); // expected output: /* This document uses 3 other documents */ |
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Extensions { /// <summary> /// Returns the string as alphanumeric /// </summary> /// <param name="source">The source string</param> /// <param name="replacement">The string replacement for invalid characters</param> /// <returns>The modified source string</returns> public static string ToAlphaNumeric(this string source, string replacement = " ") { var pattern = "[^a-zA-Z0-9]+"; var result = System.Text.RegularExpressions.Regex.Replace(source, pattern, replacement).Trim(); return result; } } }// 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 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 word = @"This-document_uses-3#other@documents!!!"; // Creates single space string var result = word.ToAlphaNumeric(); Display(result); } 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 Replace Entire Words In A String Using C#
The following is a module with functions which demonstrates how to replace entire words in a string using C#.
This function is different from String.Replace in that instead of replacing all substring instances in a word, it replaces all instances of matching entire words in a string.
1. Replace Entire Word
The example below demonstrates the use of ‘Utils.Extensions.ReplaceWord‘ to replace an entire word.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Replace Entire Word using Utils; var word = "This docment uses 3 other docments to docment the docmentation"; // Replace the entire word in the string var result = word.ReplaceWord("docment", "document"); Console.WriteLine(result); // expected output: /* This document uses 3 other docments to document the docmentation */ |
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Extensions { /// <summary> /// Replaces the entire word in the string /// </summary> /// <param name="source">The source string</param> /// <param name="wordToReplace">The word to replace</param> /// <param name="replacementWord">The replacement word</param> /// <param name="regexOptions">The search options</param> /// <returns>The modified source string</returns> public static string ReplaceWord(this string source, string wordToReplace, string replacementWord , System.Text.RegularExpressions.RegexOptions regexOptions = System.Text.RegularExpressions.RegexOptions.None) { var pattern = $@"\b{System.Text.RegularExpressions.Regex.Escape(wordToReplace)}\b"; var result = System.Text.RegularExpressions.Regex.Replace(source, pattern, replacementWord, regexOptions); return result; } } }// 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 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 word = "This docment uses 3 other docments to docment the docmentation"; // Replace the entire word in the string var result = word.ReplaceWord("docment", "document"); Display(result); } 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 Manually Copy Two Streams From One To Another Using C#
The following is a module with functions which demonstrates how to manually copy two steams from one to another using C#.
1. Manually Copy Stream
The example below demonstrates the use of ‘Utils.Extensions.CopyStream‘ to copy two streams.
1 2 3 4 5 6 7 8 9 |
// Manually Copy Stream using Utils; System.IO.Stream stream1; System.IO.Stream stream2; // Copy stream1 to stream2 stream1.CopyStream(stream2); |
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Extensions { /// <summary> /// Reads bytes from the 'streamFrom' and writes them to 'streamTo' /// </summary> /// <param name="streamFrom">The source stream</param> /// <param name="streamTo">The destination stram</param> /// <returns>The total bytes written</returns> public static int CopyStream(this System.IO.Stream streamFrom, System.IO.Stream streamTo, int bufferSize = 4096) { int bytesWritten = 0; byte[] bytBuffer = new byte[bufferSize]; int bytesRead = 0; var tempPos = streamFrom.CanSeek ? (int?)streamFrom.Position : null; if (streamFrom.CanSeek) { streamFrom.Position = 0; } do { bytesRead = streamFrom.Read(bytBuffer, 0, bytBuffer.Length); if (bytesRead > 0) { streamTo.Write(bytBuffer, 0, bytesRead); bytesWritten += bytesRead; } } while (bytesRead > 0); if (tempPos.HasValue) { streamFrom.Position = tempPos.Value; } return bytesWritten; } } }// 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 12, 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 { System.IO.Stream stream1; System.IO.Stream stream2; // Copy stream1 to stream2 stream1.CopyStream(stream2); } 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.