Daily Archives: May 10, 2021
C# || How To Get, Add, Update & Remove Values From A URL Query String Using C#
The following is a module with functions which demonstrates how to get, add, update and remove parameters from a query string using C#.
The following functions use System.Web to modify the url.
To use the functions in this module, make sure you have a reference to ‘System.Web‘ 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 Reference‘, then type ‘System.Web‘ in the search box, and add the reference titled System.Web in the results Tab.
Note: Don’t forget to include the ‘Utils Namespace‘ before running the examples!
1. Add – Single Parameter
The example below demonstrates the use of ‘Utils.HttpParams.Add‘ to add a query string parameter to a url.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Add - Single Parameter // Declare url var url = "http://programmingnotes.org/"; // Add single key value parameter to the url var result = Utils.HttpParams.Add(url, new KeyValuePair<string, string>("ids", "1987")); // Display result Console.WriteLine(result); // expected output: /* http://programmingnotes.org/?ids=1987 */ |
2. Add – Multiple Parameters
The example below demonstrates the use of ‘Utils.HttpParams.Add‘ to add a query string parameter to a url.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Add - Multiple Parameters // Declare url var url = "http://programmingnotes.org/?ids=1987,1991&names=Kenneth,Jennifer"; // Add multiple key value parameters to the url var addition = new System.Collections.Specialized.NameValueCollection() { {"ids", "2010"}, {"ids", "2019"}, {"names", "Lynn"}, {"names", "Sole"} }; // Update the url var result = Utils.HttpParams.Add(url, addition); // Display result Console.WriteLine(result); // expected output: /* http://programmingnotes.org/?ids=1987%2c1991%2c2010%2c2019&names=Kenneth%2cJennifer%2cLynn%2cSole */ |
3. Update – Single Parameter
The example below demonstrates the use of ‘Utils.HttpParams.Update‘ to update a query string parameter to a url.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Update - Single Parameter // Declare url var url = "http://programmingnotes.org/?ids=1987"; // Update single key value parameter to the url var result = Utils.HttpParams.Update(url, new KeyValuePair<string, string>("ids", "1991")); // Display result Console.WriteLine(result); // expected output: /* http://programmingnotes.org/?ids=1991 */ |
4. Update – Multiple Parameters
The example below demonstrates the use of ‘Utils.HttpParams.Update‘ to update a query string parameter to a url.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Update - Multiple Parameters // Declare url var url = "http://programmingnotes.org/?ids=1987,1991&names=Kenneth,Jennifer"; // Update multiple key value parameters to the url var addition = new System.Collections.Specialized.NameValueCollection() { {"ids", "2010"}, {"ids", "2019"}, {"names", "Lynn"}, {"names", "Sole"} }; // Update the url var result = Utils.HttpParams.Update(url, addition); // Display result Console.WriteLine(result); // expected output: /* http://programmingnotes.org/?ids=2010%2c2019&names=Lynn%2cSole */ |
5. Remove – Single Parameter
The example below demonstrates the use of ‘Utils.HttpParams.Remove‘ to remove a query string parameter from a url.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Remove - Single Parameter // Declare url var url = "http://programmingnotes.org/?ids=1987,1991&names=Kenneth,Jennifer"; // Remove single parameter from the url var result = Utils.HttpParams.Remove(url, "names"); // Display result Console.WriteLine(result); // expected output: /* http://programmingnotes.org/?ids=1987%2c1991 */ |
6. Remove – Multiple Parameters
The example below demonstrates the use of ‘Utils.HttpParams.Remove‘ to remove multiple query string parameters from a url.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Remove - Multiple Parameters // Declare url var url = "http://programmingnotes.org/?ids=1987,1991&names=Kenneth,Jennifer"; // Remove multiple parameters from the url var result = Utils.HttpParams.Remove(url, new string[] { "ids", "names" }); // Display result Console.WriteLine(result); // expected output: /* http://programmingnotes.org/ */ |
7. Clear – Remove All Parameters
The example below demonstrates the use of ‘Utils.HttpParams.Clear‘ to remove all query string parameters from a url.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Clear - Remove All Parameters // Declare url var url = "http://programmingnotes.org/?ids=1987,1991&names=Kenneth,Jennifer"; // Remove multiple parameters from the url var result = Utils.HttpParams.Clear(url); // Display result Console.WriteLine(result); // expected output: /* http://programmingnotes.org/ */ |
8. Get – Get All Parameters
The example below demonstrates the use of ‘Utils.HttpParams.Get‘ to get all query string parameters from a url.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Get - Get All Parameters // Declare url var url = "http://programmingnotes.org/?ids=1987,1991,2010,2019&names=Kenneth,Jennifer,Lynn,Sole"; // Get parameters from the url var result = Utils.HttpParams.Get(url); // Display result foreach (string key in result) { Console.WriteLine($"Parameter: {key}, Value: {result[key]}"); } // expected output: /* Parameter: ids, Value: 1987,1991,2010,2019 Parameter: names, Value: Kenneth,Jennifer,Lynn,Sole */ |
9. 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 10, 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 { public static class HttpParams { /// <summary> /// Adds the query string parameters to a url /// </summary> /// <param name="url">The url to append parameters</param> /// <param name="query">The parameters to add to the url</param> /// <returns>The url appended with the specified query</returns> public static string Add(string url, System.Collections.Specialized.NameValueCollection query) { return UpdateQuery(url, queryString => { var merged = new System.Collections.Specialized.NameValueCollection { queryString, query }; CopyProps(merged, queryString); }); } /// <summary> /// Adds the query string parameters to a url /// </summary> /// <param name="url">The url to append parameters</param> /// <param name="param">The parameters to add to the url</param> /// <returns>The url appended with the specified query</returns> public static string Add(string url, KeyValuePair<string, string> param) { return Add(url, new System.Collections.Specialized.NameValueCollection() { { param.Key, param.Value } }); } /// <summary> /// Updates the query string parameters to a url /// </summary> /// <param name="url">The url to update parameters</param> /// <param name="query">The parameters to update to the url</param> /// <returns>The url updated with the specified query</returns> public static string Update(string url, System.Collections.Specialized.NameValueCollection query) { return UpdateQuery(url, queryString => { CopyProps(query, queryString); }); } /// <summary> /// Updates the query string parameters to a url /// </summary> /// <param name="url">The url to update parameters</param> /// <param name="param">The parameters to update to the url</param> /// <returns>The url updated with the specified query</returns> public static string Update(string url, KeyValuePair<string, string> param) { return Update(url, new System.Collections.Specialized.NameValueCollection() { { param.Key, param.Value } }); } /// <summary> /// Removes the parameters with the matching keys from the query string of a url /// </summary> /// <param name="url">The url to remove parameters</param> /// <param name="keys">The parameter keys to remove from the url</param> /// <returns>The url with the parameters removed</returns> public static string Remove(string url, IEnumerable<string> keys) { return UpdateQuery(url, queryString => { foreach (var key in keys) { if (queryString.AllKeys.Contains(key)) { queryString.Remove(key); } } }); } /// <summary> /// Removes the parameter with the matching key from the query string of a url /// </summary> /// <param name="url">The url to remove a parameter</param> /// <param name="key">The parameter key to remove from the url</param> /// <returns>The url with the parameter removed</returns> public static string Remove(string url, string key) { return Remove(url, new string[]{ key }); } /// <summary> /// Removes all parameters from the query string of a url /// </summary> /// <param name="url">The url to clear parameters</param> /// <returns>The url with the parameters removed</returns> public static string Clear(string url) { return UpdateQuery(url, queryString => { queryString.Clear(); }); } /// <summary> /// Returns all parameters from the query string of a url /// </summary> /// <param name="url">The url to get parameters</param> /// <returns>The url parameters</returns> public static System.Collections.Specialized.NameValueCollection Get(string url) { System.Collections.Specialized.NameValueCollection result = null; UpdateQuery(url, queryString => { result = queryString; }); return result; } /// <summary> /// Sets the query string parameters to a url /// </summary> /// <param name="url">The url to set parameters</param> /// <param name="query">The parameters to set to the url</param> /// <returns>The url set with the specified query</returns> public static string Set(string url, System.Collections.Specialized.NameValueCollection query) { url = Clear(url); return Add(url, query); } /// <summary> /// Sets the query string parameters to a url /// </summary> /// <param name="url">The url to set parameters</param> /// <param name="param">The parameters to set to the url</param> /// <returns>The url set with the specified query</returns> public static string Set(string url, KeyValuePair<string, string> param) { return Set(url, new System.Collections.Specialized.NameValueCollection() { { param.Key, param.Value } }); } private static void CopyProps(System.Collections.Specialized.NameValueCollection source, System.Collections.Specialized.NameValueCollection destination) { foreach (string key in source) { destination[key] = source[key]; } } private static string UpdateQuery(string url, Action<System.Collections.Specialized.NameValueCollection> modifyQuery) { var uriBuilder = new System.UriBuilder(url); var query = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query); modifyQuery(query); uriBuilder.Query = query.ToString(); return uriBuilder.Uri.ToString(); } } }// http://programmingnotes.org/ |
10. 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 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 10, 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 { // Declare url var url = "http://programmingnotes.org/"; // Add single key value parameter to the url var result = Utils.HttpParams.Add(url, new KeyValuePair<string, string>("ids", "1987")); // Display result Display(result); Display(""); // Declare url var url2 = "http://programmingnotes.org/?ids=1987,1991&names=Kenneth,Jennifer"; // Add multiple key value parameters to the url var addition = new System.Collections.Specialized.NameValueCollection() { {"ids", "2010"}, {"ids", "2019"}, {"names", "Lynn"}, {"names", "Sole"} }; // Update the url var result2 = Utils.HttpParams.Add(url2, addition); // Display result Display(result2); Display(""); // Declare url var url3 = "http://programmingnotes.org/?ids=1987,1991&names=Kenneth,Jennifer"; // Remove single parameter from the url var result3 = Utils.HttpParams.Remove(url3, "names"); // Display result Display(result3); Display(""); // Declare url var url4 = "http://programmingnotes.org/?ids=1987,1991&names=Kenneth,Jennifer"; // Remove multiple parameters from the url var result4 = Utils.HttpParams.Remove(url4, new string[] { "ids", "names" }); // Display result Display(result4); Display(""); // Declare url var url5 = "http://programmingnotes.org/?ids=1987,1991&names=Kenneth,Jennifer"; // Remove multiple parameters from the url var result5 = Utils.HttpParams.Clear(url5); // Display result Display(result5); Display(""); // Declare url var url6 = "http://programmingnotes.org/?ids=1987,1991&names=Kenneth,Jennifer"; // Get parameters from the url var result6 = Utils.HttpParams.Get(url6); // Display result foreach (string key in result6) { Display($"Parameter: {key}, Value: {result6[key]}"); } Display(""); // Declare url var url7 = "http://programmingnotes.org/?ids=1987"; // Update single key value parameter to the url var result7 = Utils.HttpParams.Update(url7, new KeyValuePair<string, string>("ids", "1991")); // Display result Display(result7); Display(""); // Declare url var url8 = "http://programmingnotes.org/?ids=1987&names=Kenneth"; // Update multiple key value parameters to the url var addition8 = new System.Collections.Specialized.NameValueCollection() { {"ids", "1991"}, {"ids", "2019"}, {"names", "Jennifer"}, {"names", "Sole"} }; // Update the url var result8 = Utils.HttpParams.Update(url8, addition8); // Display result Display(result8); Display(""); // Declare url var url9 = "http://programmingnotes.org/?ids=1987&names=Kenneth"; // Set multiple key value parameters to the url var addition9 = new System.Collections.Specialized.NameValueCollection() { {"ids", "1991"}, {"ids", "2010"}, {"ids", "2019"}, {"names", "Jennifer"}, {"names", "Lynn"}, {"names", "Sole"} }; // Update the url var result9 = Utils.HttpParams.Set(url9, addition9); // Display result Display(result9); } 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 Serialize & Deserialize JSON Using C#
The following is a module with functions which demonstrates how to serialize and deserialize Json using C#.
The following generic functions use Newtonsoft.Json to serialize and deserialize an object.
Note: To use the functions in this module, make sure you have the ‘Newtonsoft.Json‘ package installed 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 ‘Manage NuGet Packages….‘, then type ‘Newtonsoft.Json‘ in the search box, and install the package titled Newtonsoft.Json in the results Tab.
Note: Don’t forget to include the ‘Utils Namespace‘ before running the examples!
1. Serialize – Integer Array
The example below demonstrates the use of ‘Utils.Json.Serialize‘ to serialize an integer array to Json.
The optional function parameter allows you to specify the Newtonsoft.Json.JsonSerializerSettings.
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 |
// Serialize - Integer Array // Declare array of integers var numbers = new int[] { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; // Optional: Create the JsonSerializerSettings with optional settings. var settings = new Newtonsoft.Json.JsonSerializerSettings() { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }; // Serialize to Json var numbersJson = Utils.Json.Serialize(numbers); // Display Json Console.WriteLine(numbersJson); // expected output: /* [ 1987, 19, 22, 2009, 2019, 1991, 28, 31 ] */ |
2. Serialize – String List
The example below demonstrates the use of ‘Utils.Json.Serialize‘ to serialize a list of strings to Json.
The optional function parameter allows you to specify the Newtonsoft.Json.JsonSerializerSettings.
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 |
// Serialize - String List // Declare list of strings var names = new List<string>() { "Kenneth", "Jennifer", "Lynn", "Sole" }; // Serialize to Json var namesJson = Utils.Json.Serialize(names); // Display Json Console.WriteLine(namesJson); // expected output: /* [ "Kenneth", "Jennifer", "Lynn", "Sole" ] */ |
3. Serialize – Custom Object List
The example below demonstrates the use of ‘Utils.Json.Serialize‘ to serialize a list of custom objects to Json.
The optional function parameter allows you to specify the Newtonsoft.Json.JsonSerializerSettings.
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 |
// Serialize - Custom Object List public class Part { public string PartName { get; set; } public int PartId { get; set; } } // Declare list of objects 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 } }; // Serialize to Json var partsJson = Utils.Json.Serialize(parts); // Display Json Console.WriteLine(partsJson); // expected output: /* [ { "PartName": "crank arm", "PartId": 1234 }, { "PartName": "chain ring", "PartId": 1334 }, { "PartName": "regular seat", "PartId": 1434 }, { "PartName": "banana seat", "PartId": 1444 }, { "PartName": "cassette", "PartId": 1534 }, { "PartName": "shift lever", "PartId": 1634 } ] */ |
4. Deserialize – Integer Array
The example below demonstrates the use of ‘Utils.Json.Deserialize‘ to deserialize Json to an integer array.
The optional function parameter allows you to specify the Newtonsoft.Json.JsonSerializerSettings.
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 |
// Deserialize - Integer Array // Declare Json array of integers var numbersJson = @" [ 1987, 19, 22, 2009, 2019, 1991, 28, 31 ] "; // Optional: Create the JsonSerializerSettings with optional settings. var settings = new Newtonsoft.Json.JsonSerializerSettings() { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }; // Deserialize from Json to specified type var numbers = Utils.Json.Deserialize<int[]>(numbersJson); // Display the items foreach (var item in numbers) { Console.WriteLine($"{item}"); } // expected output: /* 1987 19 22 2009 2019 1991 28 31 */ |
5. Deserialize – String List
The example below demonstrates the use of ‘Utils.Json.Deserialize‘ to deserialize Json to a list of strings.
The optional function parameter allows you to specify the Newtonsoft.Json.JsonSerializerSettings.
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 |
// Deserialize - String List // Declare Json array of strings var namesJson = @" [ ""Kenneth"", ""Jennifer"", ""Lynn"", ""Sole"" ] "; // Deserialize from Json to specified type var names = Utils.Json.Deserialize<List<string>>(namesJson); // Display the items foreach (var item in names) { Console.WriteLine($"{item}"); } // expected output: /* Kenneth Jennifer Lynn Sole */ |
6. Deserialize – Custom Object List
The example below demonstrates the use of ‘Utils.Json.Deserialize‘ to deserialize Json to a list of objects.
The optional function parameter allows you to specify the Newtonsoft.Json.JsonSerializerSettings.
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 |
// Deserialize - Custom Object List public class Part { public string PartName { get; set; } public int PartId { get; set; } } // Declare Json array of objects var partsJson = @" [ { ""PartName"": ""crank arm"", ""PartId"": 1234 }, { ""PartName"": ""chain ring"", ""PartId"": 1334 }, { ""PartName"": ""regular seat"", ""PartId"": 1434 }, { ""PartName"": ""banana seat"", ""PartId"": 1444 }, { ""PartName"": ""cassette"", ""PartId"": 1534 }, { ""PartName"": ""shift lever"", ""PartId"": 1634 } ] "; // Deserialize from Json to specified type var parts = Utils.Json.Deserialize<List<Part>>(partsJson); // Display the items foreach (var item in parts) { Console.WriteLine($"{item.PartId} - {item.PartName}"); } // expected output: /* 1234 - crank arm 1334 - chain ring 1434 - regular seat 1444 - banana seat 1534 - cassette 1634 - shift lever */ |
7. 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 10, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Json { /// <summary> /// Serializes the specified value to Json /// </summary> /// <param name="value">The value to serialize</param> /// <param name="settings">The Newtonsoft.Json.JsonSerializerSettings used to serialize the object</param> /// <returns>The value serialized to Json</returns> public static string Serialize(object value , Newtonsoft.Json.JsonSerializerSettings settings = null) { if (settings == null) { settings = GetDefaultSettings(); } return Newtonsoft.Json.JsonConvert.SerializeObject(value, settings); } /// <summary> /// Deserializes the specified value from Json to Object T /// </summary> /// <param name="value">The value to deserialize</param> /// <param name="settings">The Newtonsoft.Json.JsonSerializerSettings used to deserialize the object</param> /// <returns>The value deserialized to Object T</returns> public static T Deserialize<T>(string value , Newtonsoft.Json.JsonSerializerSettings settings = null) { if (settings == null) { settings = GetDefaultSettings(); } return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value, settings); } private static Newtonsoft.Json.JsonSerializerSettings GetDefaultSettings() { var settings = new Newtonsoft.Json.JsonSerializerSettings() { Formatting = Newtonsoft.Json.Formatting.Indented }; return settings; } } }// http://programmingnotes.org/ |
8. 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 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 10, 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 { public class Part { public string PartName { get; set; } public int PartId { get; set; } } static void Main(string[] args) { try { // Declare array of integers var numbers = new int[] { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; // Optional: Create the JsonSerializerSettings with optional settings. var settings = new Newtonsoft.Json.JsonSerializerSettings() { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }; // Serialize to Json var numbersJson = Utils.Json.Serialize(numbers); // Display Json Display(numbersJson); Display(""); // Declare list of strings var names = new List<string>() { "Kenneth", "Jennifer", "Lynn", "Sole" }; // Serialize to Json var namesJson = Utils.Json.Serialize(names); // Display Json Display(namesJson); Display(""); // Declare list of objects 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 } }; // Serialize to Json var partsJson = Utils.Json.Serialize(parts); // Display Json Display(partsJson); Display(""); // Declare Json array of integers var numbersJsonTest = @" [ 1987, 19, 22, 2009, 2019, 1991, 28, 31 ] "; // Deserialize from Json to specified type var numbersTest = Utils.Json.Deserialize<int[]>(numbersJsonTest); // Display the items foreach (var item in numbersTest) { Display($"{item}"); } Display(""); // Declare Json array of strings var namesJsonTest = @" [ ""Kenneth"", ""Jennifer"", ""Lynn"", ""Sole"" ] "; // Deserialize from Json to specified type var namesTest = Utils.Json.Deserialize<List<string>>(namesJsonTest); // Display the items foreach (var item in namesTest) { Display($"{item}"); } Display(""); // Declare Json array of objects var partsJsonTest = @" [ { ""PartName"": ""crank arm"", ""PartId"": 1234 }, { ""PartName"": ""chain ring"", ""PartId"": 1334 }, { ""PartName"": ""regular seat"", ""PartId"": 1434 }, { ""PartName"": ""banana seat"", ""PartId"": 1444 }, { ""PartName"": ""cassette"", ""PartId"": 1534 }, { ""PartName"": ""shift lever"", ""PartId"": 1634 } ] "; // Deserialize from Json to specified type var partsTest = Utils.Json.Deserialize<List<Part>>(partsJsonTest); // Display the items foreach (var item in partsTest) { 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# || How To Serialize & Deserialize XML Using C#
The following is a module with functions which demonstrates how to serialize and deserialize XML using C#.
The following generic functions use System.Xml.Serialization to serialize and deserialize an object.
Note: Don’t forget to include the ‘Utils Namespace‘ before running the examples!
1. Serialize – Integer Array
The example below demonstrates the use of ‘Utils.Xml.Serialize‘ to serialize an integer array to xml.
The optional function parameter allows you to specify the System.Xml.Serialization.XmlRootAttribute.
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 |
// Serialize - Integer Array // Declare array of integers var numbers = new int[] { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; // Optional: Create an XmlRootAttribute overloaded constructor and set its namespace. var myXmlRootAttribute = new System.Xml.Serialization.XmlRootAttribute("OverriddenRootElementName") { Namespace = "http://www.microsoft.com" }; // Serialize to XML var numbersXml = Utils.Xml.Serialize(numbers); // Display XML Console.WriteLine(numbersXml); // expected output: /* <?xml version="1.0"?> <ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <int>1987</int> <int>19</int> <int>22</int> <int>2009</int> <int>2019</int> <int>1991</int> <int>28</int> <int>31</int> </ArrayOfInt> */ |
2. Serialize – String List
The example below demonstrates the use of ‘Utils.Xml.Serialize‘ to serialize a list of strings to xml.
The optional function parameter allows you to specify the System.Xml.Serialization.XmlRootAttribute.
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 |
// Serialize - String List // Declare list of strings var names = new List<string>() { "Kenneth", "Jennifer", "Lynn", "Sole" }; // Serialize to XML var namesXml = Utils.Xml.Serialize(names); // Display XML Console.WriteLine(namesXml); // expected output: /* <?xml version="1.0"?> <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <string>Kenneth</string> <string>Jennifer</string> <string>Lynn</string> <string>Sole</string> </ArrayOfString> */ |
3. Serialize – Custom Object List
The example below demonstrates the use of ‘Utils.Xml.Serialize‘ to serialize a list of custom objects to xml.
The optional function parameter allows you to specify the System.Xml.Serialization.XmlRootAttribute.
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 |
// Serialize - Custom Object List [System.Xml.Serialization.XmlRoot(ElementName = "Inventory")] // Optional public class Inventory { [System.Xml.Serialization.XmlArray(ElementName = "Parts")] // Optional public List<Part> Parts { get; set; } } public class Part { [System.Xml.Serialization.XmlElement(ElementName = "PartName")] // Optional public string PartName { get; set; } [System.Xml.Serialization.XmlElement(ElementName = "PartId")] // Optional public int PartId { get; set; } } // Declare list of objects var inventory = new Inventory() { 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 } } }; // Serialize to XML var inventoryXml = Utils.Xml.Serialize(inventory); // Display XML Console.WriteLine(inventoryXml); // expected output: /* <?xml version="1.0"?> <Inventory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Parts> <Part> <PartName>crank arm</PartName> <PartId>1234</PartId> </Part> <Part> <PartName>chain ring</PartName> <PartId>1334</PartId> </Part> <Part> <PartName>regular seat</PartName> <PartId>1434</PartId> </Part> <Part> <PartName>banana seat</PartName> <PartId>1444</PartId> </Part> <Part> <PartName>cassette</PartName> <PartId>1534</PartId> </Part> <Part> <PartName>shift lever</PartName> <PartId>1634</PartId> </Part> </Parts> </Inventory> */ |
4. Deserialize – Integer Array
The example below demonstrates the use of ‘Utils.Xml.Deserialize‘ to deserialize xml to an integer array.
The optional function parameter allows you to specify the System.Xml.Serialization.XmlRootAttribute.
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 |
// Deserialize - Integer Array // Declare Xml array of integers var numbersXml = $@"<?xml version=""1.0""?> <ArrayOfInt xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <int>1987</int> <int>19</int> <int>22</int> <int>2009</int> <int>2019</int> <int>1991</int> <int>28</int> <int>31</int> </ArrayOfInt> "; // Optional: Create an XmlRootAttribute overloaded constructor and set its namespace. var myXmlRootAttribute = new System.Xml.Serialization.XmlRootAttribute("OverriddenRootElementName") { Namespace = "http://www.microsoft.com" }; // Deserialize from XML to specified type var numbers = Utils.Xml.Deserialize<int[]>(numbersXml); // Display the items foreach (var item in numbers) { Console.WriteLine($"{item}"); } // expected output: /* 1987 19 22 2009 2019 1991 28 31 */ |
5. Deserialize – String List
The example below demonstrates the use of ‘Utils.Xml.Deserialize‘ to deserialize xml to a list of strings.
The optional function parameter allows you to specify the System.Xml.Serialization.XmlRootAttribute.
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 |
// Deserialize - String List // Declare Xml array of strings var namesXml = $@"<?xml version=""1.0""?> <ArrayOfString xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <string>Kenneth</string> <string>Jennifer</string> <string>Lynn</string> <string>Sole</string> </ArrayOfString> "; // Deserialize from XML to specified type var names = Utils.Xml.Deserialize<List<string>>(namesXml); // Display the items foreach (var item in names) { Console.WriteLine($"{item}"); } // expected output: /* Kenneth Jennifer Lynn Sole */ |
6. Deserialize – Custom Object List
The example below demonstrates the use of ‘Utils.Xml.Deserialize‘ to deserialize xml to a list of objects.
The optional function parameter allows you to specify the System.Xml.Serialization.XmlRootAttribute.
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 |
// Deserialize - Custom Object List [System.Xml.Serialization.XmlRoot(ElementName = "Inventory")] // Optional public class Inventory { [System.Xml.Serialization.XmlArray(ElementName = "Parts")] // Optional public List<Part> Parts { get; set; } } public class Part { [System.Xml.Serialization.XmlElement(ElementName = "PartName")] // Optional public string PartName { get; set; } [System.Xml.Serialization.XmlElement(ElementName = "PartId")] // Optional public int PartId { get; set; } } // Declare Xml array of objects var inventoryXml = $@"<?xml version=""1.0""?> <Inventory xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""> <Parts> <Part> <PartName>crank arm</PartName> <PartId>1234</PartId> </Part> <Part> <PartName>chain ring</PartName> <PartId>1334</PartId> </Part> <Part> <PartName>regular seat</PartName> <PartId>1434</PartId> </Part> <Part> <PartName>banana seat</PartName> <PartId>1444</PartId> </Part> <Part> <PartName>cassette</PartName> <PartId>1534</PartId> </Part> <Part> <PartName>shift lever</PartName> <PartId>1634</PartId> </Part> </Parts> </Inventory> "; // Deserialize from XML to specified type var inventory = Utils.Xml.Deserialize<Inventory>(inventoryXml); // Display the items foreach (var item in inventory.Parts) { Console.WriteLine($"{item.PartId} - {item.PartName}"); } // expected output: /* 1234 - crank arm 1334 - chain ring 1434 - regular seat 1444 - banana seat 1534 - cassette 1634 - shift lever */ |
7. 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 10, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Xml { /// <summary> /// Serializes the specified value to XML /// </summary> /// <param name="value">The value to serialize</param> /// <param name="root">The XmlRootAttribute that represents the XML root element</param> /// <returns>The value serialized to XML</returns> public static string Serialize<T>(T value , System.Xml.Serialization.XmlRootAttribute root = null) { var xml = string.Empty; var type = value != null ? value.GetType() : typeof(T); var serializer = new System.Xml.Serialization.XmlSerializer(type: type, root: root); using (var stream = new System.IO.MemoryStream()) { serializer.Serialize(stream, value); xml = GetStreamText(stream); } return xml; } /// <summary> /// Deserializes the specified value from XML to Object T /// </summary> /// <param name="value">The value to deserialize</param> /// <param name="root">The XmlRootAttribute that represents the XML root element</param> /// <returns>The value deserialized to Object T</returns> public static T Deserialize<T>(string value , System.Xml.Serialization.XmlRootAttribute root = null) { T obj = default; var serializer = new System.Xml.Serialization.XmlSerializer(type: typeof(T), root: root); using (var stringReader = new System.IO.StringReader(value)) { using (var xmlReader = System.Xml.XmlReader.Create(stringReader)) { obj = (T)serializer.Deserialize(xmlReader); } } return obj; } public static string GetStreamText(System.IO.Stream stream) { try { TryResetPosition(stream); var stmReader = new System.IO.StreamReader(stream); var text = stmReader.ReadToEnd(); return text; } catch { throw; } finally { TryResetPosition(stream); } } private static void TryResetPosition(System.IO.Stream stream) { if (stream.CanSeek) { stream.Position = 0; } } } }// http://programmingnotes.org/ |
8. 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 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 10, 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 { [System.Xml.Serialization.XmlRoot(ElementName = "Inventory")] // Optional public class Inventory { [System.Xml.Serialization.XmlArray(ElementName = "Parts")] // Optional public List<Part> Parts { get; set; } } public class Part { [System.Xml.Serialization.XmlElement(ElementName = "PartName")] // Optional public string PartName { get; set; } [System.Xml.Serialization.XmlElement(ElementName = "PartId")] // Optional public int PartId { get; set; } } static void Main(string[] args) { try { // Declare array of integers var numbers = new int[] { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; // Create an XmlRootAttribute overloaded constructor and set its namespace. var myXmlRootAttribute = new System.Xml.Serialization.XmlRootAttribute("OverriddenRootElementName") { Namespace = "http://www.microsoft.com" }; // Serialize to XML var numbersXml = Utils.Xml.Serialize(numbers); // Display XML Display(numbersXml); Display(""); // Declare list of strings var names = new List<string>() { "Kenneth", "Jennifer", "Lynn", "Sole" }; // Serialize to XML var namesXml = Utils.Xml.Serialize(names); // Display XML Display(namesXml); Display(""); // Declare list of objects var inventory = new Inventory() { 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 } } }; // Serialize to XML var inventoryXml = Utils.Xml.Serialize(inventory); // Display XML Display(inventoryXml); Display(""); // Declare Xml array of integers var numbersXmlTest = $@"<?xml version=""1.0""?> <ArrayOfInt xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <int>1987</int> <int>19</int> <int>22</int> <int>2009</int> <int>2019</int> <int>1991</int> <int>28</int> <int>31</int> </ArrayOfInt> "; // Deserialize from XML to specified type var numbersTest = Utils.Xml.Deserialize<int[]>(numbersXmlTest); // Display the items foreach (var item in numbersTest) { Display($"{item}"); } Display(""); // Declare Xml array of strings var namesXmlTest = $@"<?xml version=""1.0""?> <ArrayOfString xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <string>Kenneth</string> <string>Jennifer</string> <string>Lynn</string> <string>Sole</string> </ArrayOfString> "; // Deserialize from XML to specified type var namesTest = Utils.Xml.Deserialize<List<string>>(namesXmlTest); // Display the items foreach (var item in namesTest) { Display($"{item}"); } Display(""); // Declare Xml array of objects var inventoryXmlTest = $@"<?xml version=""1.0""?> <Inventory xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""> <Parts> <Part> <PartName>crank arm</PartName> <PartId>1234</PartId> </Part> <Part> <PartName>chain ring</PartName> <PartId>1334</PartId> </Part> <Part> <PartName>regular seat</PartName> <PartId>1434</PartId> </Part> <Part> <PartName>banana seat</PartName> <PartId>1444</PartId> </Part> <Part> <PartName>cassette</PartName> <PartId>1534</PartId> </Part> <Part> <PartName>shift lever</PartName> <PartId>1634</PartId> </Part> </Parts> </Inventory> "; // Deserialize from XML to specified type var inventoryTest = Utils.Xml.Deserialize<Inventory>(inventoryXmlTest); // Display the items foreach (var item in inventoryTest.Parts) { 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.