<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Jason Archer</title>
    <description>The latest articles on DEV Community by Jason Archer (@jasoncarcher).</description>
    <link>https://dev.to/jasoncarcher</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F931401%2F69c0aa31-02a6-400b-9600-c66d4954a123.jpeg</url>
      <title>DEV Community: Jason Archer</title>
      <link>https://dev.to/jasoncarcher</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/jasoncarcher"/>
    <language>en</language>
    <item>
      <title>A Beginners Guide to GraphQL Dotnet CancellationToken</title>
      <dc:creator>Jason Archer</dc:creator>
      <pubDate>Fri, 14 Oct 2022 15:26:16 +0000</pubDate>
      <link>https://dev.to/jasoncarcher/a-beginners-guide-to-graphql-dotnet-cancellationtoken-3ccm</link>
      <guid>https://dev.to/jasoncarcher/a-beginners-guide-to-graphql-dotnet-cancellationtoken-3ccm</guid>
      <description>&lt;p&gt;In the early 2000s, the REST API gained much fame in the technology sector due to its multipurpose functionality and responsiveness. However, despite the increased usage, the developer community encountered an issue of over-fetching data points. The data holds core importance in any web or mobile application. Apart from it, the excessive retrieval of data can slow the process and may further lead to an unresponsive server as well.&lt;/p&gt;

&lt;p&gt;In order to tackle the growing concern, the Graph Query Language was developed by Facebook to make its app more responsive and reliable. GraphQL is an API standard, particularly an alternative to REST APIs. Unlike the traditional REST API, this solution grants the control to the client to directly request the specified data rather than irrelevant data.&lt;/p&gt;

&lt;p&gt;The goal of GraphQL is to make APIs quick, adaptable, and developer-friendly. In contrast to REST, GraphQL APIs allow data to be retrieved and delivered from different sources while accepting all incoming requests at a single endpoint.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;- GraphQL Dotnet&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://clearinsights.io/blog/a-beginners-guide-to-graphql-dotnet-cancellationtoken/"&gt;GraphQL&lt;/a&gt; is not only bounded to specific backend languages but can also be used to develop projects in Dotnet. There are numerous platforms and languages in the GraphQL ecosystem. Despite the fact that .NET was slow to implement support, several widely used client and server solutions are available now.&lt;/p&gt;

