<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shehan Samarasinghe on Medium]]></title>
        <description><![CDATA[Stories by Shehan Samarasinghe on Medium]]></description>
        <link>https://medium.com/@shehan.s?source=rss-c92e64f643af------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bty9LdXp8uMuMvdlHQac5w.jpeg</url>
            <title>Stories by Shehan Samarasinghe on Medium</title>
            <link>https://medium.com/@shehan.s?source=rss-c92e64f643af------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 23:11:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shehan.s/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Events, Delegates, and Lambdas on .NET: What’s the Deal?]]></title>
            <link>https://medium.com/@shehan.s/events-delegates-and-lambdas-on-net-whats-the-deal-743387f8a29b?source=rss-c92e64f643af------2</link>
            <guid isPermaLink="false">https://medium.com/p/743387f8a29b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[microsoft]]></category>
            <dc:creator><![CDATA[Shehan Samarasinghe]]></dc:creator>
            <pubDate>Thu, 02 Jan 2025 17:01:32 GMT</pubDate>
            <atom:updated>2025-01-02T17:01:32.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>Events, Delegates, and Lambdas on .NET: What’s the Deal?</h3><h4><em>Boost Your .NET Skills with Events, Delegates, and Lambdas</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMRO_B2nLWt4CiCaPQaNVQ.jpeg" /></figure><h3>Introduction</h3><p>I have used .NET 8, C# 12, Visual Studio 2022 for demonstration purposes. In this article, we will strip away the complexity of events, event arguments, delegates and Lambdas and let’s find out how they fit together.</p><h3>Events, Event Handlers and Delegates?</h3><p>Certain app types heavily rely on events, delegates, and event handlers, such as desktop apps (WinForms), Blazor.NET, and console apps. While events are less common in web development, even an API can raise an event to update a database or Redis cache.</p><h4>Event:</h4><p>An event, such as a button click in a JavaScript browser or a dropdown selection in a desktop app, is a notification sent by an Event Raiser. Events trigger notifications from objects or end users. Events typically pass event data, commonly referred to as <strong>EventArgs</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*-gnSe3PNEeibi_1WLPCI0w.jpeg" /></figure><p>Without delegates events are pretty useless. Let’s delve deeper in the next section.</p><h4>Delegates:</h4><p>Delegates are key to making events work, acting like a pipeline between an event and its handler. Like a string between two tin cans, delegates transmit data (<strong>EventArgs</strong>) to handlers.</p><p>In C#, a delegate is like a connector that links events to their handlers, allowing them to communicate and work together in .NET applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5IW8BqGQmqq_8OVrhu_AQ.gif" /></figure><p>Delegates can be used without events, acting as function pointers, which will be explored in later chapters of the article. You can assign methods to a delegate and invoke them.</p><h4>Event Handlers:</h4><p>An event handler receives and processes data from a delegate. It may also accept parameters, such as the “<strong>Sender</strong>” and “<strong>EventArgs</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*xAlFoWiL1tu_tylEiZvK7g.jpeg" /><figcaption>Sample event handler for Windows Forms app</figcaption></figure><h3>Publisher Subscriber Pattern</h3><p>While events, event handlers, and delegates are fundamental concepts for enabling communication between objects, one of the most common patterns is the Publisher-Subscriber pattern.</p><h4>Publisher &amp; Subscriber:</h4><p>The publisher is an object that raises an event when something happens, and the subscriber responds by executing a specific method.</p><p>Think of the publisher as a newspaper company publishing articles and readers as subscribers who read them. Below is an example demonstrating the use of a custom event with a custom delegate.</p><pre>namespace Demo<br>{<br>    // Publisher class that raises events<br>    public class Publisher<br>    {<br>        // Define a custom delegate for the event<br>        public delegate void NotifyEventHandler(Guid notificationId, DateTime messageDateTime);<br><br>        // Declare an event based on the custom delegate<br>        public event NotifyEventHandler? OnNotifyPerformed;<br><br>        // Declare an event using the built-in EventHandler delegate<br>        public event EventHandler? OnNotifyCompleted;<br><br>        public void DoWork(int seconds)<br>        {<br>            // Simulate work for the given number of seconds<br>            for (int i = 0; i &lt; seconds; i++)<br>            {<br>                Thread.Sleep(1000);<br>                OnNotificationPerformed(Guid.NewGuid(), DateTime.Now); // Raise OnNotifyPerformed<br>            }<br><br>            // Raise OnNotifyCompleted when work is done<br>            OnNotificationCompleted();<br>        }<br><br>        // Method to invoke the OnNotifyPerformed event<br>        protected virtual void OnNotificationPerformed(Guid notificationId, DateTime messageDateTime)<br>        {<br>            OnNotifyPerformed?.Invoke(notificationId, messageDateTime);<br>        }<br><br>        // Method to invoke the OnNotifyCompleted event<br>        protected virtual void OnNotificationCompleted()<br>        {<br>            OnNotifyCompleted?.Invoke(this, EventArgs.Empty);<br>        }<br>    }<br><br>    // Subscriber class that handles events<br>    public class Subscriber<br>    {<br>        // Handler for the OnNotifyPerformed event<br>        public void HandleNotificationPerformed(Guid notificationId, DateTime messageDateTime)<br>        {<br>            Console.WriteLine($&quot;Subscriber received notification for: {notificationId} at {messageDateTime}.&quot;);<br>        }<br><br>        // Handler for the OnNotifyCompleted event<br>        public void HandleNotificationCompleted(object? sender, EventArgs e)<br>        {<br>            Console.WriteLine(&quot;\nWork has completed&quot;);<br>        }<br>    }<br><br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            // Create instances of Publisher and Subscriber<br>            var publisher = new Publisher();<br>            var subscriber = new Subscriber();<br><br>            // Subscribe to the events<br>            publisher.OnNotifyPerformed += subscriber.HandleNotificationPerformed;<br>            publisher.OnNotifyCompleted += subscriber.HandleNotificationCompleted;<br><br>            // Trigger the events by performing work<br>            publisher.DoWork(3);<br><br>            // Unsubscribe from the events<br>            publisher.OnNotifyPerformed -= subscriber.HandleNotificationPerformed;<br>            publisher.OnNotifyCompleted -= subscriber.HandleNotificationCompleted;<br><br>            /*<br>             Sample Output:<br>                Subscriber received notification for: 790a2dd0-41ac-4219-bc45-1ff98d63cdc1 at 12/24/2024 3:54:14 PM.<br>                Subscriber received notification for: b83b892e-a64b-4976-960c-96e5f405098f at 12/24/2024 3:54:15 PM.<br>                Subscriber received notification for: 357c006f-0255-4e75-b26b-0c8a44b14f46 at 12/24/2024 3:54:16 PM.<br><br>                Work has completed<br>             */<br>        }<br>    }<br>}</pre><p>Above implementation, we have passed 2 parameters “notificationId” and “messageDateTime” to the subscriber via delegate. But we can optimize this pattern using .NET provided <strong>EventArgs</strong> class and <strong>EventHandler&lt;T&gt;</strong> generic class.</p><h4>Use EventHandler&lt;T&gt; In-Built Delegate:</h4><p>.NET provides the generic EventHandler&lt;T&gt;, eliminating the need to explicitly create delegate instances. Instead of passing inline parameters, you can define a custom event argument class.</p><pre>namespace Demo<br>{<br>    // Initiate custom event argument class.<br>    public class NotificationEventArgs : EventArgs<br>    {<br>        public Guid NotificationId { get; }<br><br>        public DateTime MessageDateTime { get; }<br><br>        public NotificationEventArgs(Guid notificationId, DateTime messageDateTime) =&gt;<br>            (NotificationId, MessageDateTime) = (notificationId, messageDateTime);<br>    }<br><br>    // Publisher class that raises events<br>    public class Publisher<br>    {<br>        // Declare an event based on the built-in generic delegate<br>        public event EventHandler&lt;NotificationEventArgs&gt;? OnNotifyPerformed;<br><br>        // Declare an event using the built-in EventHandler delegate<br>        public event EventHandler? OnNotifyCompleted;<br><br>        public void DoWork(int seconds)<br>        {<br>            // Simulate work for the given number of seconds<br>            for (int i = 0; i &lt; seconds; i++)<br>            {<br>                Thread.Sleep(1000);<br>                OnNotificationPerformed(this, new NotificationEventArgs(Guid.NewGuid(), DateTime.Now)); // Raise OnNotifyPerformed<br>            }<br><br>            // Raise OnNotifyCompleted when work is done<br>            OnNotificationCompleted();<br>        }<br><br>        // Method to invoke the OnNotifyPerformed event<br>        protected virtual void OnNotificationPerformed(object sender, NotificationEventArgs e)<br>        {<br>            OnNotifyPerformed?.Invoke(sender, e);<br>        }<br><br>        // Method to invoke the OnNotifyCompleted event<br>        protected virtual void OnNotificationCompleted()<br>        {<br>            OnNotifyCompleted?.Invoke(this, EventArgs.Empty);<br>        }<br>    }<br><br>    // Subscriber class that handles events<br>    public class Subscriber<br>    {<br>        // Handler for the OnNotifyPerformed event<br>        public void HandleNotificationPerformed(object? sender, NotificationEventArgs e)<br>        {<br>            Console.WriteLine($&quot;Subscriber received notification for: {e.NotificationId} at {e.MessageDateTime}.&quot;);<br>        }<br><br>        // Handler for the OnNotifyCompleted event<br>        public void HandleNotificationCompleted(object? sender, EventArgs e)<br>        {<br>            Console.WriteLine(&quot;\nWork has completed&quot;);<br>        }<br>    }<br><br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            // Create instances of Publisher and Subscriber<br>            var publisher = new Publisher();<br>            var subscriber = new Subscriber();<br><br>            // Subscribe to the events<br>            publisher.OnNotifyPerformed += subscriber.HandleNotificationPerformed;<br>            publisher.OnNotifyCompleted += subscriber.HandleNotificationCompleted;<br><br>            // Trigger the events by performing work<br>            publisher.DoWork(3);<br><br>            // Unsubscribe from the events<br>            publisher.OnNotifyPerformed -= subscriber.HandleNotificationPerformed;<br>            publisher.OnNotifyCompleted -= subscriber.HandleNotificationCompleted;<br>        }<br>    }<br>}</pre><h3>Lambdas, Action&lt;T&gt; &amp; Func&lt;T, TResult&gt;</h3><p>Lambdas in C# are simple, anonymous functions that make your code more concise and readable. Action&lt;T&gt; is a delegate used for methods that don’t return a value, while Func&lt;T, TResult&gt; is for methods that return a value.</p><h4>Lambdas and Delegates:</h4><p>In the previous code example, we created a separate method in the subscriber class and added it to the EventHandler delegate as shown below.</p><pre>// Subscribe to the events<br>publisher.OnNotifyPerformed += subscriber.HandleNotificationPerformed;<br>publisher.OnNotifyCompleted += subscriber.HandleNotificationCompleted;</pre><p>We can implement it below using lambdas. If you’ve worked with lists or arrays, you’ve likely used lambdas to filter or manipulate data.</p><pre>publisher.OnNotifyPerformed += (s, e) =&gt;<br>{<br>    // We don’t need {} here since the method body is a one-liner.<br>    // I included it for demonstration purposes.<br>    Console.WriteLine($&quot;Subscriber received notification for: {e.NotificationId} at {e.MessageDateTime}.&quot;);<br>};<br><br>publisher.OnNotifyCompleted += (s, e) =&gt; Console.WriteLine(&quot;\nWork has completed&quot;);</pre><ul><li>“(s, e)” are parameters</li><li>- “=&gt;” separates the parameters from the body</li><li>“<strong>Console.WriteLine()</strong>” is the expression executed when the Lambda is called.</li></ul><p>In above code snippet, we directly assign a lambda to the delegate. A lambda expression can be assigned to any delegate.</p><p>Depending on the method body size, we can choose the approach. For small code snippets, lambdas are more convenient than creating a new method.</p><h4>Action&lt;T&gt; and Func&lt;T, TResult&gt;:</h4><p>As we know, delegates are nothing more than pipelines or function pointers.</p><ul><li><strong>Action&lt;T&gt;</strong> accepts one or more parameters and returns no value (<strong>void</strong>).</li><li><strong>Func&lt;T, TResult&gt;</strong> is similar to <strong>Action</strong>, but it returns a value of type <strong>TResult</strong>.</li></ul><p>While there are many ways to use Delegates, Actions, and Funcs, let’s combine them all in one example.</p><pre>namespace Demo<br>{<br>    // Delegate that takes two integers and returns an integer<br>    public delegate int NumberDelegate(int x, int y);<br><br>    public class ProcessNumbers<br>    {<br>        // Method that processes a delegate<br>        public void ProcessDelegate(int x, int y, NumberDelegate del)<br>        {<br>            // Invoke the delegate and store the result<br>            var result = del(x, y);<br>            Console.WriteLine($&quot;Delegate has been processed: {result}&quot;);<br>        }<br><br>        // Method that processes an Action (no return value)<br>        public void ProcessAction(int x, int y, Action&lt;int, int&gt; action)<br>        {<br>            // Invoke the action<br>            action(x, y);<br>            Console.WriteLine(&quot;Action has been processed&quot;);<br>        }<br><br>        // Method that processes a Func (returns a value as &#39;result&#39;)<br>        public void ProcessFunc(int x, int y, Func&lt;int, int, int&gt; func)<br>        {<br>            // Invoke the func and store the result<br>            var result = func(x, y);<br>            Console.WriteLine($&quot;Func has been processed: {result}&quot;);<br>        }<br>    }<br><br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            // Create an instance of the ProcessNumbers class<br>            var processNumbers = new ProcessNumbers();<br><br>            // Create a delegate for adding and multiplying numbers<br>            NumberDelegate addNumbersDelegate = (x, y) =&gt; x + y;<br>            NumberDelegate multiplyNumbersDelegate = (x, y) =&gt; x * y;<br><br>            // Process the delegate (addition and multiplication)<br>            processNumbers.ProcessDelegate(5, 10, addNumbersDelegate);<br>            processNumbers.ProcessDelegate(5, 10, multiplyNumbersDelegate);<br>            Console.WriteLine();<br><br>            // Create Actions for adding and multiplying numbers (no return value)<br>            Action&lt;int, int&gt; addNumbersAction = (x, y) =&gt; Console.WriteLine(x + y);<br>            Action&lt;int, int&gt; multiplyNumbersAction = (x, y) =&gt; Console.WriteLine(x * y);<br><br>            // Process the actions (addition and multiplication)<br>            processNumbers.ProcessAction(5, 10, addNumbersAction);<br>            processNumbers.ProcessAction(5, 10, multiplyNumbersAction);<br>            Console.WriteLine();<br><br>            // Create Funcs for adding and multiplying numbers (returns a result)<br>            Func&lt;int, int, int&gt; addNumbersFunc = (x, y) =&gt; x + y;<br>            Func&lt;int, int, int&gt; multiplyNumbersFunc = (x, y) =&gt; x * y;<br><br>            // Process the funcs (addition and multiplication)<br>            processNumbers.ProcessFunc(5, 10, addNumbersFunc);<br>            processNumbers.ProcessFunc(5, 10, multiplyNumbersFunc);<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*e9dbDWyN7ngsIbiI1kD4dA.jpeg" /><figcaption>Console output</figcaption></figure><h3>Conclusion</h3><p>To wrap up, events, delegates, and lambdas are key tools in C# for connecting application parts. .NET also offers built-in delegate types like <strong>Action&lt;T&gt;</strong> and <strong>Func&lt;T, TResult&gt;</strong>, which can be useful in many cases. Using these tools effectively leads to cleaner and more maintainable code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=743387f8a29b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamline JSON Handling in .NET C#: Best Practices and Tips]]></title>
            <link>https://medium.com/@shehan.s/streamline-json-handling-in-net-c-best-practices-and-tips-14680bede552?source=rss-c92e64f643af------2</link>
            <guid isPermaLink="false">https://medium.com/p/14680bede552</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Shehan Samarasinghe]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 15:51:34 GMT</pubDate>
            <atom:updated>2024-12-18T15:51:34.115Z</atom:updated>
            <content:encoded><![CDATA[<h3>Streamline JSON Handling in .NET C#: Best Practices and Tips</h3><h4>Master JSON in .NET C# to simplify your code and boost performance.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCBBe53_oOCDE254ze9icw.png" /></figure><h3>Introduction</h3><p>The code examples in this article are fully applicable to .NET 6/7/8/9, C# 10/11/12/13, Visual Studio 2022 and I have used also VS Code 1.96. I believe most of developers are familiar with JSON and let’s uncover some useful tips.</p><h3>JSON?</h3><p>JSON stands for “JavaScript Object Notation,” a lightweight, text-based format for data exchange. It is language-independent and stores data using key-value pairs with various <a href="https://www.json.org/json-en.html">data types</a>, including string, number, object, array, boolean, and null.</p><p>In object-oriented languages like C#, data is often in object form. JSON serializes objects into a text format for easy transmission and storage, and can be easily deserialized back into objects.</p><h3>Marshalling and Unmarshalling?</h3><p>Don’t familiar? How about serialization and deserialization? They basically <a href="https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/overview">refer</a> to the same thing.</p><ul><li>Serialization — Converts an object to a format (like JSON or binary) for storage or transmission</li><li>Deserialization — Converts the stored or transmitted format back into an object. In .NET, a POCO (Plain Old CLR Object) is created in the .NET runtime to hold data.</li></ul><h3>System.Text.Json or Newtonsoft.Json?</h3><p><strong>Newtonsoft.Json</strong>, the most downloaded NuGet package, is a third-party JSON library. Microsoft developed <strong>System.Text.Json</strong> for better performance and native support. If you are considering migrating from <strong>Newtonsoft.Json</strong> to <strong>System.Text.Json</strong>, it should not be too difficult. See below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_cNOal7gmdfoUWPMsZaIg.jpeg" /></figure><p>However, this <a href="https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/migrate-from-newtonsoft?pivots=dotnet-8-0">article</a> is for the native library <strong>System.Text.Json</strong>. I will use the following classes in my console app (Employee.cs) for the demonstration.</p><pre>public class Employee<br>{<br>    public string? Name { get; set; }<br>    public int Age { get; set; }<br>    public bool IsActive { get; set; }<br>    public DateTime DateJoined { get; set; }<br>    public string[]? Tags { get; set; }<br>    public Address? Address { get; set; }<br>}<br><br>public class Address<br>{<br>    public string? City { get; set; }<br>    public string? Country { get; set; }<br>}<br><br>public class Post<br>{<br>    public int Id { get; set; }<br>    public string? Body { get; set; }<br>    public string? Title { get; set; }<br>    public int UserId { get; set; }<br>}</pre><h3>Default Serialization Behavior</h3><p>There are several important points you need to consider regarding the default serialization behavior.</p><ul><li>The default encoder escapes non-ASCII characters outside the 0–127 range.</li><li>All public properties in a class are serialized.</li><li>JSON names match the .NET naming conventions.</li><li>Circular references cause exceptions.</li><li>The JSON string is minified.</li></ul><h3>Serialization</h3><p>We can break down the serialization operations as follows.</p><ol><li>Serialization to string — Converts an object to a string format (e.g. JSON)</li><li>Serialization using generics — Serializes objects of any type using generics</li><li>1. Serialization to a file — Saves a serialized object to a file</li><li>Serialization with collections — Serializes collections like lists or array</li><li>1. Async serialization — Performs serialization asynchronously, without blocking</li></ol><p>The .NET Framework provides several overloads that are likely to meet your needs. For more details, please refer to the official documentation <a href="https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer.serialize?view=net-9.0">here</a>.</p><h4>Serialization to String (with collection), Generics and File:</h4><p>These cases are quite straightforward. See below.</p><pre>using System.Text.Json;<br><br>var employee = new Employee<br>{<br>    Name = &quot;Jhon Smith&quot;,<br>    Age = 30,<br>    IsActive = true,<br>    DateJoined = DateTime.Parse(&quot;2024-12-10&quot;), // collection<br>    Tags = [&quot;manager&quot;, &quot;hr&quot;, &quot;operation&quot;],<br>    Address = new Address //object<br>    {<br>        City = &quot;New York&quot;,<br>        Country = &quot;USA&quot;<br>    }<br>};<br><br>// 1. Basic Serialization<br>// 4. Serialization with collections<br>var jsonString = JsonSerializer.Serialize(employee);<br>Console.WriteLine(jsonString);<br><br>// 2. Serialziation with generics.<br>var jsonStringGenerics = JsonSerializer.Serialize&lt;Employee&gt;(employee);<br>Console.WriteLine(jsonStringGenerics);<br><br>// 3. Serialization to a file<br>var filePath = $&quot;D:\\Employee_{Guid.NewGuid()}.json&quot;;<br>File.WriteAllText(filePath, jsonStringGenerics);<br>Console.WriteLine(File.Exists(filePath));</pre><h4>Async Serialization:</h4><p>When working with large JSON files and strings, you may want to consider asynchronous serialization, which helps execute serialization without blocking the main thread.</p><pre>using System.Text.Json;<br><br>var employee = new Employee<br>{<br>    Name = &quot;Jhon Smith&quot;,<br>    Age = 30,<br>    IsActive = true,<br>    DateJoined = DateTime.Parse(&quot;2024-12-10&quot;), // collection<br>    Tags = [&quot;namager&quot;, &quot;hr&quot;, &quot;operation&quot;],<br>    Address = new Address //object<br>    {<br>        City = &quot;New York&quot;,<br>        Country = &quot;USA&quot;<br>    }<br>};<br><br>var filePath = $&quot;D:\\Employee_{Guid.NewGuid()}.json&quot;;<br>using FileStream stream = File.Create(filePath);<br><br>// 5. Async serialization.<br>await JsonSerializer.SerializeAsync(stream, employee);<br><br>await stream.DisposeAsync();<br>Console.WriteLine(&quot;debugger here&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*naW-Iy4M57HxVW1iYIRUhg.jpeg" /><figcaption>VS Code debugger call stack</figcaption></figure><h3>Default Deserialization Behavior</h3><p>There are several important points you need to consider regarding the default deserialization behavior.</p><ul><li>Property name matching is case‑sensitive.</li><li>The serializer ignores constructors that are not public</li><li>Enums are treated as numeric values during deserialization</li><li>JSON containing comments or trailing commas will result errors</li><li>And the default maximum depth for nested objects is 64</li></ul><h3>Deserialization</h3><p>There are basic deserialization scenarios that are quite common.</p><ol><li>1. Deserialize from a string</li><li>Deserialize from a file</li><li>Async deserialization</li></ol><p>For more details, please refer the documentation <a href="https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer.deserialize?view=net-9.0">here</a>. Refer to the examples below for a demonstration of the scenarios described above.</p><pre>using System.Text.Json;<br><br>var jsonString = @&quot;{<br>   &quot;&quot;Name&quot;&quot;:&quot;&quot;Jhon Smith&quot;&quot;,<br>   &quot;&quot;Age&quot;&quot;:30,<br>   &quot;&quot;IsActive&quot;&quot;:true,<br>   &quot;&quot;DateJoined&quot;&quot;:&quot;&quot;2024-12-10T00:00:00&quot;&quot;,<br>   &quot;&quot;Tags&quot;&quot;:[<br>      &quot;&quot;namager&quot;&quot;,<br>      &quot;&quot;hr&quot;&quot;,<br>      &quot;&quot;operation&quot;&quot;<br>   ],<br>   &quot;&quot;Address&quot;&quot;:{<br>      &quot;&quot;City&quot;&quot;:&quot;&quot;New York&quot;&quot;,<br>      &quot;&quot;Country&quot;&quot;:&quot;&quot;USA&quot;&quot;<br>   }<br>}&quot;;<br><br>var filePath = &quot;path\\to\\your\file\\Employee.json&quot;;<br><br>// 1. Deserialize from a string<br>var employeeFromString = JsonSerializer.Deserialize&lt;Employee&gt;(jsonString);<br><br>if (File.Exists(filePath))<br>{<br>    // 2. Deserialize from a file<br>    string jsonContent = File.ReadAllText(filePath); // Read the JSON file<br>    var employeeFromFile = JsonSerializer.Deserialize&lt;Employee&gt;(jsonContent);<br><br>    // 3. Async deserialize<br>    await using FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);<br>    var employeeAsync = await JsonSerializer.DeserializeAsync&lt;Employee&gt;(fileStream);<br>    await fileStream.DisposeAsync();<br>}</pre><h3>HTTP Client Extension Methods</h3><p>JSON is widely used for API requests/responses across devices over networks. The <strong>System.Net.Http.Json</strong> namespace provides <a href="https://learn.microsoft.com/en-us/dotnet/api/system.net.http.json.httpclientjsonextensions?view=net-9.0">HttpClientJsonExtensions</a> for sending/receiving JSON over HTTP and <a href="https://learn.microsoft.com/en-us/dotnet/api/system.net.http.json.httpcontentjsonextensions?view=net-9.0">HttpContentJsonExtensions</a> for parsing HTTP content as JSON efficiently. In the example below, I have demonstrated the use of GET and POST methods with an open JSON API.</p><pre>using System.Net.Http.Json;<br><br>var client = new HttpClient();<br>client.BaseAddress = new Uri(&quot;https://jsonplaceholder.typicode.com/&quot;);<br><br>// GET post - /posts/1<br>var post = await client.GetFromJsonAsync&lt;Post&gt;(&quot;posts/1&quot;);<br>if (post != null)<br>{<br>    Console.WriteLine($&quot;Id: {post.Id}&quot;);<br>    Console.WriteLine($&quot;Title: {post.Title}&quot;);<br>}<br><br>var newPost = new Post<br>{<br>    Id = 100,<br>    Body = &quot;Lorem ipsum odor amet, consectetuer adipiscing elit.&quot;,<br>    Title = &quot;Lorem ipsum&quot;,<br>    UserId = 1<br>};<br><br>// POST post - /posts<br>var httpResponse = await client.PostAsJsonAsync&lt;Post&gt;(&quot;/posts&quot;, newPost);<br>var content = await httpResponse.Content.ReadFromJsonAsync&lt;Post&gt;();<br><br>if (content != null)<br>{<br>    Console.WriteLine($&quot;New Id: {content.Id}&quot;);<br>    Console.WriteLine($&quot;New Title: {content.Title}&quot;);<br>}<br><br>client.Dispose();</pre><h3>Controlling Serialization Behavior</h3><p>In real-world scenarios, JSON often requires customization to handle unexpected formats. For example, the <strong>JsonSerializerOptions</strong> class enables case-insensitive matching, property name customization with <strong>JsonPropertyName </strong>attribute, <strong>JsonIgnore</strong> attribute for ignoring properties and converters like <strong>JsonStringEnumConverter</strong>.</p><p>It also handles invalid JSON, allowing trailing commas and comments, making JSON handling more flexible. .NET provides many ways to override the web defaults and I will show you some examples.</p><pre>using System.Text.Json;<br>using System.Text.Json.Serialization;<br><br>class Program<br>{<br>    public class Example<br>    {<br>        // Renaming JSON property using JsonPropertyName<br>        [JsonPropertyName(&quot;field_name&quot;)]<br>        public string? Name { get; set; }<br><br>        // This property will be ignored during deserialization<br>        [JsonIgnore]<br>        public string? IgnoredProperty { get; set; }<br><br>        // Enum will be converted to string using JsonStringEnumConverter<br>        public StatusEnum Status { get; set; }<br><br>        public int TrailingComma { get; set; }<br>    }<br><br>    // Enum with JsonStringEnumConverter to serialize and deserialize as strings<br>    [JsonConverter(typeof(JsonStringEnumConverter))]<br>    public enum StatusEnum<br>    {<br>        Active,<br>        Inactive<br>    }<br><br>    static void Main()<br>    {<br>        // Example JSON string<br>        string json = @&quot;<br>        {<br>            &quot;&quot;field_name&quot;&quot;: &quot;&quot;Test&quot;&quot;,  // A comment<br>            &quot;&quot;IgnoredProperty&quot;&quot;: &quot;&quot;ShouldNotDeserialize&quot;&quot;, <br>            &quot;&quot;Status&quot;&quot;: &quot;&quot;Active&quot;&quot;, <br>            &quot;&quot;ExtraProperty&quot;&quot;: &quot;&quot;Ignored&quot;&quot;,<br>            &quot;&quot;TrailingComma&quot;&quot;: 123,  // Trailing comma<br>        }&quot;;<br><br>        // Set JsonSerializerOptions with customization<br>        var options = new JsonSerializerOptions<br>        {<br>            PropertyNameCaseInsensitive = true,  // Enable case-insensitive matching<br>            Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) },  // Enums as strings<br>            AllowTrailingCommas = true,  // Allow trailing commas<br>            ReadCommentHandling = JsonCommentHandling.Skip  // Skip comments in JSON<br>        };<br><br>        var example = JsonSerializer.Deserialize&lt;Example&gt;(json, options);<br><br>        Console.WriteLine($&quot;Name: {example?.Name}&quot;);  // &quot;Test&quot;<br>        Console.WriteLine($&quot;Status: {example?.Status}&quot;);  // &quot;Active&quot;<br>        Console.WriteLine($&quot;TrailingComma: {example?.TrailingComma}&quot;);  // 123<br>        Console.WriteLine($&quot;IgnoredProperty: {example?.IgnoredProperty}&quot;);<br><br>        // IgnoredProperty will not be printed as it&#39;s ignored<br>    }<br>}</pre><h3>JSON to C# ?</h3><p>When provided with a JSON string or file, you may need to create C# classes to deserialize it. While free online tools can assist with this, Visual Studio offers a built-in feature to simplify the process.</p><p>Copy the entire JSON string (Ctrl + C) and in Visual Studio, use the “Paste Special” option under the edit menu as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*sTa0VPog-aVAGvWWJGAtjw.png" /><figcaption>Visual studio edit menu</figcaption></figure><h3>Best Practices</h3><h4>Handle Exceptions Gracefully:</h4><p>During the execution of a program, <strong>JsonExceptions</strong> can be raised for various reasons, such as invalid JSON text, exceeding the maximum depth, or the JSON text being incompatible with the type of a property.</p><ul><li>Create a custom exception with details to help with logging and debugging</li><li>Catch <strong>JsonException</strong> or the base <strong>Exception</strong> to handle errors</li><li>Use clear and organized logging to easily track and fix issues</li></ul><pre>// Ex: Custom exception class<br>public class JsonHandlingException: JsonException<br>{<br>public JsonHandlingException(string message) <br>: base(message)<br>{<br>}<br><br>public JsonHandlingException(string message, Exception innerException)<br>: base(message, innerException)<br>{<br>}<br>}</pre><h4>Allow Invalid JSON:</h4><p>Comments and trailing commas are not allowed in JSON by default. However, JSON can handle numbers in quotes (e.g., “256”) during deserialization. Below is an example demonstrating how we can manage this using <strong>JsonSerializerOptions.</strong></p><pre>var options = new JsonSerializerOptions<br>{<br>    ReadCommentHandling = JsonCommentHandling.Skip,<br>    AllowTrailingCommas = true,<br>    NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString<br>}</pre><h4>Handle JSON that overflow:</h4><p>JSON may potentially include fields that are not represented in the target properties. In such cases, we can use the <strong>JsonExtensionData </strong>attribute to capture this extra data into a dictionary. The data can be stored in:</p><ul><li>Dictionary&lt;string, object&gt;</li><li>Dictionary&lt;string, JsonElement&gt;</li></ul><p>Check the below Demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*jLbek2z-BVe7gRQBfK_OXg.png" /><figcaption>Visual studio output</figcaption></figure><h4>Handle circular references:</h4><p>There are several ways to handle this, depending on your specific requirements. While I won’t dive into all the details here, it’s important to note that these situations can be managed gracefully with the right approach.</p><h3>Conclusion</h3><p>With the right techniques, you can manage serialization, deserialization, and tricky scenarios like handling invalid JSON effortlessly. I believe, these tips make your code cleaner and more reliable, helping you handle data smoothly in your .NET projects. Keep it simple and efficient !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14680bede552" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XML Demystified in .NET C#: A Practical Guide]]></title>
            <link>https://medium.com/@shehan.s/xml-demystified-in-net-c-a-practical-guide-626553cbe64b?source=rss-c92e64f643af------2</link>
            <guid isPermaLink="false">https://medium.com/p/626553cbe64b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Shehan Samarasinghe]]></dc:creator>
            <pubDate>Wed, 11 Dec 2024 10:02:24 GMT</pubDate>
            <atom:updated>2024-12-11T10:02:24.768Z</atom:updated>
            <content:encoded><![CDATA[<h3>XML Demystified in .NET C#: A Practical Guide</h3><h4>Unlock the power of XML in .NET with C#</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73dyNwTvZbyaIOFexWmApA.jpeg" /></figure><h3>Introduction</h3><p>In this article, we will explore several topics, such as what XML is, how we can manipulate XML in .NET, and LINQ to XML. The code examples in this article are fully applicable to .NET 6/7/8/9, C# 10/11/12/13, and Visual Studio 2022.</p><h3>What is XML &amp; Uses?</h3><ul><li>XML (Extensible Markup Language) is a tag-based markup language</li><li>Use to store and transport data</li><li>No pre-defined tags. Define your own tags and data</li><li>Use for web services, configuration settings, and document storage etc.</li><li>Applications like Word and Excel use XML to store document data</li></ul><h3>Components of XML Structure</h3><p>XML is made up of several building blocks. Declaration, XML namespace declaration, Attribute, Tag, Element and Comment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*QRyioN7Ty2I9zFE1SC3_Cg.png" /></figure><h3>XML Document Structure</h3><p>An XML document is structured with a declaration, a root node, parent nodes, child nodes, and sibling nodes to the child nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*LV19WDkEDDY8dQ8D9dB3lw.png" /></figure><p>This document defines the structure of XML, describing elements, attributes, their behavior (whether they repeat or not) and type of data. An XML schema helps validate the XML document. There are two ways to do this.</p><ul><li>DTD — Document Type Definition (Old Version)</li><li>XSD — Xml Schema Definition (New Version)</li></ul><p>By using this <a href="https://www.freeformatter.com/xsd-generator.html">free tool</a>, you can generate an XSD from a given XML document and validate the XML against a given XSD. Below is a sample XSD, including the named parts with comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*GvJ2iemh_Kn-4R-_0HLftg.png" /></figure><h3>Using .NET System.Xml.Linq</h3><p>I believe we now have a better understanding of XML and its components. The <strong>System.Xml.Linq</strong> namespace provides all the classes required to work with XML programmatically. We have several major classes, such as <strong>XDocument, XDeclaration, XElement, XAttribute, </strong>and<strong> XComment.</strong></p><p>We can create XML programmatically as shown below. As discussed earlier, you can see how the XML document is structured with a declaration, a root node, parent nodes, child nodes, and sibling nodes.</p><pre>using System.Xml.Linq;<br><br>var document =<br>    new XDocument(<br>        new XDeclaration(&quot;1.0&quot;, &quot;utf-8&quot;, &quot;yes&quot;),<br>        new XComment(&quot;Library Information&quot;),<br>        new XElement(&quot;Library&quot;,<br>            new XElement(&quot;Book&quot;, new XAttribute(&quot;id&quot;, 1),<br>                new XElement(&quot;Title&quot;, &quot;Clean Code&quot;),<br>                new XElement(&quot;Author&quot;, &quot;Robert C. Martin&quot;),<br>                new XElement(&quot;Price&quot;, new XAttribute(&quot;currency&quot;, &quot;USD&quot;), 37.99),<br>                new XElement(&quot;Publisher&quot;,<br>                    new XElement(&quot;Name&quot;, &quot;Prentice Hall&quot;),<br>                    new XElement(&quot;Year&quot;, 2008)<br>                )<br>            )<br>        )<br>    );<br><br>Console.WriteLine(document);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*aGmZB01wWCmnJl6Bwx3zDg.png" /></figure><h4>XML string to XML Document:</h4><p>We can use <strong>XDocument.Parse</strong> method to achieve this. However, this operation can lead to errors (<strong>System.Xml.XmlException</strong>) if the XML string is not valid.</p><pre>using System.Xml.Linq;<br><br>var xml = @&quot;&lt;Library&gt;<br>              &lt;Book id=&quot;&quot;1&quot;&quot;&gt;<br>                &lt;Title&gt;Clean Code&lt;/Title&gt;<br>                &lt;Publisher&gt;<br>                  &lt;Year&gt;2008&lt;/Year&gt;<br>                &lt;/Publisher&gt;<br>              &lt;/Book&gt;<br>            &lt;/Library&gt;&quot;;<br><br>var doc = XDocument.Parse(xml);<br>Console.WriteLine(doc);</pre><h4>Add, Update and Delete Element:</h4><p>We can add, update, and delete elements in an XML document in various ways. Append the code block below to the previous one for testing.</p><pre>var newBook =<br>    new XElement(&quot;Book&quot;, new XAttribute(&quot;id&quot;, 2),<br>        new XElement(&quot;Title&quot;, &quot;Refactoring&quot;),<br>        new XElement(&quot;Publisher&quot;,<br>            new XElement(&quot;Year&quot;, 2005)<br>        )<br>    );<br><br>// Add new element<br>doc?.Root?.Add(newBook);<br>Console.WriteLine(doc + &quot;\n&quot;);<br><br>// Get the first book element.<br>var element = doc?.Root?.Descendants().FirstOrDefault();<br><br>if (element != null &amp;&amp; element.Element(&quot;Title&quot;) != null)<br>{<br>    // Update the title of the element<br>    element.Element(&quot;Title&quot;)!.Value = &quot;C# Basics&quot;;<br>    Console.WriteLine(doc + &quot;\n&quot;);<br><br>    // Remove element<br>    element.Remove();<br>    Console.WriteLine(doc);<br>}</pre><h3>Load, Save and Validate XML</h3><h4>Load XML Files:</h4><p>Loading XML files in .NET can be efficiently done using the <strong>XDocument</strong> and <strong>XElement</strong> classes from the <strong>System.Xml.Linq</strong> namespace. Here is how you can load an XML file and display the first node to demonstrate the difference between <strong>XDocument</strong> and <strong>XElement</strong>.</p><pre>// Using XDocument<br>var xdoc = XDocument.Load(&quot;path/to/your/xmlfile.xml&quot;);<br>Console.WriteLine(&quot;First node using XDocument: &quot; + xdoc.FirstNode);<br><br>// Using XElement<br>var xelement = XElement.Load(&quot;path/to/your/xmlfile.xml&quot;);<br>Console.WriteLine(&quot;First node using XElement: &quot; + xelement.FirstNode);</pre><p><strong>XDocument</strong> represents the whole XML document, including the declaration, while <strong>XElement</strong> represents just one XML element.</p><h4>Save XML Files:</h4><p>Using <strong>XDocument</strong>, saving an XML document is straightforward operation. Check the below example.</p><pre>var xdoc = new XDocument(<br>    new XElement(&quot;root&quot;,<br>        new XElement(&quot;element&quot;, &quot;Value&quot;)<br>    )<br>);<br>xdoc.Save(&quot;path/to/your/newxmlfile.xml&quot;);</pre><h4>Using XmlWriter and XmlWriterSettings:</h4><p>There are scenarios where data comes from various sources, such as SQL tables, JSON files, etc. When you need to read this information and build an XML document from scratch, using <strong>XmlWriter</strong> is an ideal choice.</p><pre>var settings = new XmlWriterSettings<br>{<br>    Indent = true,<br>    IndentChars = &quot;  &quot;,<br>    NewLineOnAttributes = true<br>};<br><br>using (var writer = XmlWriter.Create(&quot;path/to/your/formattedxmlfile.xml&quot;, settings))<br>{<br>    writer.WriteStartDocument();<br>    writer.WriteStartElement(&quot;root&quot;);<br>    writer.WriteElementString(&quot;element&quot;, &quot;Value&quot;);<br>    writer.WriteEndElement();<br>    writer.WriteEndDocument();<br>}</pre><h3>Valiate XML</h3><p>By validating XML documents against an <strong>XSD </strong>(XML Schema Definition) ensures that the XML data adheres to a defined structure.</p><pre>var schemas = new XmlSchemaSet();<br>schemas.Add(&quot;&quot;, &quot;path/to/your/schema.xsd&quot;);<br><br>var xdoc = XDocument.Load(&quot;path/to/your/xmlfile.xml&quot;);<br>bool isValid = true;<br><br>xdoc.Validate(schemas, (o, e) =&gt;<br>{<br>    if (e.Severity == XmlSeverityType.Error) // Check for Error<br>    {<br>        Console.WriteLine($&quot;Error: {e.Message}&quot;);<br>        isValid = false;<br>    }<br>    else if (e.Severity == XmlSeverityType.Warning) // Check for warning<br>    {<br>        Console.WriteLine($&quot;Warning: {e.Message}&quot;);<br>        isValid = false;<br>    }<br>});</pre><h3>XML using XPath in .NET</h3><p><strong>XPath</strong> is a language for navigating XML elements and attributes, supporting querying, filtering, and aggregating data. The .NET <strong>System.Xml.XPath</strong> namespace provides methods for working with XPath. Here’s an example of selecting elements using XPath<strong>.</strong></p><pre>using System.Xml.Linq;<br>using System.Xml.XPath;<br><br>var xml = @&quot;&lt;Library&gt;<br>              &lt;Book id=&quot;&quot;1&quot;&quot;&gt;<br>                &lt;Title&gt;Clean Code&lt;/Title&gt;<br>                &lt;Publisher&gt;<br>                  &lt;Year&gt;2008&lt;/Year&gt;<br>                &lt;/Publisher&gt;<br>              &lt;/Book&gt;<br>              &lt;Book id=&quot;&quot;2&quot;&quot;&gt;<br>                &lt;Title&gt;Learn C#&lt;/Title&gt;<br>                &lt;Publisher&gt;<br>                  &lt;Year&gt;2009&lt;/Year&gt;<br>                &lt;/Publisher&gt;<br>              &lt;/Book&gt;<br>            &lt;/Library&gt;&quot;;<br><br>var xdoc = XDocument.Parse(xml);<br><br>// Select a single element<br>var element = xdoc.XPathSelectElement(&quot;//Publisher&quot;);<br>Console.WriteLine($&quot;Selected Element: \n {element} \n&quot;);<br><br>// Select multiple elements<br>var elements = xdoc.XPathSelectElements(&quot;//Publisher&quot;);<br>foreach (var elem in elements)<br>{<br>    Console.WriteLine($&quot;Element: \n {elem}&quot;);<br>}</pre><p>Probably we can use LINQ to XML for new development.</p><h3>LINQ to XML</h3><p><strong>LINQ </strong>is simpler than XPath and provides more functionality for many operations, such as querying, filtering, sorting, searching, etc. You can use either Lambda expressions with LINQ or direct LINQ, depending on your personal preference. In the example below, I have used LINQ with Lambda expressions.</p><pre>using System.Xml.Linq;<br><br>var xml = @&quot;&lt;Library&gt;<br>              &lt;Book id=&quot;&quot;1&quot;&quot;&gt;<br>                &lt;Title&gt;Solid Principles&lt;/Title&gt;<br>                &lt;Publisher&gt;<br>                  &lt;Year&gt;2008&lt;/Year&gt;<br>                &lt;/Publisher&gt;<br>              &lt;/Book&gt;<br>              &lt;Book id=&quot;&quot;2&quot;&quot;&gt;<br>                &lt;Title&gt;Learn C#&lt;/Title&gt;<br>                &lt;Publisher&gt;<br>                  &lt;Year&gt;2010&lt;/Year&gt;<br>                &lt;/Publisher&gt;<br>              &lt;/Book&gt;<br>               &lt;Book id=&quot;&quot;3&quot;&quot;&gt;<br>                &lt;Title&gt;Clean Code&lt;/Title&gt;<br>                &lt;Publisher&gt;<br>                  &lt;Year&gt;2008&lt;/Year&gt;<br>                &lt;/Publisher&gt;<br>              &lt;/Book&gt;<br>            &lt;/Library&gt;&quot;;<br><br>var xelements = XElement.Parse(xml);<br><br>// List of book elements<br>var books = xelements.Elements(&quot;Book&quot;).ToList();<br><br>// Filter books by publisher year<br>var filteredBooks = xelements.Elements(&quot;Book&quot;)<br>            .Where(book =&gt; book.Element(&quot;Publisher&quot;)?.Element(&quot;Year&quot;)?.Value == &quot;2008&quot;);<br><br>// Get the single book by id (Single selection)<br>var singleNode = xelements.Elements(&quot;Book&quot;)<br>            .Where(book =&gt; book.Attribute(&quot;id&quot;)?.Value == &quot;2&quot;)<br>            .SingleOrDefault();<br><br>// Calculate average price<br>var averagePrice = xelements.Elements(&quot;Book&quot;)<br>    .Average(book =&gt; (decimal?)book.Element(&quot;Publisher&quot;)?.Element(&quot;Price&quot;) ?? 0);<br><br>// Order books by title in ascending order<br>var orderedBooks = xelements.Elements(&quot;Book&quot;)<br>            .Where(book =&gt; (book.Element(&quot;Publisher&quot;)?.Element(&quot;Year&quot;)?.Value) == &quot;2008&quot;)<br>            .OrderBy(book =&gt; book.Element(&quot;Title&quot;)?.Value);<br><br>// Create a collection of C# objects<br>// Here, I have created an anonymous object for demonstration purposes<br>var bookCollection = xelements.Elements(&quot;Book&quot;)<br>            .Where(book =&gt; (book.Element(&quot;Publisher&quot;)?.Element(&quot;Year&quot;)?.Value) == &quot;2008&quot;)<br>            .OrderBy(book =&gt; book.Element(&quot;Title&quot;)?.Value)<br>            .Select(x =&gt; new<br>            {<br>                id = x.Attribute(&quot;id&quot;)?.Value,<br>                name = x.Element(&quot;Title&quot;)?.Value<br>            });</pre><h3>XmlDocument (DOM-Based XML Processing)</h3><p>The <strong>XmlDocument </strong>class in .NET provides a way to work with XML documents using the <strong>DOM </strong>(Document Object Model). You can perform various operations such as loading, navigating, modifying, and saving XML data. Below is a sample code for DOM-based XML reading.</p><pre>using System.Xml;<br><br>var xml = @&quot;&lt;Library&gt;<br>              &lt;Book id=&quot;&quot;1&quot;&quot;&gt;<br>                &lt;Title&gt;Solid Principles&lt;/Title&gt;<br>                &lt;Publisher&gt;<br>                  &lt;Year&gt;2008&lt;/Year&gt;<br>                  &lt;Price&gt;3000&lt;/Price&gt;<br>                &lt;/Publisher&gt;<br>              &lt;/Book&gt;<br>              &lt;Book id=&quot;&quot;2&quot;&quot;&gt;<br>                &lt;Title&gt;Learn C#&lt;/Title&gt;<br>                &lt;Publisher&gt;<br>                  &lt;Year&gt;2010&lt;/Year&gt;<br>                  &lt;Price&gt;2000&lt;/Price&gt;<br>                &lt;/Publisher&gt;<br>              &lt;/Book&gt;<br>               &lt;Book id=&quot;&quot;3&quot;&quot;&gt;<br>                &lt;Title&gt;Clean Code&lt;/Title&gt;<br>                &lt;Publisher&gt;<br>                  &lt;Year&gt;2008&lt;/Year&gt;<br>                  &lt;Price&gt;1000&lt;/Price&gt;<br>                &lt;/Publisher&gt;<br>              &lt;/Book&gt;<br>            &lt;/Library&gt;&quot;;<br><br>var xmlDoc = new XmlDocument();<br>xmlDoc.LoadXml(xml);<br><br>var bookNodes = xmlDoc.GetElementsByTagName(&quot;Book&quot;);<br>foreach (XmlNode book in bookNodes)<br>{<br>    var publisherNode = book[&quot;Publisher&quot;];<br>    var yearNode = publisherNode?[&quot;Year&quot;];<br>    if (yearNode?.InnerText == &quot;2008&quot;)<br>    {<br>        Console.WriteLine(book[&quot;Title&quot;]?.InnerText);<br>    }<br>}</pre><h3>Best Practices</h3><p>· Choose the Right API: Use <strong>XDocument</strong> for LINQ to XML, <strong>XmlDocument</strong> for DOM-based operations.</p><p>· Validate XML: Ensure your XML complies with an XSD to maintain data integrity.</p><p>· Handle Exceptions Gracefully: Deliver helpful error messages and ensure reliability.</p><p>· Use XPath for Complex Queries: Simplify your code with efficient <strong>XPath</strong> expressions.</p><p>· Optimize Performance: Use <strong>XmlReader</strong> and <strong>XmlWriter</strong> for handling large XML files.</p><h3>Conclusion</h3><p>To sum up, XML is a flexible way to store and share data. In .NET, tools like <strong>XDocument</strong> and <strong>XmlDocument</strong> make it easy to create, edit, and manage XML. With features like <strong>LINQ</strong> and XPath, you can handle XML efficiently for a variety of applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=626553cbe64b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File Operations in C# .NET: Part 01 — File and Directory Handling]]></title>
            <link>https://medium.com/@shehan.s/file-operations-in-c-net-part-01-file-and-directory-handling-60051437cc24?source=rss-c92e64f643af------2</link>
            <guid isPermaLink="false">https://medium.com/p/60051437cc24</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Shehan Samarasinghe]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 01:31:01 GMT</pubDate>
            <atom:updated>2024-12-09T16:35:57.147Z</atom:updated>
            <content:encoded><![CDATA[<h3>File Operations .NET C#: Part 01 — File and Directory Handling</h3><h4>Master file and directory handling in .NET C#</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8A09pGyLRjWf6VtTT6K4QA.jpeg" /></figure><h3>Introduction</h3><p>File handling is a fundamental skill every developer must master. This article covers the basics of file and directory management, including path manipulation, copying, moving, deleting, and exception handling. For demonstration purposes, I used Visual Studio 2022, .NET 8, and C# 12.</p><h3>Managing File Paths</h3><p>It is crucial to manage paths to ensure that your application can locate and access files accurately. The .NET framework provides useful methods in the <strong>System.IO.Path</strong> class for manipulating file and directory paths.</p><h4>Combine Paths:</h4><p>The <strong>Path.Combine</strong> method combines multiple strings into a single path.</p><pre>using System;<br>using System.IO;<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        string folderPath = &quot;C:\\Users\\User&quot;;<br>        string fileName = &quot;example.txt&quot;;<br>        string fullPath = Path.Combine(folderPath, fileName);<br>        Console.WriteLine(fullPath); // Output: C:\Users\User\example.txt<br>    }<br>}</pre><h4>Getting the File Name:</h4><p>The <strong>Path.GetFileName</strong> method returns the file name along with its extension.</p><pre>string filePath = &quot;C:\\Users\\User\\example.txt&quot;;<br>string fileName = Path.GetFileName(filePath);<br>Console.WriteLine(fileName); // Output: example.txt</pre><h4>Getting the File Extension:</h4><p>The <strong>Path.GetExtension</strong> method returns the extension of a file, including the dot.</p><pre>string filePath = &quot;example.txt&quot;;<br>string extension = Path.GetExtension(filePath);<br>Console.WriteLine(extension); // Output: .txt</pre><h3>Checking the Existence of Files and Directories</h3><p>When working with files or directories in C#, it’s always a good practice to check if they exist beforehand. .NET framework offers built-in methods to perform these checks efficiently.</p><h4>Check Whether a File Exists:</h4><p>The <strong>File.Exists</strong> method checks if a file exists at a specified path.</p><pre>string filePath = &quot;C:\\Users\\Logs\\example.txt&quot;;<br><br>if (File.Exists(filePath))<br>{<br>    Console.WriteLine(&quot;File exists.&quot;);<br>}<br>else<br>{<br>    Console.WriteLine(&quot;File does not exist.&quot;);<br>}</pre><h4>Check Whether a Directory Exists:</h4><p>The <strong>Directory.Exists</strong> method checks if a directory exists at a specified path.</p><pre>string directoryPath = &quot;C:\\Users\\Logs&quot;;<br><br>if (Directory.Exists(directoryPath))<br>{<br>    Console.WriteLine(&quot;Directory exists.&quot;);<br>}<br>else<br>{<br>    Console.WriteLine(&quot;Directory does not exist.&quot;);<br>}</pre><h3>Copying Files</h3><p>Copying files is a frequent operation, especially when you need to create duplicates or backup data. .NET provides the <strong>File.Copy</strong> method provides an efficient way to copy files from one location to another ensuring that the original file remains unchanged while creating a replica at the specified destination.</p><h4>Using File.Copy:</h4><p>The <strong>File.Copy</strong> method is used to copy an existing file to a new location. If the file already exists at the destination, you can decide whether to overwrite it.</p><pre>string sourceFilePath = &quot;C:\\Users\\Logs\\example.txt&quot;;<br>string destinationFilePath = &quot;example_copy.txt&quot;;<br><br>// Copy the file and overwrite if it already exists<br>File.Copy(sourceFilePath, destinationFilePath, true);<br>Console.WriteLine(&quot;File copied successfully.&quot;);</pre><h3>Moving Files</h3><p>Moving files means transferring a file from one location to another. You can use the <strong>File.Move</strong> method to handle this operation easily.</p><h4>Using File.Move:</h4><p>The <strong>File.Move</strong> method is used to move an existing file to a new location. If the destination file already exists, an exception (IOException) is thrown.</p><pre>string sourceFilePath = &quot;C:\\Users\\Logs\\example.txt&quot;;<br>string destinationFilePath = &quot;C:\\Users\\ArchivedLogs\\example.txt&quot;;<br><br>// Move the file to the new location<br>File.Move(sourceFilePath, destinationFilePath);<br>Console.WriteLine(&quot;File moved successfully.&quot;);</pre><h3>Listing Files in a Directory</h3><p>When we need to analyze multiple files, it may be necessary to list all the files in a directory. By using <strong>Directory.GetFiles</strong>, we can fetch the names of the files in a specified directory.</p><h4>Using Directory.GetFiles:</h4><p>The <strong>Directory.GetFiles</strong> method retrieves a list of file names from a specified directory that match a given search pattern and returns them as an array.</p><pre>using System;<br>using System.IO;<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        string directoryPath = &quot;C:\\Users\\User\\Documents&quot;;<br>        <br>        // Get all files in the directory<br>        string[] files = Directory.GetFiles(directoryPath);<br>        <br>        foreach (string file in files)<br>        {<br>            Console.WriteLine(file);<br>        }<br>    }<br>}</pre><h4>Using Search Pattern:</h4><p>You can use search patterns with <strong>Directory.GetFiles</strong> to filter files, such as retrieving all text files in a directory.</p><pre>string directoryPath = &quot;C:\\Users\\User\\Documents&quot;;<br><br>// Get all .txt files in the directory<br>string[] textFiles = Directory.GetFiles(directoryPath, &quot;*.txt&quot;);<br>foreach (string file in textFiles)<br>{<br>    Console.WriteLine(file);<br>}</pre><h4>Using Search for Recursive Search:</h4><p>The <strong>SearchOption</strong> enum lets you decide whether to search only the current directory or include sub-directories.</p><pre>string directoryPath = &quot;C:\\Users\\User\\Documents&quot;;<br><br>// Get all files in the directory and its subdirectories<br>string[] allFiles = Directory.GetFiles(directoryPath, &quot;*.*&quot;, SearchOption.AllDirectories);<br>foreach (string file in allFiles)<br>{<br>    Console.WriteLine(file);<br>}</pre><h3>Deleting Directories</h3><p>Deleting directories is a common operation when you want to remove a folder and its contents. You can use the <strong>Directory.Delete</strong> method to do this easily.</p><pre>string directoryPath = &quot;C:\\Users\\User\\ArchivedLogs&quot;;<br><br>// Delete the directory and all its contents<br>Directory.Delete(directoryPath, true);<br>Console.WriteLine(&quot;Directory deleted successfully.&quot;);</pre><h3>Handling Exceptions</h3><p>File operations can often cause errors, such as when a file is missing or access is restricted. Properly handling these exceptions is essential for creating reliable applications.</p><h4>Common Exceptions:</h4><ul><li><strong>FileNotFoundException</strong>: Thrown when a file specified in a method is not found.</li><li><strong>UnauthorizedAccessException</strong>: Thrown when the operating system denies access to a file.</li><li><strong>IOException</strong>: Thrown when an I/O error occurs.</li></ul><h4>Handle Gracefully:</h4><p>Here is an example of how to handle exceptions when working with file operations.</p><pre>using System;<br>using System.IO;<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        string filePath = &quot;example.txt&quot;;<br>        <br>        try<br>        {<br>            string content = File.ReadAllText(filePath);<br>            Console.WriteLine(content);<br>        }<br>        catch (FileNotFoundException ex)<br>        {<br>            Console.WriteLine($&quot;File not found: {ex.Message}&quot;);<br>        }<br>        catch (UnauthorizedAccessException ex)<br>        {<br>            Console.WriteLine($&quot;Access denied: {ex.Message}&quot;);<br>        }<br>        catch (IOException ex)<br>        {<br>            Console.WriteLine($&quot;I/O error: {ex.Message}&quot;);<br>        }<br>        catch (Exception ex)<br>        {<br>            Console.WriteLine($&quot;Unhandled error: {ex.Message}&quot;);<br>        }<br>    }<br>}</pre><h3>Best Practices Tips</h3><ul><li>Validate file paths.<br>This helps to avoid exceptions and ensure that the path is correct.</li><li>Avoid hard-coding paths.<br>Use configuration files or environment variables to manage paths.</li><li>Use <strong>using</strong> statement<br>Always use using statements to ensure file streams are closed and resources are released. This helps prevent memory leaks and keeps your app running smoothly.</li><li>Handle exceptions gracefully<br>Implement proper exception handling to manage errors and provide meaningful error details.</li><li>Use asynchronous programming<br>Specially when working with large files or I/O bound operations, consider using asynchronous methods to enhance performance.</li><li>Ensure proper permissions<br>Always make sure your application has the required permissions to access or modify files and directories, especially in secure environments.</li><li>Monitor file system changes<br>In a separate article, I’ll discuss using the <strong>FileSystemWatcher </strong>class to monitor file changes, which is useful for apps that need to respond to file creation, modification, or deletion.</li></ul><h3>Conclusion</h3><p>Mastering file handling is important for building reliable applications. By using powerful methods provided by the .NET framework, file operations like managing paths, listing files, copying, moving, checking existence, and deleting are easier. By following best practices, you can make your file operations efficient and secure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60051437cc24" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>