Monthly Archives: May 2021
C# || How To Set & Get The Description Of An Enum Using C#
The following is a module with functions which demonstrates how to set and get the description of an enum using C#.
This function uses the DescriptionAttribute to get the description of an Enum element. If a description attribute is not specified, the string value of the Enum element is returned.
1. Get Description
The example below demonstrates the use of ‘Utils.Extensions.GetDescription‘ to get the description of enum elements.
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 |
// Get Description using Utils; public enum MimeTypes { [System.ComponentModel.Description("application/pdf")] ApplicationPDF = 1, [System.ComponentModel.Description("application/octet-stream")] ApplicationOctect = 2, [System.ComponentModel.Description("application/zip")] ApplicationZip = 3, [System.ComponentModel.Description("application/msword")] ApplicationMSWordDOC = 4, [System.ComponentModel.Description("application/vnd.openxmlformats-officedocument.wordprocessingml.document")] ApplicationMSWordDOCX = 5, [System.ComponentModel.Description("application/vnd.ms-excel")] ApplicationMSExcelXLS = 6, [System.ComponentModel.Description("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")] ApplicationMSExcelXLSX = 7 } foreach (MimeTypes value in System.Enum.GetValues(typeof(MimeTypes))) { Console.WriteLine($"Numeric Value: {(int)value}, Name: {value.ToString()}, Description: {value.GetDescription()}"); } // expected output: /* Numeric Value: 1, Name: ApplicationPDF, Description: application/pdf Numeric Value: 2, Name: ApplicationOctect, Description: application/octet-stream Numeric Value: 3, Name: ApplicationZip, Description: application/zip Numeric Value: 4, Name: ApplicationMSWordDOC, Description: application/msword Numeric Value: 5, Name: ApplicationMSWordDOCX, Description: application/vnd.openxmlformats-officedocument.wordprocessingml.document Numeric Value: 6, Name: ApplicationMSExcelXLS, Description: application/vnd.ms-excel Numeric Value: 7, Name: ApplicationMSExcelXLSX, Description: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet */ |
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 9, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Linq; namespace Utils { public static class Extensions { /// <summary> /// Returns the description of an enum decorated with a DescriptionAttribute /// </summary> /// <param name="value">An Enumeration value</param> /// <returns>The description of an enumeration value</returns> public static string GetDescription(this System.Enum value) { var description = value.ToString(); var attribute = GetAttribute<System.ComponentModel.DescriptionAttribute>(value); if (attribute != null) { description = attribute.Description; } return description; } public static T GetAttribute<T>(System.Enum value) where T : System.Attribute { var field = value.GetType().GetField(value.ToString()); var attribute = ((T[])field.GetCustomAttributes(typeof(T), false)).FirstOrDefault(); return attribute; } } }// 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 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 9, 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 enum MimeTypes { [System.ComponentModel.Description("application/pdf")] ApplicationPDF = 1, [System.ComponentModel.Description("application/octet-stream")] ApplicationOctect = 2, [System.ComponentModel.Description("application/zip")] ApplicationZip = 3, [System.ComponentModel.Description("application/msword")] ApplicationMSWordDOC = 4, [System.ComponentModel.Description("application/vnd.openxmlformats-officedocument.wordprocessingml.document")] ApplicationMSWordDOCX = 5, [System.ComponentModel.Description("application/vnd.ms-excel")] ApplicationMSExcelXLS = 6, [System.ComponentModel.Description("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")] ApplicationMSExcelXLSX = 7, [System.ComponentModel.Description("application/vnd.ms-powerpoint")] ApplicationMSPowerPointPPT = 8, [System.ComponentModel.Description("application/vnd.openxmlformats-officedocument.presentationml.presentation")] ApplicationMSPowerPointPPTX = 9, [System.ComponentModel.Description("audio/basic")] AudioBasic = 10, [System.ComponentModel.Description("audio/mpeg")] AudioMPEG = 11, [System.ComponentModel.Description("audio/x-wav")] AudioWAV = 12, [System.ComponentModel.Description("image/gif")] ImageGIF = 13, [System.ComponentModel.Description("image/jpeg")] ImageJPEG = 14, [System.ComponentModel.Description("image/png")] ImagePNG = 15, [System.ComponentModel.Description("text/html")] TextHTML = 16, [System.ComponentModel.Description("text/plain")] TextPlain = 17, [System.ComponentModel.Description("video/mpeg")] VideoMPEG = 18, [System.ComponentModel.Description("video/x-msvideo")] VideoAVI = 19 } static void Main(string[] args) { try { foreach (MimeTypes value in System.Enum.GetValues(typeof(MimeTypes))) { Display($"Numeric Value: {(int)value}, Name: {value.ToString()}, Description: {value.GetDescription()}"); } } 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 Iterate & Get The Values Of An Enum Using C#
The following is a module with functions which demonstrates how to iterate and get the values of an enum using C#.
This function is a generic wrapper for the Enum.GetValues function.
1. Get Values – Basic Enum
The example below demonstrates the use of ‘Utils.Methods.GetEnumValues‘ to get the values of a simple Enum.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Get Values - Basic Enum enum Colors { Red, Green, Blue, Yellow } var colors = Utils.Methods.GetEnumValues<Colors>(); foreach (var color in colors) { Console.WriteLine($"Numeric Value: {(int)color}, Name: {color.ToString()}"); } // expected output: /* Numeric Value: 0, Name: Red Numeric Value: 1, Name: Green Numeric Value: 2, Name: Blue Numeric Value: 3, Name: Yellow */ |
2. Get Values – Numbered Enum
The example below demonstrates the use of ‘Utils.Methods.GetEnumValues‘ to get the values of a numbered Enum.
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 |
// Get Values - Numbered Enum public enum Pets { None = 0, Dog = 1, Cat = 2, Rodent = 4, Bird = 8, Fish = 16, Reptile = 32, Other = 64 } var pets = Utils.Methods.GetEnumValues<Pets>(); foreach (var pet in pets) { Console.WriteLine($"Numeric Value: {(int)pet}, Name: {pet.ToString()}"); } // expected output: /* Numeric Value: 0, Name: None Numeric Value: 1, Name: Dog Numeric Value: 2, Name: Cat Numeric Value: 4, Name: Rodent Numeric Value: 8, Name: Bird Numeric Value: 16, Name: Fish Numeric Value: 32, Name: Reptile Numeric Value: 64, Name: Other */ |
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 9, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Collections.Generic; namespace Utils { public static class Methods { /// <summary> /// Returns a List of the values of the constants in a specified enumeration /// </summary> /// <returns>The values contained in the enumeration</returns> public static List<T> GetEnumValues<T>() { var type = typeof(T); if (!type.IsSubclassOf(typeof(System.Enum))) { throw new InvalidCastException($"Unable to cast '{type.FullName}' to System.Enum"); } var result = new List<T>(); foreach (T value in System.Enum.GetValues(type)) { result.Add(value); } return result; } } }// 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 9, 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 { enum Colors { Red, Green, Blue, Yellow } public enum Pets { None = 0, Dog = 1, Cat = 2, Rodent = 4, Bird = 8, Fish = 16, Reptile = 32, Other = 64 } static void Main(string[] args) { try { var colors = Utils.Methods.GetEnumValues<Colors>(); foreach (var color in colors) { Display($"Numeric Value: {(int)color}, Name: {color.ToString()}"); } Display(""); var pets = Utils.Methods.GetEnumValues<Pets>(); foreach (var pet in pets) { Display($"Numeric Value: {(int)pet}, Name: {pet.ToString()}"); } } 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 Resize & Rotate Image, Convert Image To Byte Array, Change Image Format, & Fix Image Orientation Using C#
The following is a module with functions which demonstrates how to resize an image, rotate an image to a specific angle, convert an image to a byte array, change an image format, and fix an image orientation Using C#.
Contents
1. Overview
2. Resize & Rotate - Image
3. Resize & Rotate - Byte Array
4. Resize & Rotate - Memory Stream
5. Convert Image To Byte Array
6. Change Image Format
7. Fix Image Orientation
8. Utils Namespace
9. More Examples
1. Overview
To use the functions in this module, make sure you have a reference to ‘System.Drawing‘ in your project.
One way to do this is, in your Solution Explorer (where all the files are shown with your project), right click the ‘References‘ folder, click ‘Add References‘, then type ‘System.Drawing‘ in the search box, and add a reference to System.Drawing in the results Tab.
Note: Don’t forget to include the ‘Utils Namespace‘ before running the examples!
2. Resize & Rotate – Image
The example below demonstrates the use of ‘Utils.Image.Extensions.Resize‘ and ‘Utils.Image.Extensions.Rotate‘ to resize and rotate an image object.
Resizing and rotating an image returns a newly created image object.
1 2 3 4 5 6 7 8 9 10 11 12 |
// Resize & Rotate - Image using Utils.Image; var path = $@"path-to-file\file.extension"; var image = System.Drawing.Image.FromFile(path); // Resize image 500x500 var resized = image.Resize(new System.Drawing.Size(500, 500)); // Rotate 90 degrees counter clockwise var rotated = image.Rotate(-90); |
3. Resize & Rotate – Byte Array
The example below demonstrates the use of ‘Utils.Image.Extensions.Resize‘ and ‘Utils.Image.Extensions.Rotate‘ to resize and rotate a byte array.
Resizing and rotating an image returns a newly created image object.
1 2 3 4 5 6 7 8 9 10 |
// Resize & Rotate - Byte Array // Read file to byte array byte[] bytes; // Resize image 800x800 var resized = Utils.Image.Extensions.Resize(bytes, new System.Drawing.Size(800, 800)); // Rotate 180 degrees clockwise var rotated = Utils.Image.Extensions.Rotate(bytes, 180); |
4. Resize & Rotate – Memory Stream
The example below demonstrates the use of ‘Utils.Image.Resize‘ and ‘Utils.Image.Rotate‘ to resize and rotate a memory stream.
Resizing and rotating an image returns a newly created image object.
1 2 3 4 5 6 7 8 9 10 |
// Resize & Rotate - Memory Stream // Read file to memory stream var stream = new System.IO.MemoryStream(); // Resize image 2000x2000 var resized = Utils.Image.Extensions.Resize(stream, new System.Drawing.Size(2000, 2000)); // Rotate 360 degrees var rotated = Utils.Image.Extensions.Rotate(stream, 360); |
5. Convert Image To Byte Array
The example below demonstrates the use of ‘Utils.Image.Extensions.ToArray‘ to convert an image object to a byte array.
The optional function parameter allows you to specify the image format.
1 2 3 4 5 6 7 8 9 |
// Convert Image To Byte Array using Utils.Image; var path = $@"path-to-file\file.extension" var image = System.Drawing.Image.FromFile(path); // Convert image to byte array var bytes = image.ToArray(); |
6. Change Image Format
The example below demonstrates the use of ‘Utils.Image.Extensions.ConvertFormat‘ to convert the image object raw format to another format.
Converting an images format returns a newly created image object.
1 2 3 4 5 6 7 8 9 |
// Change Image Format using Utils.Image; var path = $@"path-to-file\file.extension"; var image = System.Drawing.Image.FromFile(path); // Convert image to another format var newImage = image.ConvertFormat(System.Drawing.Imaging.ImageFormat.Png); |
7. Fix Image Orientation
The example below demonstrates the use of ‘Utils.Image.Extensions.FixOrientation‘ to update the image object to reflect its Exif orientation.
When you view an image in a Photo Viewer, it automatically corrects image orientation if it has Exif orientation data.
‘Utils.Image.Extensions.FixOrientation‘ makes it so the loaded image object reflects the correct orientation when rendered according to its Exif orientation data.
1 2 3 4 5 6 7 8 9 |
// Fix Image Orientation using Utils.Image; var path = $@"path-to-file\file.extension"; var image = System.Drawing.Image.FromFile(path); // Correct the image object to reflect its Exif orientation image.FixOrientation(); |
8. 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 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 9, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Collections.Generic; using System.Linq; namespace Utils { namespace Image { public static class Extensions { /// <summary> /// Resizes an image to a specified size /// </summary> /// <param name="source">The image to resize</param> /// <param name="desiredSize">The size to resize the image to</param> /// <param name="preserveAspectRatio">Determines if the aspect ratio should be preserved</param> /// <returns>A new image resized to the specified size</returns> public static System.Drawing.Image Resize(this System.Drawing.Image source, System.Drawing.Size desiredSize, bool preserveAspectRatio = true) { if (desiredSize.IsEmpty) { throw new ArgumentException("Image size cannot be empty", nameof(desiredSize)); } var resizedWidth = desiredSize.Width; var resizedHeight = desiredSize.Height; var sourceFormat = source.RawFormat; source.FixOrientation(); if (preserveAspectRatio) { var sourceWidth = Math.Max(source.Width, 1); var sourceHeight = Math.Max(source.Height, 1); var resizedPercentWidth = desiredSize.Width / (double)sourceWidth; var resizedPercentHeight = desiredSize.Height / (double)sourceHeight; var resizedPercentRatio = Math.Min(resizedPercentHeight, resizedPercentWidth); resizedWidth = System.Convert.ToInt32(sourceWidth * resizedPercentRatio); resizedHeight = System.Convert.ToInt32(sourceHeight * resizedPercentRatio); } var resizedImage = new System.Drawing.Bitmap(resizedWidth, resizedHeight); resizedImage.SetResolution(source.HorizontalResolution, source.VerticalResolution); using (var graphicsHandle = System.Drawing.Graphics.FromImage(resizedImage)) { graphicsHandle.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphicsHandle.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphicsHandle.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphicsHandle.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphicsHandle.DrawImage(source, 0, 0, resizedWidth, resizedHeight); } if (!sourceFormat.Equals(resizedImage.RawFormat)) { resizedImage = (System.Drawing.Bitmap)resizedImage.ConvertFormat(sourceFormat); } return resizedImage; } /// <summary> /// Resizes an image to a specified size /// </summary> /// <param name="stream">The stream of the image to resize</param> /// <param name="desiredSize">The size to resize the image to</param> /// <param name="preserveAspectRatio">Determines if the aspect ratio should be preserved</param> /// <returns>A new image resized to the specified size</returns> public static System.Drawing.Image Resize(System.IO.Stream stream, System.Drawing.Size desiredSize, bool preserveAspectRatio = true) { System.Drawing.Image image; using (var original = StreamToImage(stream)) { image = Resize(original, desiredSize, preserveAspectRatio: preserveAspectRatio); } return image; } /// <summary> /// Resizes an image to a specified size /// </summary> /// <param name="bytes">The byte array of the image to resize</param> /// <param name="desiredSize">The size to resize the image to</param> /// <param name="preserveAspectRatio">Determines if the aspect ratio should be preserved</param> /// <returns>A new image resized to the specified size</returns> public static System.Drawing.Image Resize(byte[] bytes, System.Drawing.Size desiredSize, bool preserveAspectRatio = true) { System.Drawing.Image image; using (var original = BytesToImage(bytes)) { image = Resize(original, desiredSize, preserveAspectRatio: preserveAspectRatio); } return image; } /// <summary> /// Rotates an image to a specified angle /// </summary> /// <param name="source">The image to resize</param> /// <param name="angle">The angle to rotate the image</param> /// <returns>A new image rotated to the specified angle</returns> public static System.Drawing.Image Rotate(this System.Drawing.Image source, decimal angle) { var sourceFormat = source.RawFormat; source.FixOrientation(); var alpha = angle; while (alpha < 0) { alpha += 360; } var gamma = 90M; var beta = 180 - angle - gamma; var c1 = source.Height; var a1 = Math.Abs((c1 * Math.Sin((double)alpha * Math.PI / 180))); var b1 = Math.Abs((c1 * Math.Sin((double)beta * Math.PI / 180))); var c2 = source.Width; var a2 = Math.Abs((c2 * Math.Sin((double)alpha * Math.PI / 180))); var b2 = Math.Abs((c2 * Math.Sin((double)beta * Math.PI / 180))); var width = System.Convert.ToInt32(b2 + a1); var height = System.Convert.ToInt32(b1 + a2); var rotatedImage = new System.Drawing.Bitmap(width, height); rotatedImage.SetResolution(source.HorizontalResolution, source.VerticalResolution); using (var graphicsHandle = System.Drawing.Graphics.FromImage(rotatedImage)) { graphicsHandle.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphicsHandle.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphicsHandle.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphicsHandle.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphicsHandle.TranslateTransform(rotatedImage.Width / 2, rotatedImage.Height / 2); graphicsHandle.RotateTransform((float)angle); graphicsHandle.TranslateTransform(-rotatedImage.Width / 2, -rotatedImage.Height / 2); graphicsHandle.DrawImage(source, new System.Drawing.Point((width - source.Width) / 2, (height - source.Height) / 2)); } if (!sourceFormat.Equals(rotatedImage.RawFormat)) { rotatedImage = (System.Drawing.Bitmap)rotatedImage.ConvertFormat(sourceFormat); } return rotatedImage; } /// <summary> /// Rotates an image to a specified angle /// </summary> /// <param name="stream">The stream of the image to resize</param> /// <param name="angle">The angle to rotate the image</param> /// <returns>A new image rotated to the specified angle</returns> public static System.Drawing.Image Rotate(System.IO.Stream stream, decimal angle) { System.Drawing.Image image; using (var original = StreamToImage(stream)) { image = Rotate(original, angle); } return image; } /// <summary> /// Rotates an image to a specified angle /// </summary> /// <param name="bytes">The byte array of the image to rotate</param> /// <param name="angle">The angle to rotate the image</param> /// <returns>A new image rotated to the specified angle</returns> public static System.Drawing.Image Rotate(byte[] bytes, decimal angle) { System.Drawing.Image image; using (var original = BytesToImage(bytes)) { image = Rotate(original, angle); } return image; } /// <summary> /// Converts an image to a byte array /// </summary> /// <param name="source">The image to convert</param> /// <param name="format">The format the byte array image should be converted to</param> /// <returns>The image as a byte array</returns> public static byte[] ToArray(this System.Drawing.Image source, System.Drawing.Imaging.ImageFormat format = null) { if (format == null) { format = source.ResolvedFormat(); if (format.Equals(System.Drawing.Imaging.ImageFormat.MemoryBmp)) { format = System.Drawing.Imaging.ImageFormat.Png; } } byte[] bytes; using (var stream = new System.IO.MemoryStream()) { source.Save(stream, format); bytes = stream.ToArray(); } return bytes; } /// <summary> /// Converts an image to a different ImageFormat /// </summary> /// <param name="source">The image to convert</param> /// <param name="format">The format the image should be changed to</param> /// <returns>The new image converted to the specified format</returns> public static System.Drawing.Image ConvertFormat(this System.Drawing.Image source, System.Drawing.Imaging.ImageFormat format) { var bytes = source.ToArray(format); var image = BytesToImage(bytes); return image; } /// <summary> /// Returns the resolved static image format from an images RawFormat /// </summary> /// <param name="source">The image to get the format from</param> /// <returns>The resolved image format</returns> public static System.Drawing.Imaging.ImageFormat ResolvedFormat(this System.Drawing.Image source) { var format = FindImageFormat(source.RawFormat); return format; } /// <summary> /// Returns all the ImageFormats as an IEnumerable /// </summary> /// <returns>All the ImageFormats as an IEnumerable</returns> public static IEnumerable<System.Drawing.Imaging.ImageFormat> GetImageFormats() { var formats = typeof(System.Drawing.Imaging.ImageFormat) .GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public) .Select(p => (System.Drawing.Imaging.ImageFormat)p.GetValue(null, null)); return formats; } /// <summary> /// Returns the static image format from a RawFormat /// </summary> /// <param name="raw">The ImageFormat to get info from</param> /// <returns>The resolved image format</returns> public static System.Drawing.Imaging.ImageFormat FindImageFormat(System.Drawing.Imaging.ImageFormat raw) { var format = GetImageFormats().FirstOrDefault(x => raw.Equals(x)); if (format == null) { format = System.Drawing.Imaging.ImageFormat.Png; } return format; } /// <summary> /// Update the image to reflect its exif orientation /// </summary> /// <param name="image">The image to update</param> public static void FixOrientation(this System.Drawing.Image image) { var orientationId = 274; if (!image.PropertyIdList.Contains(orientationId)) { return; } var orientation = BitConverter.ToInt16(image.GetPropertyItem(orientationId).Value, 0); var rotateFlip = System.Drawing.RotateFlipType.RotateNoneFlipNone; switch (orientation) { case 1: // Image is correctly oriented rotateFlip = System.Drawing.RotateFlipType.RotateNoneFlipNone; break; case 2: // Image has been mirrored horizontally rotateFlip = System.Drawing.RotateFlipType.RotateNoneFlipX; break; case 3: // Image has been rotated 180 degrees rotateFlip = System.Drawing.RotateFlipType.Rotate180FlipNone; break; case 4: // Image has been mirrored horizontally and rotated 180 degrees rotateFlip = System.Drawing.RotateFlipType.Rotate180FlipX; break; case 5: // Image has been mirrored horizontally and rotated 90 degrees clockwise rotateFlip = System.Drawing.RotateFlipType.Rotate90FlipX; break; case 6: // Image has been rotated 90 degrees clockwise rotateFlip = System.Drawing.RotateFlipType.Rotate90FlipNone; break; case 7: // Image has been mirrored horizontally and rotated 270 degrees clockwise rotateFlip = System.Drawing.RotateFlipType.Rotate270FlipX; break; case 8: // Image has been rotated 270 degrees clockwise rotateFlip = System.Drawing.RotateFlipType.Rotate270FlipNone; break; } if (rotateFlip != System.Drawing.RotateFlipType.RotateNoneFlipNone) { image.RotateFlip(rotateFlip); } } /// <summary> /// Returns an image from a byte array /// </summary> /// <param name="bytes">The bytes representing the image</param> /// <returns>The image from the byte array</returns> public static System.Drawing.Image BytesToImage(byte[] bytes) { return StreamToImage(new System.IO.MemoryStream(bytes)); } /// <summary> /// Returns an image from a stream /// </summary> /// <param name="stream">The stream representing the image</param> /// <returns>The image from the stream</returns> public static System.Drawing.Image StreamToImage(System.IO.Stream stream) { return System.Drawing.Image.FromStream(stream); } } } }// http://programmingnotes.org/ |
9. 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 9, 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.Image; public class Program { static void Main(string[] args) { try { var path = ""; // Image var image = System.Drawing.Image.FromFile(path); var resized = image.Resize(new System.Drawing.Size(500, 500)); //var rotated = image.Rotate(-90); // Byte //byte[] bytes; //var resized = Utils.Image.Extensions.Resize(bytes, new System.Drawing.Size(800, 800)); //var rotated = Utils.Image.Extensions.Rotate(bytes, 180); // Stream //var stream = new System.IO.MemoryStream(); //var resized = Utils.Image.Extensions.Resize(stream, new System.Drawing.Size(2000, 2000)); //var rotated = Utils.Image.Extensions.Rotate(stream, 360); var newPath = ""; resized.Save(newPath); } 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 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>() { "a@gmail.comm", "name@yah00.com", "_name@yah00.com", "name@again@example.com", "anystring@anystring.anystring", "prettyandsimple@example.com", "very.common@example.com", "disposable.style.email.with+symbol@example.com", "other.email-with-dash@example.com", "x@example.com", "\"much.more unusual\"@example.com", "\"very.unusual.@.unusual.com\"@example.com", "<< example-indeed@strange-example.com >>", "<< admin@mailserver1 >>", @"<< #!$%&\'*+-/=?^_`{}|~@example.org >>", "example@s.solutions", "user@com", "john.doe@example..com", "john..doe@example.com", "A@b@c@example.com" }; foreach (var email in addresses) { Console.WriteLine($"Email: {email}, Is Valid: {Utils.Email.IsValid(email)}"); } // expected output: /* Email: a@gmail.comm, Is Valid: True Email: name@yah00.com, Is Valid: True Email: _name@yah00.com, Is Valid: False Email: name@again@example.com, Is Valid: False Email: anystring@anystring.anystring, Is Valid: True Email: prettyandsimple@example.com, Is Valid: True Email: very.common@example.com, Is Valid: True Email: disposable.style.email.with+symbol@example.com, Is Valid: True Email: other.email-with-dash@example.com, Is Valid: True Email: x@example.com, Is Valid: True Email: "much.more unusual"@example.com, Is Valid: False Email: "very.unusual.@.unusual.com"@example.com, Is Valid: False Email: << example-indeed@strange-example.com >>, Is Valid: False Email: << admin@mailserver1 >>, Is Valid: False Email: << #!$%&\'*+-/=?^_`{}|~@example.org >>, Is Valid: False Email: example@s.solutions, Is Valid: True Email: user@com, Is Valid: False Email: john.doe@example..com, Is Valid: False Email: john..doe@example.com, Is Valid: False Email: A@b@c@example.com, 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>() { "a@gmail.comm", "name@yah00.com", "prettyandsimple@bumpymail.com", "disposable@gold2world.com", "user@gold2world.biz" }; // 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: a@gmail.comm, Is Valid: False Email: name@yah00.com, Is Valid: False Email: prettyandsimple@bumpymail.com, Is Valid: False Email: disposable@gold2world.com, Is Valid: True Email: user@gold2world.biz, 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>() { "a@gmail.comm", "name@yah00.com", "_name@yah00.com", "name@again@example.com", "anystring@anystring.anystring", "prettyandsimple@example.com", "very.common@example.com", "disposable.style.email.with+symbol@example.com", "other.email-with-dash@example.com", "x@example.com", "\"much.more unusual\"@example.com", "\"very.unusual.@.unusual.com\"@example.com", "<< example-indeed@strange-example.com >>", "<< admin@mailserver1 >>", @"<< #!$%&\'*+-/=?^_`{}|~@example.org >>", "example@s.solutions", "user@com", "john.doe@example..com", "john..doe@example.com", "A@b@c@example.com" }; 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>() { "a@gmail.comm", "name@yah00.com", "prettyandsimple@bumpymail.com", "disposable@gold2world.com", "user@gold2world.biz" }; // 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.
C# || How To Shuffle & Randomize An Array/List/IEnumerable Using C#
The following is a module with functions which demonstrates how to randomize and shuffle the contents of an Array/List/IEnumerable using C#.
This function shuffles an IEnumerable and returns the results as a new List(Of T).
This function is generic, so it should work on IEnumerables of any datatype.
1. Shuffle – Integer Array
The example below demonstrates the use of ‘Utils.Extensions.Shuffle‘ to randomize an integer array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Shuffle - Integer Array using Utils; var numbers = new int[] { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; var results = numbers.Shuffle(); foreach (var item in results) { Console.WriteLine($"{item}"); } // example output: /* 1991 1987 2009 22 28 2019 31 19 */ |
2. Shuffle – String List
The example below demonstrates the use of ‘Utils.Extensions.Shuffle‘ to randomize a list of strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Shuffle - String List using Utils; var names = new List<string>() { "Kenneth", "Jennifer", "Lynn", "Sole" }; var results = names.Shuffle(); foreach (var item in results) { Console.WriteLine($"{item}"); } // example output: /* Jennifer Kenneth Sole Lynn */ |
3. Shuffle – Custom Object List
The example below demonstrates the use of ‘Utils.Extensions.Shuffle‘ to randomize a list of custom objects.
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 |
// Shuffle - Custom Object List using Utils; public class Part { public string PartName { get; set; } public int PartId { get; set; } } var parts = new List<Part>() { new Part() { PartName = "crank arm", PartId = 1234 }, new Part() { PartName = "chain ring", PartId = 1334 }, new Part() { PartName = "regular seat", PartId = 1434 }, new Part() { PartName = "banana seat", PartId = 1444 }, new Part() { PartName = "cassette", PartId = 1534 }, new Part() { PartName = "shift lever", PartId = 1634 } }; var results = parts.Shuffle(); foreach (var item in results) { Console.WriteLine($"{item.PartId} - {item.PartName}"); } // example output: /* 1334 - chain ring 1444 - banana seat 1434 - regular seat 1534 - cassette 1634 - shift lever 1234 - crank arm */ |
4. 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 7, 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 Extensions { /// <summary> /// Shuffles an IEnumerable and returns the results as a List /// </summary> /// <param name="list">The IEnumerable list to shuffle</param> /// <returns>A List of shuffled items from the IEnumerable</returns> public static List<T> Shuffle<T>(this IEnumerable<T> list) { var r = new Random(); var shuffled = list.ToList(); for (int index = 0; index < shuffled.Count; ++index) { var randomIndex = r.Next(index, shuffled.Count); if (index != randomIndex) { var temp = shuffled[index]; shuffled[index] = shuffled[randomIndex]; shuffled[randomIndex] = temp; } } return shuffled; } } }// http://programmingnotes.org/ |
5. 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 7, 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; using Utils; public class Program { public class Part { public string PartName { get; set; } public int PartId { get; set; } } static void Main(string[] args) { try { var numbers = new int[] { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; var results = numbers.Shuffle(); foreach (var item in results) { Display($"{item}"); } Display(""); var names = new List<string>() { "Kenneth", "Jennifer", "Lynn", "Sole" }; var results1 = names.Shuffle(); foreach (var item in results1) { Display($"{item}"); } Display(""); var parts = new List<Part>() { new Part() { PartName = "crank arm", PartId = 1234 }, new Part() { PartName = "chain ring", PartId = 1334 }, new Part() { PartName = "regular seat", PartId = 1434 }, new Part() { PartName = "banana seat", PartId = 1444 }, new Part() { PartName = "cassette", PartId = 1534 }, new Part() { PartName = "shift lever", PartId = 1634 } }; var results2 = parts.Shuffle(); foreach (var item in results2) { Display($"{item.PartId} - {item.PartName}"); } } 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# || Word Wrap – How To Split A String Text Into lines With Maximum Length Using C#
The following is a module with functions which demonstrates how to split text into multiple lines using C#.
The following function is an extension method, which takes a string, and splits it into multiple lines (array indices) of a specified length.
An optional boolean parameter specifies whether this function should break up long individual words to fit as many characters as possible on a line.
With this option enabled, if a word is too long to fit on a line, the word is broken up to fit as many characters as possible up to the maximum length on the current line, and the remaining characters gets moved to the next line (the next array index).
Note: Don’t forget to include the ‘Utils Namespace‘ before running the examples!
1. Word Wrap – Don’t Break Words
The example below demonstrates the use of ‘Utils.Extensions.WordWrap‘ to split a string into multiple lines.
In this example, individual words are not broken up. They are simply moved onto the next line (if necessary).
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 |
// Word Wrap - Don't Break Words using Utils; // Limit string text to 40 characters per line var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus faucibus venenatis justo, placerat maximus tortor dictum non. Curabitur efficitur pulvinar arcu, id vehicula nisi commodo in. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vivamus consectetur ut orci scelerisque fringilla. Sed id nisl ac nunc congue suscipit at sollicitudin elit. Nullam tempus tortor sit amet molestie rutrum. Sed a sollicitudin magna, eget vulputate tortor. Proin ut sodales orci, a iaculis ipsum.Ut nec odio risus. Vivamus viverra metus turpis. Pellentesque lacinia lacinia tempus. Suspendisse in justo eget orci porttitor ornare vitae nec tortor. Donec dolor odio, dapibus non sodales quis, volutpat a turpis. Curabitur eget fermentum ante. Donec pulvinar nulla non ante mattis aliquam.Aenean vulputate, ligula sit amet laoreet porttitor, magna justo pellentesque diam, id tempus eros orci ut arcu. Praesent et finibus ipsum. Mauris luctus, metus vel sagittis pharetra, felis odio placerat felis, et ullamcorper neque turpis eget tellus. Maecenas vel imperdiet augue. Morbi imperdiet diam ac enim cursus venenatis. Donec eros turpis, pharetra a aliquet sed, vehicula sed libero. Donec efficitur volutpat ex, in euismod dolor tristique at. Quisque a nisi ultricies libero lacinia fringilla nec vel tortor.Aenean id felis et quam lacinia ornare. Curabitur blandit, arcu eget ultricies pulvinar, neque lectus ultrices mauris, vitae feugiat mauris diam id tellus. Vestibulum finibus cursus dui et feugiat. Sed vitae sagittis lorem. Duis suscipit sollicitudin est tempor efficitur. Morbi eget fringilla massa. Integer ullamcorper, ligula congue consequat sodales, dolor eros pretium augue, in luctus enim massa quis est. Fusce cursus ac ipsum quis aliquet. Curabitur pharetra lectus non suscipit scelerisque. Pellentesque vitae scelerisque tellus. Donec sit amet ligula felis. Donec ac hendrerit magna, sed pharetra diam. Morbi gravida felis finibus sodales suscipit. In hac habitasse platea dictumst.Curabitur purus erat, tincidunt vel tincidunt et, fermentum eget dui. Fusce eu justo vel massa ultrices lacinia sit amet quis augue. Nunc fringilla justo quis felis fringilla, at rutrum justo venenatis. Ut ullamcorper gravida finibus. Donec fermentum varius metus sit amet porttitor. Sed at auctor velit. Quisque et urna metus. Donec ut mi vel turpis dignissim pulvinar. Curabitur massa leo, interdum ac urna id, dictum pellentesque nunc. Ut dolor justo, vehicula quis porta in, laoreet eget augue. this is a test pneumonoultramicroscopicsilicovolcanoconiosis"; var maxCharacters = 40; var result = text.WordWrap(maxCharacters); foreach (var line in result) { Console.WriteLine($"Length: {line.Length} - {line}"); } // expected output: /* Length: 39 - Lorem ipsum dolor sit amet, consectetur Length: 35 - adipiscing elit. Phasellus faucibus Length: 40 - venenatis justo, placerat maximus tortor Length: 40 - dictum non. Curabitur efficitur pulvinar Length: 34 - arcu, id vehicula nisi commodo in. Length: 35 - Interdum et malesuada fames ac ante Length: 33 - ipsum primis in faucibus. Vivamus Length: 31 - consectetur ut orci scelerisque Length: 37 - fringilla. Sed id nisl ac nunc congue Length: 37 - suscipit at sollicitudin elit. Nullam Length: 39 - tempus tortor sit amet molestie rutrum. Length: 40 - Sed a sollicitudin magna, eget vulputate Length: 40 - tortor. Proin ut sodales orci, a iaculis Length: 40 - ipsum.Ut nec odio risus. Vivamus viverra Length: 34 - metus turpis. Pellentesque lacinia Length: 36 - lacinia tempus. Suspendisse in justo Length: 36 - eget orci porttitor ornare vitae nec Length: 37 - tortor. Donec dolor odio, dapibus non Length: 32 - sodales quis, volutpat a turpis. Length: 36 - Curabitur eget fermentum ante. Donec Length: 30 - pulvinar nulla non ante mattis Length: 36 - aliquam.Aenean vulputate, ligula sit Length: 35 - amet laoreet porttitor, magna justo Length: 38 - pellentesque diam, id tempus eros orci Length: 35 - ut arcu. Praesent et finibus ipsum. Length: 33 - Mauris luctus, metus vel sagittis Length: 39 - pharetra, felis odio placerat felis, et Length: 37 - ullamcorper neque turpis eget tellus. Length: 35 - Maecenas vel imperdiet augue. Morbi Length: 40 - imperdiet diam ac enim cursus venenatis. Length: 37 - Donec eros turpis, pharetra a aliquet Length: 31 - sed, vehicula sed libero. Donec Length: 39 - efficitur volutpat ex, in euismod dolor Length: 38 - tristique at. Quisque a nisi ultricies Length: 32 - libero lacinia fringilla nec vel Length: 38 - tortor.Aenean id felis et quam lacinia Length: 36 - ornare. Curabitur blandit, arcu eget Length: 32 - ultricies pulvinar, neque lectus Length: 37 - ultrices mauris, vitae feugiat mauris Length: 34 - diam id tellus. Vestibulum finibus Length: 32 - cursus dui et feugiat. Sed vitae Length: 29 - sagittis lorem. Duis suscipit Length: 40 - sollicitudin est tempor efficitur. Morbi Length: 29 - eget fringilla massa. Integer Length: 36 - ullamcorper, ligula congue consequat Length: 37 - sodales, dolor eros pretium augue, in Length: 40 - luctus enim massa quis est. Fusce cursus Length: 32 - ac ipsum quis aliquet. Curabitur Length: 28 - pharetra lectus non suscipit Length: 31 - scelerisque. Pellentesque vitae Length: 34 - scelerisque tellus. Donec sit amet Length: 39 - ligula felis. Donec ac hendrerit magna, Length: 38 - sed pharetra diam. Morbi gravida felis Length: 32 - finibus sodales suscipit. In hac Length: 35 - habitasse platea dictumst.Curabitur Length: 39 - purus erat, tincidunt vel tincidunt et, Length: 38 - fermentum eget dui. Fusce eu justo vel Length: 36 - massa ultrices lacinia sit amet quis Length: 38 - augue. Nunc fringilla justo quis felis Length: 40 - fringilla, at rutrum justo venenatis. Ut Length: 34 - ullamcorper gravida finibus. Donec Length: 31 - fermentum varius metus sit amet Length: 39 - porttitor. Sed at auctor velit. Quisque Length: 37 - et urna metus. Donec ut mi vel turpis Length: 40 - dignissim pulvinar. Curabitur massa leo, Length: 40 - interdum ac urna id, dictum pellentesque Length: 35 - nunc. Ut dolor justo, vehicula quis Length: 39 - porta in, laoreet eget augue. this is a Length: 4 - test Length: 45 - pneumonoultramicroscopicsilicovolcanoconiosis */ |
2. Word Wrap – Break Words
The example below demonstrates the use of ‘Utils.Extensions.WordWrap‘ to split a string into multiple lines.
In this example, individual words are broken up and moved onto the next line (if necessary), with the default hyphen character used, which is a dash (‘-‘).
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 |
// Word Wrap - Break Words using Utils; // Limit string text to 40 characters per line var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus faucibus venenatis justo, placerat maximus tortor dictum non. Curabitur efficitur pulvinar arcu, id vehicula nisi commodo in. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vivamus consectetur ut orci scelerisque fringilla. Sed id nisl ac nunc congue suscipit at sollicitudin elit. Nullam tempus tortor sit amet molestie rutrum. Sed a sollicitudin magna, eget vulputate tortor. Proin ut sodales orci, a iaculis ipsum.Ut nec odio risus. Vivamus viverra metus turpis. Pellentesque lacinia lacinia tempus. Suspendisse in justo eget orci porttitor ornare vitae nec tortor. Donec dolor odio, dapibus non sodales quis, volutpat a turpis. Curabitur eget fermentum ante. Donec pulvinar nulla non ante mattis aliquam.Aenean vulputate, ligula sit amet laoreet porttitor, magna justo pellentesque diam, id tempus eros orci ut arcu. Praesent et finibus ipsum. Mauris luctus, metus vel sagittis pharetra, felis odio placerat felis, et ullamcorper neque turpis eget tellus. Maecenas vel imperdiet augue. Morbi imperdiet diam ac enim cursus venenatis. Donec eros turpis, pharetra a aliquet sed, vehicula sed libero. Donec efficitur volutpat ex, in euismod dolor tristique at. Quisque a nisi ultricies libero lacinia fringilla nec vel tortor.Aenean id felis et quam lacinia ornare. Curabitur blandit, arcu eget ultricies pulvinar, neque lectus ultrices mauris, vitae feugiat mauris diam id tellus. Vestibulum finibus cursus dui et feugiat. Sed vitae sagittis lorem. Duis suscipit sollicitudin est tempor efficitur. Morbi eget fringilla massa. Integer ullamcorper, ligula congue consequat sodales, dolor eros pretium augue, in luctus enim massa quis est. Fusce cursus ac ipsum quis aliquet. Curabitur pharetra lectus non suscipit scelerisque. Pellentesque vitae scelerisque tellus. Donec sit amet ligula felis. Donec ac hendrerit magna, sed pharetra diam. Morbi gravida felis finibus sodales suscipit. In hac habitasse platea dictumst.Curabitur purus erat, tincidunt vel tincidunt et, fermentum eget dui. Fusce eu justo vel massa ultrices lacinia sit amet quis augue. Nunc fringilla justo quis felis fringilla, at rutrum justo venenatis. Ut ullamcorper gravida finibus. Donec fermentum varius metus sit amet porttitor. Sed at auctor velit. Quisque et urna metus. Donec ut mi vel turpis dignissim pulvinar. Curabitur massa leo, interdum ac urna id, dictum pellentesque nunc. Ut dolor justo, vehicula quis porta in, laoreet eget augue. this is a test pneumonoultramicroscopicsilicovolcanoconiosis"; var maxCharacters = 40; var result = text.WordWrap(maxCharacters, true); foreach (var line in result) { Console.WriteLine($"Length: {line.Length} - {line}"); } // expected output: /* Length: 39 - Lorem ipsum dolor sit amet, consectetur Length: 40 - adipiscing elit. Phasellus faucibus ven- Length: 40 - enatis justo, placerat maximus tortor d- Length: 39 - ictum non. Curabitur efficitur pulvinar Length: 40 - arcu, id vehicula nisi commodo in. Inte- Length: 40 - rdum et malesuada fames ac ante ipsum p- Length: 38 - rimis in faucibus. Vivamus consectetur Length: 40 - ut orci scelerisque fringilla. Sed id n- Length: 40 - isl ac nunc congue suscipit at sollicit- Length: 40 - udin elit. Nullam tempus tortor sit amet Length: 40 - molestie rutrum. Sed a sollicitudin mag- Length: 40 - na, eget vulputate tortor. Proin ut sod- Length: 38 - ales orci, a iaculis ipsum.Ut nec odio Length: 40 - risus. Vivamus viverra metus turpis. Pe- Length: 40 - llentesque lacinia lacinia tempus. Susp- Length: 40 - endisse in justo eget orci porttitor or- Length: 40 - nare vitae nec tortor. Donec dolor odio, Length: 40 - dapibus non sodales quis, volutpat a tu- Length: 40 - rpis. Curabitur eget fermentum ante. Do- Length: 40 - nec pulvinar nulla non ante mattis aliq- Length: 40 - uam.Aenean vulputate, ligula sit amet l- Length: 40 - aoreet porttitor, magna justo pellentes- Length: 38 - que diam, id tempus eros orci ut arcu. Length: 40 - Praesent et finibus ipsum. Mauris luctu- Length: 40 - s, metus vel sagittis pharetra, felis o- Length: 40 - dio placerat felis, et ullamcorper neque Length: 40 - turpis eget tellus. Maecenas vel imperd- Length: 39 - iet augue. Morbi imperdiet diam ac enim Length: 40 - cursus venenatis. Donec eros turpis, ph- Length: 40 - aretra a aliquet sed, vehicula sed libe- Length: 40 - ro. Donec efficitur volutpat ex, in eui- Length: 39 - smod dolor tristique at. Quisque a nisi Length: 38 - ultricies libero lacinia fringilla nec Length: 40 - vel tortor.Aenean id felis et quam laci- Length: 40 - nia ornare. Curabitur blandit, arcu eget Length: 40 - ultricies pulvinar, neque lectus ultric- Length: 39 - es mauris, vitae feugiat mauris diam id Length: 40 - tellus. Vestibulum finibus cursus dui et Length: 39 - feugiat. Sed vitae sagittis lorem. Duis Length: 40 - suscipit sollicitudin est tempor effici- Length: 40 - tur. Morbi eget fringilla massa. Integer Length: 40 - ullamcorper, ligula congue consequat so- Length: 40 - dales, dolor eros pretium augue, in luc- Length: 40 - tus enim massa quis est. Fusce cursus ac Length: 38 - ipsum quis aliquet. Curabitur pharetra Length: 40 - lectus non suscipit scelerisque. Pellen- Length: 38 - tesque vitae scelerisque tellus. Donec Length: 40 - sit amet ligula felis. Donec ac hendrer- Length: 40 - it magna, sed pharetra diam. Morbi grav- Length: 38 - ida felis finibus sodales suscipit. In Length: 39 - hac habitasse platea dictumst.Curabitur Length: 39 - purus erat, tincidunt vel tincidunt et, Length: 38 - fermentum eget dui. Fusce eu justo vel Length: 40 - massa ultrices lacinia sit amet quis au- Length: 40 - gue. Nunc fringilla justo quis felis fr- Length: 38 - ingilla, at rutrum justo venenatis. Ut Length: 40 - ullamcorper gravida finibus. Donec ferm- Length: 38 - entum varius metus sit amet porttitor. Length: 40 - Sed at auctor velit. Quisque et urna me- Length: 40 - tus. Donec ut mi vel turpis dignissim p- Length: 38 - ulvinar. Curabitur massa leo, interdum Length: 40 - ac urna id, dictum pellentesque nunc. Ut Length: 40 - dolor justo, vehicula quis porta in, la- Length: 40 - oreet eget augue. this is a test pneumo- Length: 39 - noultramicroscopicsilicovolcanoconiosis */ |
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 7, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Extensions { /// <summary> /// Takes in a string and splits it into multiple lines (array indices) /// of a specified length. If a word is too long to fit on a line, /// the word gets moved to the next line (the next array index) /// </summary> /// <param name="text">The text to word wrap</param> /// <param name="maxCharactersPerLine">The maximum characters per /// line</param> /// <param name="breakWords">Determine if words should fit as many as /// possible on current line, with remaining broken up to the next line</param> /// <param name="hyphenChar">The character to use at the end of the line /// as a hyphen when breaking up words</param> /// <param name="hyphenatedWordMinLength">The minimum length of the /// hyphenated word after it is broken up. A word will not be hyphenated /// unless it meets this minimum length after it is broken up</param> /// <returns>A list of strings that contains each line limited by /// the specified length</returns> public static System.Collections.Generic.List<string> WordWrap(this string text, int maxCharactersPerLine, bool breakWords = false, char? hyphenChar = '-', int hyphenatedWordMinLength = 1) { if (breakWords && hyphenatedWordMinLength >= maxCharactersPerLine) { throw new System.InvalidOperationException($"Unable to fit the value of '{nameof(hyphenatedWordMinLength)}' ({hyphenatedWordMinLength}) with '{nameof(maxCharactersPerLine)}' ({maxCharactersPerLine}). Either increase the value of '{nameof(maxCharactersPerLine)}' or decrease the value of '{nameof(hyphenatedWordMinLength)}'"); } text = text.Trim(); var result = new System.Collections.Generic.List<string>(); if (text.Length <= maxCharactersPerLine) { result.Add(text); } else { var words = text.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries); var leftOver = string.Empty; for (int wordIndex = 0; wordIndex < words.Length || !string.IsNullOrWhiteSpace(leftOver); ++wordIndex) { var currentResultLineIndex = result.Count - 1; var currentResultLineLength = currentResultLineIndex > -1 ? result[currentResultLineIndex].Length : 0; // Start string with left over text from previous word var addition = string.Empty; if (!string.IsNullOrWhiteSpace(leftOver)) { if (currentResultLineLength > 0 && currentResultLineLength < maxCharactersPerLine && !leftOver.StartsWith(" ")) { addition += " "; } addition += leftOver; } // Add current word to string if (wordIndex < words.Length) { var word = words[wordIndex].Trim(); if (currentResultLineLength > 0 && !addition.EndsWith(" ")) { addition += " "; } addition += word; } if (breakWords) { // Determine how many characters to take from the current addition var remainingLineLength = maxCharactersPerLine - currentResultLineLength; var charactersToAddLength = Math.Min((remainingLineLength > 0 ? remainingLineLength : maxCharactersPerLine), addition.Length); // Include hyphen if word will be broken up if (charactersToAddLength > 1 && charactersToAddLength < addition.Length) { var slice = addition.Substring(0, charactersToAddLength); if (!string.IsNullOrWhiteSpace(slice)) { if (hyphenChar == null || slice[charactersToAddLength - 1] != hyphenChar) { // Determine the length of the hyphenated word var hyphenatedWordLength = 0; var hyphenInsertIndexStart = charactersToAddLength - 1; while (hyphenInsertIndexStart >= 0 && !char.IsWhiteSpace(slice[hyphenInsertIndexStart])) { ++hyphenatedWordLength; --hyphenInsertIndexStart; } // Subtract the hypenated character from the result if (hyphenChar.HasValue) { --hyphenatedWordLength; } if (hyphenatedWordLength >= hyphenatedWordMinLength) { addition = addition.Insert(charactersToAddLength - 1, hyphenChar.HasValue ? hyphenChar.ToString() : string.Empty); } else if (hyphenInsertIndexStart >= 0 && (hyphenChar == null || addition[hyphenInsertIndexStart] != hyphenChar)) { addition = addition.Insert(hyphenInsertIndexStart, new string(' ', hyphenatedWordMinLength)); } } } } currentResultLineLength += charactersToAddLength; // Save excess characters from current addition for the next line leftOver = charactersToAddLength < addition.Length ? addition.Substring(charactersToAddLength) : string.Empty; // Only take the specified characters from the string addition = addition.Substring(0, charactersToAddLength); } else { currentResultLineLength += addition.Length; } // Add or append words to result if (result.Count < 1 || currentResultLineLength > maxCharactersPerLine) { // Start new line addition = addition.Trim(); result.Add(addition); } else { // Append existing line result[currentResultLineIndex] += addition; } } } // Remove excess whitespace for (int index = 0; index < result.Count; ++index) { result[index] = result[index].Trim(); } return result; } } }// 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 7, 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 { // Limit string text to 40 characters per line var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus faucibus venenatis justo, placerat maximus tortor dictum non. Curabitur efficitur pulvinar arcu, id vehicula nisi commodo in. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vivamus consectetur ut orci scelerisque fringilla. Sed id nisl ac nunc congue suscipit at sollicitudin elit. Nullam tempus tortor sit amet molestie rutrum. Sed a sollicitudin magna, eget vulputate tortor. Proin ut sodales orci, a iaculis ipsum.Ut nec odio risus. Vivamus viverra metus turpis. Pellentesque lacinia lacinia tempus. Suspendisse in justo eget orci porttitor ornare vitae nec tortor. Donec dolor odio, dapibus non sodales quis, volutpat a turpis. Curabitur eget fermentum ante. Donec pulvinar nulla non ante mattis aliquam.Aenean vulputate, ligula sit amet laoreet porttitor, magna justo pellentesque diam, id tempus eros orci ut arcu. Praesent et finibus ipsum. Mauris luctus, metus vel sagittis pharetra, felis odio placerat felis, et ullamcorper neque turpis eget tellus. Maecenas vel imperdiet augue. Morbi imperdiet diam ac enim cursus venenatis. Donec eros turpis, pharetra a aliquet sed, vehicula sed libero. Donec efficitur volutpat ex, in euismod dolor tristique at. Quisque a nisi ultricies libero lacinia fringilla nec vel tortor.Aenean id felis et quam lacinia ornare. Curabitur blandit, arcu eget ultricies pulvinar, neque lectus ultrices mauris, vitae feugiat mauris diam id tellus. Vestibulum finibus cursus dui et feugiat. Sed vitae sagittis lorem. Duis suscipit sollicitudin est tempor efficitur. Morbi eget fringilla massa. Integer ullamcorper, ligula congue consequat sodales, dolor eros pretium augue, in luctus enim massa quis est. Fusce cursus ac ipsum quis aliquet. Curabitur pharetra lectus non suscipit scelerisque. Pellentesque vitae scelerisque tellus. Donec sit amet ligula felis. Donec ac hendrerit magna, sed pharetra diam. Morbi gravida felis finibus sodales suscipit. In hac habitasse platea dictumst.Curabitur purus erat, tincidunt vel tincidunt et, fermentum eget dui. Fusce eu justo vel massa ultrices lacinia sit amet quis augue. Nunc fringilla justo quis felis fringilla, at rutrum justo venenatis. Ut ullamcorper gravida finibus. Donec fermentum varius metus sit amet porttitor. Sed at auctor velit. Quisque et urna metus. Donec ut mi vel turpis dignissim pulvinar. Curabitur massa leo, interdum ac urna id, dictum pellentesque nunc. Ut dolor justo, vehicula quis porta in, laoreet eget augue. this is a test pneumonoultramicroscopicsilicovolcanoconiosis"; var maxCharacters = 40; var result = text.WordWrap(maxCharacters); foreach (var line in result) { Display($"Length: {line.Length} - {line}"); } } 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 Get First/Last Day Of The Week And The First/Last Day Of The Month
The following is a module with functions which demonstrates how to get the first and last day of the week, as well as how to get the first and last day of the month using C#.
1. First & Last Day Of Week
The example below demonstrates the use of ‘Utils.DateRange.GetWeekStartAndEnd‘ to get the first and last day of the week.
By default, the start of the week is set on Monday. This can be changed by setting the second parameter to any valid property contained in the System.DayOfWeek enum.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// First & Last Day Of Week // Get the first and last day of the week var weekResult = Utils.DateRange.GetWeekStartAndEnd(DateTime.Today); // Display results Console.WriteLine($@" Today = {DateTime.Today.ToShortDateString()} Week Start = {weekResult.StartDate.ToShortDateString()} Week End = {weekResult.EndDate.ToShortDateString()} "); // expected output: /* Today = 5/7/2021 Week Start = 5/3/2021 Week End = 5/9/2021 */ |
2. First & Last Day Of Month
The example below demonstrates the use of ‘Utils.DateRange.GetMonthStartAndEnd‘ to get the first and last day of the week.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// First & Last Day Of Month // Get the first and last day of the month var monthResult = Utils.DateRange.GetMonthStartAndEnd(DateTime.Today); // Display results Console.WriteLine($@" Today = {DateTime.Today.ToShortDateString()} Month Start = {monthResult.StartDate.ToShortDateString()} Month End = {monthResult.EndDate.ToShortDateString()} "); // expected output: /* Today = 5/7/2021 Month Start = 5/1/2021 Month End = 5/31/2021 */ |
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 7, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public class DateRange { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } /// <summary> /// Takes in a date and returns the first and last day of the week /// </summary> /// <param name="date">The reference date in question</param> /// <param name="firstDayOfWeek">The day the week starts on</param> /// <returns>An object that contains the date range result</returns> public static DateRange GetWeekStartAndEnd(DateTime date, DayOfWeek firstDayOfWeek = DayOfWeek.Monday) { DateRange result = new DateRange(); result.StartDate = date.AddDays(1 - Weekday(date, firstDayOfWeek)).Date; result.EndDate = result.StartDate.AddDays(6).Date; return result; } /// <summary> /// Takes in a date and returns the first and last day of the month /// </summary> /// <param name="date">The reference date in question</param> /// <returns>An object that contains the date range result</returns> public static DateRange GetMonthStartAndEnd(DateTime date) { DateRange result = new DateRange(); result.StartDate = new DateTime(date.Year, date.Month, 1).Date; result.EndDate = result.StartDate.AddMonths(1).AddDays(-1).Date; return result; } private static int Weekday(DateTime date, DayOfWeek firstDayOfWeek) { return ((date.DayOfWeek - firstDayOfWeek + 7) % 7) + 1; } } }// 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 7, 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 weekResult = Utils.DateRange.GetWeekStartAndEnd(DateTime.Today); Display($@" Today = {DateTime.Today.ToShortDateString()} Week Start = {weekResult.StartDate.ToShortDateString()} Week End = {weekResult.EndDate.ToShortDateString()} "); var monthResult = Utils.DateRange.GetMonthStartAndEnd(DateTime.Today); Display($@" Today = {DateTime.Today.ToShortDateString()} Month Start = {monthResult.StartDate.ToShortDateString()} Month End = {monthResult.EndDate.ToShortDateString()} "); } 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.