&lt;p&gt;A basic example of &lt;strong&gt;GraphQL.NET using the System.Text.Json serialization engine.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using System;
using System.Threading.Tasks;
using GraphQL;
using GraphQL.Types;
using GraphQL.SystemTextJson;
public class Program
{
    public static async Task Main(string[] args)
    {
        var schema = Schema.For(@"
            type Query {
                hello: String
            }
        ");
        var json = await schema.ExecuteAsync(_ =&amp;gt;
        {
            _.Query = "{ hello }";
            _.Root = new { Hello = "Hello World!" };
        });
        Console.WriteLine(json);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
   "data":{
      "hello":"Hello World!"
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;- Defining Schema in GraphQL&lt;/strong&gt;&lt;br&gt;
As GraphQL is a structured Graph Query Language, it must have its schema defined. In order to design its schema, two approaches can be utilized:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;- Schema First Approach (Using GraphQL)&lt;/strong&gt;&lt;br&gt;
This approach is believed to be the simplest one to get started with, and it has limitations for advanced implementations and scenarios. This methodology’s practical procedure lies upon the GraphQL schema language and syntaxes, resulting in a minimal syntax approach. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;- GraphType (Code First Approach)&lt;/strong&gt;&lt;br&gt;
Although the GraphType technique can be more expansive and has a higher Line of Code (LOC). Furthermore, GraphType implementation allows the developers access to every property that GraphType and Schema provide. To use this methodology, Object Oriented Programming (OOP) paradigm is opted for, and Inheritance is used to leverage this functionality.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;- CancellationToken in Dotnet&lt;/strong&gt;&lt;br&gt;
In a web-based application, the request from the client and the reposne from the server sides are standard ways of communication between stakeholders. However, such scenarios exist too, where a client-server interaction is interrupted, and the client-side becomes unresponsive.&lt;/p&gt;

&lt;p&gt;Once a user gets disconnected due to a network interruption, navigating between multiple browser tabs, or closing the browser, the request becomes an orphan. Whereas an orphan request cannot deliver a response to the client, it will still communicate with the server, resulting in a recursive process and further leading to excessive memory usage by the particular process.&lt;/p&gt;

&lt;p&gt;To prevent a process from making irregular and consistent calls to the server side, the CancellationToken is used. It terminates the request execution at the server immediately.&lt;/p&gt;

&lt;p&gt;Canceling tasks in Dotnet/C# is not tricky. However, there are several ways to do so. The three commonly used methods include:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Polling&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Registering a Callback&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Wait Handle&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Additionally, multiple tokens can be canceled at once as the polling strategy is designed for situations where there are lengthy computations that loop or recurse.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The typical procedure followed when canceling a task using CancellationToken:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Instantiate a &lt;strong&gt;CancellationTokenSource&lt;/strong&gt; object. This object manages and sends the cancellation notification to the individual cancellation tokens.&lt;/li&gt;
&lt;li&gt;Passing the token returned by the CancellationTokenSource. Token property to each task or thread that listens for cancellation.&lt;/li&gt;
&lt;li&gt;Providing a mechanism for the thread to respond to cancellation. The token cannot be used to initiate a cancellation&lt;/li&gt;
&lt;li&gt;Calling the CancellationTokenSource.&lt;/li&gt;
&lt;li&gt;When the owning object calls CancellationTokenSource.Cancel, the IsCancellationRequested property on every copy of the cancellation token is set.&lt;/li&gt;
&lt;li&gt;Canceling method to provide notification of cancellation.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;- GraphQL Dotnet CancellationToken&lt;/strong&gt;&lt;br&gt;
When GraphQL.NET is used, the query fetches results, and the conditions exist where the proper process synchronization needs to be done by canceling excessive tasks at once. The CancellationToken may be used to prevent an application failure or unresponsive behavior as cooperative cancellation between threads or Task objects is made possible through a CancellationToken.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;- ClearInsights Application Logging &amp;amp; Monitoring&lt;/strong&gt;&lt;br&gt;
To prevent your application from failing at runtime or crashing, use ClearInsights application performance and &lt;a href="https://clearinsights.io/monitoring/"&gt;uptime monitoring&lt;/a&gt; for your deployed systems. Furthermore, with our extensive integrated monitoring for applications &amp;amp; services in any environment, you can keep developers, product teams, and stakeholders informed.&lt;/p&gt;

</description>
      <category>graphql</category>
      <category>csharp</category>
      <category>beginners</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>The Best Practices for Exception Handling in C#</title>
      <dc:creator>Jason Archer</dc:creator>
      <pubDate>Sat, 24 Sep 2022 04:17:25 +0000</pubDate>
      <link>https://dev.to/jasoncarcher/the-best-practices-for-exception-handling-in-c-20e2</link>
      <guid>https://dev.to/jasoncarcher/the-best-practices-for-exception-handling-in-c-20e2</guid>
      <description>&lt;p&gt;No matter how efficient your software application runs, one exception due to bad code can crash the application and make it unavailable for even millions of users. That is simply why &lt;a href="https://clearinsights.io/blog/clearinsights-net-global-exception-handling/"&gt;exception handling&lt;/a&gt; is a critical requirement for any code. This article explains the best practices you should follow when handling exceptions in C#.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Exception Handling?
&lt;/h2&gt;

&lt;p&gt;An exception is an error that occurs during the execution of a program that disrupts its normal control flow or execution. Examples include invalid user input, unavailable resources like files and folders,  and trying to access elements of arrays in a non-existent index. Exception handling is handling possible error conditions to allow the program to continue without disruption.&lt;/p&gt;

&lt;h2&gt;
  
  
  What are the best practices for exception handling in C#?
&lt;/h2&gt;

&lt;p&gt;C# provides several ways to handle exceptions like try-catch-blocks, multiple try-catch-blocks, and user-defined custom exceptions. Here are some best practices you should follow for you to build a well-designed application.&lt;/p&gt;

&lt;h4&gt;
  
  
  1.   If you can handle the error, do not throw exceptions
&lt;/h4&gt;

&lt;p&gt;There can be error conditions that are very common or likely to occur in many applications. For example, suppose you have a division operation in your code. The 'divide by zero' is a common exception for such operations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int num1 = 100;
int num2  = 0;

try {
   Console.WriteLine(num1 / num2);
}
catch (DivideByZeroException) {
   Console.WriteLine("Divide by zero exception occured .");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But, you do not have to throw exceptions for such common errors in the first place. Simply check if the numbers contain 0 so you can set it to a non-zero default value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int num1 = 100;
int num2 = 0;

if (num2 == 0) {
    num2 = 1; //setting a default value
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another example is the "NullReferenceException," which can occur if an object or a variable becomes null. Instead of throwing an exception, check if the object or variable is null before doing any operation. Here is how you can do it in C#,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;User user = null;

var name = user?.Name;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Appending the '?' symbol C# automatically checks that the object is null.&lt;/p&gt;

&lt;h4&gt;
  
  
  2.   Logging exceptions
&lt;/h4&gt;

&lt;p&gt;Logging is very important in exception handling with any programming language. As a best practice, ensure you log the exception object without just logging an error message. The exception object has a lot of information, including stack trace and exception type, which are crucial to troubleshooting the issue. Also, do not forget to provide a meaningful and grammatically  correct error message for you to make the troubleshooting hassle-free&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try {
   //divide by zero
}
catch (DivideByZeroException exception)
{ 
   Logger.LogError(exception, "Divide By Zero Exception");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Using ClearInsights Exception Handling is an easy way to log exceptions and automatically push the exception into your backlog to work on. Email notifications will also be sent out to team members based on configured settings. Create a free &lt;a href="https://clearinsights.io"&gt;ClearInsights&lt;/a&gt; account to try.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Integrate ClearInsights Logging with the code below&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.Logging.AddClearInsightsLogger(configuration =&amp;gt;
{
    configuration.ApiKey = "{ApiKey}";
    configuration.Secret = "{Environment Client Secret}";
    configuration.ApplicationName = "{Application Name}";
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, you do not need to log every exception manually like this. You can make logging even more informative and advanced if you have an automated way to log exceptions. Logging tools help you to achieve that. ClearInsights &lt;a href="https://clearinsights.io/logging/"&gt;centralized logging&lt;/a&gt;, for example, is a simple but intuitive logging tool that you can integrate into your application for automatic logging. &lt;/p&gt;

&lt;p&gt;Using this tool, you can record not only the exception message but also other information like the product, environment, source, and stack trace of each log. You can also get logging reports to see an overview of the different log types like Critical, error, warning, informational, and trace that provide different levels of logs. Another best thing about using this tool is you can filter them to get insight into the exceptions that frequently occur in your system. Thus, as a best practice, ensure that you use a good logging tool that provides you with an easy application logging experience.&lt;/p&gt;

&lt;h4&gt;
  
  
  3. Use throw statements to preserve the stack trace
&lt;/h4&gt;

&lt;p&gt;In some C# applications, developers use the "throw ex" statement instead of the " throw " statement in exceptions. This will not be helpful if you want to get the complete stack trace from the beginning. Because the "throw ex" statement does not keep the stack traces so that it is difficult to track down where the error first occurred. But the "throw" statement does log the stack trace. Thus, do not forget to use the throw statement as follows instead of using the 'throw ex' statement in exceptions for better exception handling.&lt;/p&gt;

&lt;p&gt;catch(Exception ex)&lt;br&gt;
{&lt;br&gt;
    throw;&lt;br&gt;
}&lt;/p&gt;

&lt;h4&gt;
  
  
  4.   Create custom exceptions using the Exception keyword
&lt;/h4&gt;

&lt;p&gt;Create custom exceptions to provide explicit exception handling for your application. Use the "Exception" keyword like in the following example when you declare one.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;public class MyCustomException: Exception{}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;You can define your own exception handling behavior and exceptions common across your application classes using custom exceptions. Also, it is a good practice to include three common constructors for custom exception classes, which are: Exception(), which sets the default values; exception (String) which you can pass a message; and Exception(String, Exception), for setting an inner exception. When you define the custom exception, do not forget to include logging for every exception you declare there. In addition, use additional properties to provide additional information about the exception.&lt;/p&gt;

&lt;h4&gt;
  
  
  5.   Use already existing exceptions as much as possible
&lt;/h4&gt;

&lt;p&gt;The fifth best practice of C# exception handling is using the pre-defined exceptions whenever possible in your code. This can be quite contradictive to the 4th best practice. But creating custom exceptions is best if your application code has more specific error cases. Following are some of the  predefined exceptions available in C# and when they are used:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  FileNotFoundException  - Throws when the program cannot locate a file.&lt;/li&gt;
&lt;li&gt;  DivideByZeroException - Divide a number by Zero&lt;/li&gt;
&lt;li&gt;  ArgumentNullException - When an argument value is null&lt;/li&gt;
&lt;li&gt;  InvalidOperationException  -  When an operation is invalid. For example, trying to close a connection that is already closed.&lt;/li&gt;
&lt;li&gt;  ArrayIndexOutOfBoundException  - When you try to access an element of an array that is at an index outside its maximum index.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;From this article, you learned the following five best practices of exception handling in C#.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Handling common errors rather than throwing exceptions&lt;/li&gt;
&lt;li&gt;  Using already existing exceptions as much as possible&lt;/li&gt;
&lt;li&gt;  Using custom exceptions&lt;/li&gt;
&lt;li&gt;  Using application logging&lt;/li&gt;
&lt;li&gt;  Using throw statements&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One of the most important practices is logging your exceptions to better support the troubleshooting process.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://clearinsights.io"&gt;ClearInsights&lt;/a&gt; is the perfect logging and monitoring tool provider for C# applications. Integrate ClearInsights tools into your application and make debugging your application an easy process. &lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>beginners</category>
      <category>c</category>
    </item>
  </channel>
</rss>
