Tariq Siddiqui, Author at CodeGuru https://www.codeguru.com/author/tariqsiddiqui/ Sat, 18 Mar 2023 03:01:09 +0000 en-US hourly 1 https://wordpress.org/?v=6.3.2 Different Types of JIT Compilers in .NET https://www.codeguru.com/dotnet/jit-compiler-dot-net/ Fri, 17 Mar 2023 02:49:37 +0000 https://www.codeguru.com/?p=19742 The majority of today’s programming languages are written in human-readable form known as source code. Computers, however, cannot understand source code, and, as such, to execute or run source code, compilers are used to convert code into machine language (also known as native code) for the computer to understand the set of instructions (what code […]

The post Different Types of JIT Compilers in .NET appeared first on CodeGuru.

]]>
The majority of today’s programming languages are written in human-readable form known as source code. Computers, however, cannot understand source code, and, as such, to execute or run source code, compilers are used to convert code into machine language (also known as native code) for the computer to understand the set of instructions (what code is) the programmer is issuing. This process is known as compilation.

In this programming tutorial, we will look at the different types of compilation offered in .NET, C#, and ASP.NET.

Read: Top Online Courses to Learn .NET Software Development

What are the Types of Compilation in .NET?

The process of compilation in .NET is performed in two ways: implicitly and explicitly:

    • Explicit compilation: An explicit compiler compiles the source code into machine code prior to the execution of the program. Ahead of Time (AOT) compilers are used to perform explicit compilation so that each line of the code is understood by the CPU before the execution of the program.
    • Implicit compilation: Implicit compilation takes place in two steps. First, the source code is converted into intermediate code (such as MSIL or Microsoft Intermediate Language Code) by the language-specific compiler. In the second step, this intermediate language code is converted into machine code. The difference from an explicit compiler is that, at runtime, only the executed fragment of intermediate language code is compiled into machine code. This type of compilation in .NET is called Just-in-Time (JIT) compilation.

What is JIT Compilation?

JIT is a part of the CLR (Common Language Runtime) in .NET, which is used to execute a .NET program, regardless of which .NET-supported programming language is used.

The program execution in .NET is performed using the following steps:

  • A language-specific compiler converts the programming language code into the intermediate language
  • The intermediate language code gets converted into machine code by the JIT compiler.
  • The machine code generated is specific to the computer platform.

You can learn more about the CLR on Microsoft Learn.

How Does the JIT Compiler Work in .NET?

The JIT compiler converts the intermediate language (IL) or MSIL code into machine code. The MSIL code is then converted as per the requirements of the program only and not the whole of it. .NET also keeps the MSIL code stored so it can access the source code methods on subsequent calls.

Types of JIT Compilers in .NET

.NET has three types of JIT compilers. They are:

  • Pre-JIT compiler
  • Normal JIT compiler
  • Econo JIT compiler

JIT Compilers

We discuss each type of .NET JIT compiler in the following section.

What is a Pre-JIT Compiler

Pre-Jit compiler

The Pre-JIT compiler compiles the source code into machine code in a single compilation cycle. Usually, this type of compilation is performed at the time of application deployment. This is implemented in Ngen.exe (Native Image Generator). The following figure shows the typical function of the Pre-JIT compiler:

What is a Normal JIT Compiler

Normal JIT Compiler

In normal JIT compilation, source code is converted into machine code only the first time it is called by the runtime. After that, it is stored in cache and can be accessed whenever required.

What is an Econo JIT Compiler

Econo JIT Compiler

An Econo JIT compiler compilation method only compiles the functions which are needed at the runtime and removes them once they are no longer required. The Econo JIT compiler became obsolete with the advent of .NET 2.0, but we include it here for awareness and historical purposes.

What are the Advantages and Disadvantages of JIT Compilation in .NET

JIT compilation has the following advantages for .NET developers:

  • JIT performs code optimization by performing statistical analysis.
  • JIT compilation consumes less memory, as only the functions which are required at the runtime are compiled into machine code.
  • JIT compilation is less prone to errors because all the functions required at runtime are on the same memory page.

Along with these advantages, JIT compilation also has its disadvantages in .NET, which include:

  • The JIT compiler takes more startup time when the program is executed for the first time.
  • Cache memory, which is an expensive resource, is used heavily in JIT compilation to store the source code methods, since these methods are required at runtime.

Read: .NET Core versus .NET Framework

The post Different Types of JIT Compilers in .NET appeared first on CodeGuru.

]]>
Middleware in ASP.NET Core https://www.codeguru.com/csharp/asp-net-middleware/ Thu, 16 Mar 2023 01:54:15 +0000 https://www.codeguru.com/?p=19740 Middleware is a piece of computer software that allows software ( such as an internet application) to communicate with databases, servers, and remote machines. Middleware handles the HTTP requests and HTTP responses between a client and a server, which helps developers build better and more efficient software architecture. Read: Best Online Courses to Learn C# […]

The post Middleware in ASP.NET Core appeared first on CodeGuru.

]]>
C# Tutorials

Middleware is a piece of computer software that allows software ( such as an internet application) to communicate with databases, servers, and remote machines. Middleware handles the HTTP requests and HTTP responses between a client and a server, which helps developers build better and more efficient software architecture.

Read: Best Online Courses to Learn C#

In this programming tutorial, we discuss what middleware is, how it can be used, and look at some example of using ASP.NET Core middleware and C# to create web applications.

What is ASP.NET Middleware?

The ASP.NET Core middleware was introduced to lessen the dependency of .NET websites and applications on servers. Before the introduction of middleware, the request and response objects in .NET were tightly-coupled with web servers, which led to poor maintainability of code. Middleware, fortunately, mitigated this problem. In the next section, we will look at how middleware functions in a typical .NET website and leads to better code maintainability.

How does Middleware Work in .NET?

.NET Core middleware makes use of the request pipeline to handle HTTP requests. Developers can configure the request pipeline using different methods, such as run(), map(), and use.

The request pipeline decides whether an HTTP request should be passed to the next component in the pipeline for processing. Apart from that, the request pipeline also takes care of the required actions that need to be performed before – or after – the invocation of a component in the pipeline.

It should be noted that one application can make use of more than one middleware, depending upon the needs of the application. You can utilize the built-in middleware that comes with .NET Core or get them from the NuGet package manager. This is how the middleware functions.

Below are some of the different built-in middleware components available in .NET and their function:

  • Session: Used for user session management.
  • CORS: Used for Cross-origin Resource Sharing (CORS) constraint.
  • Routing: Used for defining and managing routes
  • Authentication: Used for authenticating users and roles

Read: Top Code Refactoring Tools for Developers

How to Set Up a Middleware Pipeline with ASP.NET

ASP.NET Middleware

Now that we have a better grasp of what middleware is, how it functions, its role in the request pipeline, and its components, let’s preview a practical example of how to set up a middleware pipeline for your ASP.NET website.

To achieve this, web developers need to make use of the configure() method, which is defined in the Startup class, whose function is to add the components below to the website lifecycle. It is important to note here that you should take care while defining the order of middleware, otherwise your application might not perform well or become unresponsive:

  • Model-View-Controller (MVC) with the area defined
  • Error handling
  • Session
  • Cookie Policy

We can better understand the importance of middleware through the following code example. Inside the configure() method of the Startup.cs class, we have the following C# code:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/NotFound");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "blog",
        pattern: "blog/{*article}",
        defaults: new { controller = "Blog", action = "Article" });
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Books}/{action=Details}/{id?}");
});

Below is an outline of the workflow of the above code. In this example:

  • The first middleware we used in our example is for error handling. In the development environment we used UseDeveloperExceptionPage and in the production environment we used UseExceptionHandler.
  • Next in the pipeline, we have the UseHttpsRedirection middleware, which redirects the HTTP request to the secure HTTPS.
  • Then, we used UseStaticFiles middleware. Its function is to serve the static files to the browser by adding them to the request pipeline. Usually, static files are stored in the webroot folder and developers can access them through that path. However, it is up to the programmer; you can also store files in any other directory.
  • Next, we use the UseCookiePolicy that adds the CookiePolicyMiddleware handler to the specified request pipeline. It ensures the application should remain compliant with the General Data Protection Regulation (GDPR) standards, laws, and regulations.
  • After this, the next middleware used is UseSession. Its purpose is to provide support for user session management. If you forget to place this middleware, then you will not be able to access the session data.
  • Last up, we have UseMvc. This is the last middleware in our request pipeline. This should be placed at the end of the pipeline so that when it comes to action, all the authentication and session work gets completed.

Final Thoughts on Middleware and ASP.NET

Middleware is one of the beneficial features .NET provides for its developers. Middleware helps ASP.NET developers to develop their websites or web applications with more control over client-server communication. We can use various middleware depending on our project requirements or even create our own customized one.

Read more C# and ASP.NET programming and software development tutorials.

The post Middleware in ASP.NET Core appeared first on CodeGuru.

]]>
Implementing Generic Singly Linked List in C# https://www.codeguru.com/csharp/c-sharp-generic-linked-lists/ Wed, 15 Feb 2023 00:37:57 +0000 https://www.codeguru.com/?p=19702 C# linked lists contain a linear collection of objects called ‘nodes’, which are stored at random memory locations. The first node in the list is a special node known as head, which points to the first element of the list. In the last part of the list, the node may either point to null or […]

The post Implementing Generic Singly Linked List in C# appeared first on CodeGuru.

]]>
C# linked lists contain a linear collection of objects called ‘nodes’, which are stored at random memory locations. The first node in the list is a special node known as head, which points to the first element of the list. In the last part of the list, the node may either point to null or it may point to a special node called tail.

In this programming tutorial, we will learn how to use linked lists in C# and .NET, providing code examples along the way.

Read: Best Bug Tracking Software for C# Developers

C# Nodes in Linked Lists

Note that a node in a linked list is an object that contains two fields; one stores data and the other holds the address of the immediate next node.

What is a Generic

In simple terms, generics allow a developer to use any data type while working with a class or method.

What is a Singly Linked List in C#?

A singly linked list in C# is forward-oriented. That means when a programmer navigates through a list, they can only traverse in one direction. A node in a singly linked list contains its value and the reference of the next node.

C# inked Lists

Important Notes about Linked Lists in C#

The following are some key notes developers should keep in mind when working with linked lists in C# and .NET software development:

  • Linked lists use memory dynamically
  • The LinkedList class implements the ICollection, IEnumerable, and ISerializable interfaces
  • Removal and reinsertion of nodes can be done in the same list or in another list
  • Programmers can store duplicate elements in a C# linked list, provided they are of the same type
  • Each node in a generic LinkedList object is of the type LinkedListNode
  • Linked lists in C# supports enumerators
  • The capacity of a LinkedList is defined as the number of elements it can hold
  • Linked lists do not support chaining, splitting, or cycles, making the list safe for inconsistent states

Constructor Methods for C# Linked Lists

C# provides different constructor methods to make writing code more efficient while working with linked lists. Here is a list of C# constructor methods and what they are used for:

  • LinkedList(): Initializes a new instance of the LinkedList class
  • LinkedList(IEnumerable): Initialize a new instance of the LinkedList class, which contains elements copied from the specified
    IEnumerable
  • LinkedList(SerializationInfo, StreamingContext): Initializes a new instance of the LinkedList class, which can be serialized with the specified SerializationInfo and StreamingContext context

You can learn more about constructors in our tutorial: Introduction to Constructors in C#.

Generic Singly Linked List in C# Code Example

To better understand how singly linked lists in C# work, let’s examine a code example. In this scenario, a generic singly linked list is used to store and retrieve elements using a for each loop:

using System;  
using System.Collections.Generic;  
  
public class MyClass  
{  
    public static void Main(string[] args)  
    {    
        var listOfNames = new LinkedList();  
        listOfNames.AddLast("Rigby Deirdre");  
        listOfNames.AddLast("Cymone Ashlee");  
        listOfNames.AddLast("Rylee Shelley");  
        listOfNames.AddLast("Elaine Teresa");  
        listOfNames.AddFirst("Emmanuel Kourtney");     //adding to the first index  
 
        //   Retrieving list elements  
        foreach (var name in listOfNames)  
        {  
           Console.WriteLine(name);  
        }  
    }  
}

Running this code produces the following output:

Emmanuel Kourtney
Rigby Deirdre  
Cymone Ashlee  
Rylee Shelley  
Elaine Teresa

As you may have anticipated, the output list contains Emmanuel Kourtney at the very first location because we added it using the AddFirst() method; the elements added with AddLast() are added at the next subsequent locations of the list.

For our second scenario, let’s consider another code example of the generic list above, in which we instead add the elements before and after a specific node:

using System;  
using System.Collections.Generic;  
  
public class MyClass  
{  
    public static void Main(string[] args)  
    {  
        var listOfNames = new LinkedList();  
        listOfNames.AddLast("Rigby Deirdre");  
        listOfNames.AddLast("Cymone Ashlee");  
        listOfNames.AddLast("Rylee Shelley");  
        listOfNames.AddLast("Elaine Teresa");  
          
        // Inserting a new element before "Rylee"  
        LinkedListNode node= listOfNames.Find("Rylee Shelley");  
        listOfNames.AddBefore(node, "Ken Heath");  
        names.AddAfter(node, "Denton Atkinson");  
  
        //  Iterating list elements  
        foreach (var name in listOfNames)  
        {  
            Console.WriteLine(name);  
        }  
    }  
}

Here is the output:

Rigby Deirdre  
Cymone Ashlee  
Ken Heath
Rylee Shelley
Denton Atkinson
Elaine Teresa

Here, we got the same output, as expected. Ken Heath is added to the list before, and Denton Atkinson is added after, the specific node Rylee Shelley. We accomplished this using the two methods – AddAfter() and AddBefore(), respectively.

Read: Best Build Tools for C# Developers

The post Implementing Generic Singly Linked List in C# appeared first on CodeGuru.

]]>
Types of Query Execution in LINQ https://www.codeguru.com/dotnet/linq-query-execution/ Thu, 15 Dec 2022 15:14:26 +0000 https://www.codeguru.com/?p=19534 When we think in terms of database performance, there is an important characteristic to emphasize and that is: What are the different behaviors of query execution? Particularly, in the .NET framework component, LINQ, there are two different behaviors of query execution developers should be aware of: deferred and immediate. In this programming tutorial, we will […]

The post Types of Query Execution in LINQ appeared first on CodeGuru.

]]>
.Net Tutorials

When we think in terms of database performance, there is an important characteristic to emphasize and that is: What are the different behaviors of query execution? Particularly, in the .NET framework component, LINQ, there are two different behaviors of query execution developers should be aware of: deferred and immediate.

In this programming tutorial, we will discuss how the deferred query execution and immediate query execution work in LINQ and .NET. In addition, we will discuss the differences between these two types of query executions and examine some .NET sample code for each.

Read: Best Online Courses to Learn .NET

What is Deferred Query Execution in LINQ?

Deferred execution means a query is executed whenever iteration is applied to the query variable. Note, however, that it will not execute when we create the query variable.

To better understand this behavior, consider the following code example:

class Product{
  public int id { get; set;}
  public string Name { get; set;}
  public double Price { get; set;}
}
static void Main(String args[]){
  var prdList = new List(
  new Product[]
  {
      new Product { Id=1, Name=”Dart”, Price=4.5},
      new Product { Id=2, Name=”Mouse Pad”, Price=2.3},
      new Product { Id=3, Name=”Toothpaste”, Price=1.2},
      new Product { Id=4, Name=”Shampoo”, Price=3.5},
  )};
  var list = from p in prdList
                 where p.Price > 3.0
           select new { p.Name } ;
  foreach(var l in list)
  {
      Console.writeline(l.Name);
      Console.ReadLine();
  }
}

Running this code in your integrated development environment (IDE) or code editor would result in the following output:

Dart
Shampoo

If you look at the code example above, you might be guessing the query is executed at the point where we assigned the query result to the variable. However, this is not true.

Instead, the query is executed when we iterate the query variable using a foreach loop. This is known as deferred execution.

To better grasp this, let’s examine another code example, which shows a deferred execution query in LINQ. To start, we will create another Product instance, just after the creation of the query variable:

var list = from p in prdList
                 where p.Price > 3.0
           select new { p.Name } ;

prdList.Add(new Product 
{ Id = 5, Name=”Perfume”, Price=4.0 
});  🡨 Deferred Execution

foreach(var l in list)
{
      Console.writeline(l.Name);
      Console.ReadLine();
}

In the above code example, we created a new Product instance just after the query variable is created. Had the query been executed when we created our query variable, the results would be the same as the one we got in our first code example, which means only two products would meet the criteria of Price > $3.0.

However, when you run the program above, you get a different result, as the query executes after the loop instead:

Dart
Shampoo
Perfume

Here, the execution of the query was deferred until the query variable was iterated over using a foreach loop.

Deferred execution gives flexibility to C# developers by allowing them to construct queries in several steps and separates both the query building and query execution. One of its important use cases is to fetch the latest information from a database that is being updated at frequent intervals.

Read: Best C# Tools for Code Quality

Immediate Query Execution in LINQ

Another method for querying in LINQ is immediate. In this method, developers force a query to execute immediately. It is useful in cases where programmers need to cache the queries.

Let us understand this concept with our previous example. Let’s add a scenario where we need to display the total number of products that match the criteria:

class Product{
  public int id { get; set;}
  public string Name { get; set;}
  public double Price { get; set;}
}
static void Main(String args[]){
  var prdList = new List(
  new Product[]
  {
      new Product { Id=1, Name=”Dart”, Price=4.5},
      new Product { Id=2, Name=”Mouse Pad”, Price=2.3},
      new Product { Id=3, Name=”Toothpaste”, Price=1.2},
      new Product { Id=4, Name=”Shampoo”, Price=3.5},
  )};
  var counter = (from p in prdList
                 where p.Price > 3.0
           select p).Count();   🡨 Immediate Execution
  
  prdList.Add(new Product {
   Id = 5, Name=”Perfume”, Price=4.0
  });  
      Console.writeline(“Number of Products whose price is greater than $3.0 is {0}: , counter);
      Console.ReadLine();
}

In the above code, to count the number of products that match the condition, the query must be executed. And, in this case, the query gets executed automatically when the Count( ) method is invoked.

As we are adding a new product instance after the query variable is declared, this would have no effect here, as the query is already executed. So, the output would be 2 in this case.

Final Thoughts on LINQ Query Executions

In this .NET programming tutorial, we learned about both query execution methods offered by LINQ. The basic difference between the two is that the deferred execution of queries produces a sequence of values, whereas immediate queries get executed immediately and return a single value.</p.

Hopefully, this article has helped novice developers, as well as veterans, understand the fundamentals of query execution methods in LINQ, the basic differences between the two, and their use cases.

Read more .NET programming tutorials and software development guides.

The post Types of Query Execution in LINQ appeared first on CodeGuru.

]]>
Asynchronous Programming Patterns in .NET C# https://www.codeguru.com/csharp/dot-net-asynchronous-patterns/ Tue, 13 Dec 2022 17:10:39 +0000 https://www.codeguru.com/?p=19532 In today’s era of modern programming technologies, it is crucial for developers to know the techniques and principles of Asynchronous programming. If you are familiar with building a website or even a class library in .NET C#, you have probably used Asynchronous counterparts or methods in your applications. In this .NET programming tutorial, we focus […]

The post Asynchronous Programming Patterns in .NET C# appeared first on CodeGuru.

]]>
C# Programming Tutorials

In today’s era of modern programming technologies, it is crucial for developers to know the techniques and principles of Asynchronous programming. If you are familiar with building a website or even a class library in .NET C#, you have probably used Asynchronous counterparts or methods in your applications. In this .NET programming tutorial, we focus on the Task-based Asynchronous Pattern (TAP), which is recommended for modern application development methodologies. Before we dive into TAP, however, let us briefly see what the different Asynchronous patterns .NET offers are.

Read: Best Online Courses to Learn C#

What are the .NET Asynchronous Patterns?

.NET provides three Asynchronous programming patterns. They include:

  • Task-based Asynchronous Pattern (TAP): Since the advent of .NET 4.0, the recommended Asynchronous model in .NET is the Task-based Asynchronous (TAP) model. C# supports TAP through the async and await keywords. In TAP, a single method represents both the initiation and completion of an Asynchronous operation.
  • Event-based Asynchronous Pattern (EAP): EAP was introduced in .NET 2. It represents the event-based legacy model for performing Asynchronous operations. It uses the async keyword and event-handler delegate types. The pattern is no longer recommended for new .NET application development.
  • Asynchronous Programming Model (APM): This is a legacy model that uses the IAsyncResult interface for providing Asynchronous operations. The pattern uses Begin and End methods for implementing Asynchronous behaviour. This pattern is also no longer recommended for new application development.

Task-based Asynchronous Pattern (TAP)

TAP is included in the System.Threading.Tasks namespace and is used to represent the arbitrary Asynchronous action of the code. As its name implies, it is related to a task-based approach. Here, you can think of a ‘Task’ as a process running in the background, either sequentially or in parallel. This Asynchronous model is based on the Task class, which is a representation of the Task Parallel Library (TPL) in C#.

Asynchronous Methods in Task-based Asynchronous Pattern (TAP)

The Task-based Asynchronous Pattern uses the async suffix with the name of the method that returns awaitable types, such as Task, Task, ValueTask, and ValueTask.
For example, developers can implement TAP to achieve the error-handling mechanism in C# in the following ways:

try
{
    var firstResult = await Task.Run(() => DoMultiplication(7,2));
    var secondResult = DoAnotherCalculation(firstResult);
}
catch (TaskCanceledException)
{
    await HandleCancelation();
}
catch (Exception exception)
{
    await HandleError(exception);
}

Read: Unit Testing Asynchronous Code in C#

What are the Use cases of C# Asynchronous Methods?

There are many use cases for Asynchronous methods in C#. For instance, If a programmer is going to run multiple tasks concurrently, they can do so in the following C# code example:

var backgroundTasks = new[]
{
    Task.Run(() => DoMultiplication(7,1)),
    Task.Run(() => DoMultiplication(8,4)),
    Task.Run(() => DoMultiplication(3,6))
};

All this code does is start all of the tasks at the same time and collect their references in an array named new[].

The Task class also provides some static helper methods to allow developers to wait until all of the tasks are completed; the static helper methods of the Task class are list below:

Task.WaitAll(tasks);
await Task.WhenAll(tasks);

Programmer can use the following pair of methods in cases where you only want one method to complete before continuing execution:

Task.WaitAny(backgroundTasks);
await Task.WhenAny(backgroundTasks);

Since some of the tasks can run for a while, you might want to cancel them before their execution completes. In that case, you can trigger the cancellation with the following C# code example:

var tokenSource = new CancellationTokenSource();
var cancellableTask = Task.Run(() =>
{
    // do long-running processing   

}, tokenSource.Token);

// Cancellation of the task

tokenSource.Cancel();
try
{
    await cancellableTask;
}
catch (OperationCanceledException)
{
    // handle cancelation exception
}

C# Asynchronous Methods for I/O operations

Since the release of .NET 4.0, Asynchronous methods have been added to the existing classes for input/output and I/O-related operations. For example, the FileStream class provides the following methods for performing operations Asynchronously in C#:

using (FileStream src = new FileStream(srcFile, FileMode.Open),
                  dest = new FileStream(destFile, FileMode.Create))
{
    await src.CopyToAsync(dest);
}

Here is another example code example of how to use the FileStream class in C#:

using (var http = new HttpClient())
{
    var data = await http.GetStringAsync(url);
}

The above code example is of the HttpClient class, which is primarily used for performing HTTP network operations. As you can see, the class provides helpful methods for Asynchronous data operations. In the above code example, we have used one of its async methods: GetStringAsync.

What is the Target Environment for Asynchronous Execution in C#?

How do you determine where the Asynchronous execution is going to occur when implementing TAP? You can implement it in any number of potential contexts. You may run it on the UI thread, or use a thread pool for Asynchronous I/O operation. A TAP method can even have nothing to execute, and in that case, it would simply return a Task.

The caller method of the TAP method could block, waiting for the TAP method to complete the execution by synchronously waiting on the dependent task, or, it could create continuation code upon the Asynchronous operation completion. The creator of this additional continuation code would have control over where they want the code to execute. This can be achieved implicitly using language features such as await in C# or through the Task class explicitly.

Read: Handling Exceptions in Asynchronous Methods in C#

Final Thoughts on Asynchronous Programming Patterns in C# and .NET

In this programming tutorial, we discussed, broadly, Asynchronous patterns in C# and .NET. Specifically, we focused on the Task-based Asynchronous Pattern (TAP) and previewed some example code and use cases for using it in our C# software development practices. We will be following up with future tutorials covering other Asynchronous patterns. Until then, check out some of our other C# software development guides and programming tips.

The post Asynchronous Programming Patterns in .NET C# appeared first on CodeGuru.

]]>
How to Create Razor Pages in .NET Core https://www.codeguru.com/dotnet/razor-pages-dot-net/ Sun, 09 Oct 2022 20:36:45 +0000 https://www.codeguru.com/?p=19470 ASP.NET Core 2.0 introduced the concept of Razor Pages and it was a useful addition to the existing features of .NET Core. Razor Pages are similar to the web forms model of ASP.NET web forms. What is a Razor Page? A Razor Page is more like a web form in the sense that it is […]

The post How to Create Razor Pages in .NET Core appeared first on CodeGuru.

]]>
ASP.NET Core 2.0 introduced the concept of Razor Pages and it was a useful addition to the existing features of .NET Core. Razor Pages are similar to the web forms model of ASP.NET web forms.

What is a Razor Page?

A Razor Page is more like a web form in the sense that it is focused on a single functionality, namely: view. A Razor Page has a view and a tightly coupled code logic that gets executed when any action is performed on the view of that page. A Razor Page allows the application to use cohesive code, which cannot be so effectively achieved using traditional Model-View-Controller (MVC) design patterns.

In this programming tutorial, we will be using ASP.NET Core 3.1 to create Razor web pages. The code examples used in this tutorial will work fine in any .NET application running version 3.1 or above, but if you are using a .NET version lower than version 3.1, you might need to perform some updates or the app examples will not work properly.

Let’s get started utilizing Razor Pages in ASP.NET using the default coding conventions.

Looking to learn how to program applications with C#? We have a list of the Best Online Courses to Learn C# to help you get started.

How to Add a Razor Page to an ASP.NET Application

As you may already know, when we add controllers in an MVC application, they are added to the Controllers folder and all the views reside in the Views folder. In the same way, Razor Pages are added conventionally to the Pages folder. This is the default file storage convention. Developers can also add Razor Pages in another folder, but they would not work properly unless the same convention is followed.

To create a Razor Page in a .NET Core app, open up Visual Studio. You need to first create a folder named Pages and then right-click the folder, select the Add option, and select Razor Page to create a new Razor Page.

Razor Pages in ASP.NET

Give the newly created Razor page a name. For the examples in this tutorial, we are naming the page Index.cshtml. After you click on the Add button, Visual Studio will automatically create two files: the first one is an Index.cshtml file and the other one is an Index.cstml.cs file, which is just a behind-the-scenes file of our Index HTML View.

Razor Page tutorial

Inside the PageModel class, we set the public property ‘Message’ in the onGet handler, as seen here:

public class IndexModel : PageModel
    {
        public string Message { get; set; }
        public void OnGet()
        {
             this.Message = "Hello there!";
        }
  }

Next, inside the Razor HTML page, we displayed the ‘Message’ property by accessing it from the Razor PageModel class:

@page
@model RazorPageExample.Pages.IndexModel
@{
    Layout = null;
}
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <h3>@Model.Message</h3>
</body>
</html>

Read: Top Unit Testing Tools for Developers

Routing Razor Pages

Next, let’s see how routing is configured when working with Razor pages. Conventionally, Razor Pages are directly mapped to physical files. This means if you have a file named Index.cshtml, then it can be accessed by the following route:

http://<your_domainname>/Index

But note that, to utilize Razor Pages in a .NET app, you need to first enable the support for Razor Pages inside the startup.cs class file.

First, configure the service in the ConfigureServices method to use Razor Pages in an ASP.NET web app:

configureservices Razor Page method

Next, configure the routing endpoints accordingly:

Razor Pages Routing Endpoints

Model Binding in an ASP.NET Razor Page

As in Model-View-Controller (MVC) architecture, the parameter of an action method is bound to the incoming request by matching values in the query string, URL, or body of the request. Razor Pages, on the other hand, bound the incoming request with the properties of PageModel.

Note that developers have to explicitly bind the properties using the [BindProperty] attribute. The following example shows the two properties – one of which is bound to the request and that is decorated with [BindProperty] and the other (the one without the attribute), which is not:

using Microsoft.AspNetCore.Mvc.RazorPages;
public class IndexModel : PageModel
{
    [BindProperty]
    public string CompanyName { get;set; }

    public string Address { get; set; };
}

Razor Page Handlers

One advantage of using Razor Pages is that they bring cohesion in code maintainability, as opposed to the MVC architecture, which does not. A Razor Page responds to requests by using page handlers. You can think of page handlers as being similar to action methods in MVC. Razor Pages execute a single handler based on the handler name and request when receiving a request from a user. They use the following convention to match a handler request:

On{Verb}[Async] 
Where {Verb} is an HTTP method, and
[Async] is optional 

In any typical HTML form, the OnGet handler initiates an empty form while the OnPost handler handles the post request generated by the client. To understand it better, consider the following code snippet, in which we are fetching the username from a service in an OnGet() method and updating it in the OnPostAsync() method:

[BindProperty]
public InputModel Input { get; set; }

public void OnGet()
    {
        Input.UserName = mailService.GetUserName();
    }

    public async Task OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            // return page
        }

        mailService.UpdateUserName(User, Input.UserName);
        return RedirectToPage("/Index");
    }

Final Thoughts on Razor Pages in ASP.NET

Razor Pages are built on top of ASP.NET primitives, which serve the same functionality as the MVC architecture, but with a page-based approach. In the modern world, there are many apps which require code to be cohesive in order to operate effectively, and in such scenarios programmers can use PageModel, which is a page-based approach used in Razor Pages, to meet the demands of such apps.

Read more ASP.NET programming tutorials and software development tips.

The post How to Create Razor Pages in .NET Core appeared first on CodeGuru.

]]>
C# Output https://www.codeguru.com/csharp/c-sharp-output/ Fri, 07 Oct 2022 19:25:29 +0000 https://www.codeguru.com/?p=19469 In the previous part of our ongoing C# programming tutorial series, we learned how a developer can perform input operations leveraging the Console class. In this article, we will demonstrate how a programmer can print output in a C# application. Let’s first look at the different methods and classes used for creating output in the […]

The post C# Output appeared first on CodeGuru.

]]>
C# Programming Guide

In the previous part of our ongoing C# programming tutorial series, we learned how a developer can perform input operations leveraging the Console class. In this article, we will demonstrate how a programmer can print output in a C# application. Let’s first look at the different methods and classes used for creating output in the popular programming language.

You can read or review the previous part of this C# tutorial by visiting: C# User Input.

How to Print User Output in C#

In the System namespace, there is a Console class, which contains several built-in methods. These methods allow programmers to get user input and produce output to the console window. Two of the most common methods used for the purpose of standard input/output (I/O) operations are:

  • Write()
  • WriteLine()

To better understand the practical use of both of these methods, observe the following code example, which shows how to print output to the console window in C#:

using System;
namespace IOProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hi there!");
        }
    }
}

If you run this code, you get the following output:

Hi there!

The code uses the WriteLine() method to print the output – in this case the text written between the two quotation marks – to the standard output stream or console.

What is the Difference Between Write() and WriteLine() in C#?

The Write() and WriteLine() methods serve the same purpose – producing output to the console. The only difference between the two is that the Write() method only prints the provided string to the console window, while the WriteLine() method not only prints the provided string, but also moves the prompt to the start of the next line in the console.

Let’s understand the difference by examining the output of the following example code:

using System;
namespace IOProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Printing using WriteLine ");
            Console.WriteLine("Places this text in a new line");
            Console.Write("Printing using Write ");
            Console.Write("… places it in the same line");
        }
    }
}

Running the above code snippet in your integrated development environment (IDE) or code editor would result in the following output:

Printing using WriteLine
Places this text in a new line
Printing using Write … places it in the same line

Read: Best Online Courses to Learn C#

How to Concatenate Strings in C# using Write() and WriteLine()

You can concatenate – or join – two or more strings in C# by using the + operator inside the WriteLine() or Write() methods. Here is an example showing string concatenation in C#:

using System;
namespace IOProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            double digit = 77.32;
            Console.WriteLine("This is how strings are combined " + "in C#");
            Console.WriteLine("Given digit is = " + digit);
        }
    }
}

Running the above code results in the following output:

This is how strings are combined in C#
Given digit is = 77.32

The above code demonstrates how programmers can combine two or more strings using the + operator. You can concatenate or combine strings in two ways. The first one is using the + operator which we have seen, or via a second method that is more efficient, which we will discuss in the following section.

Other Ways to Concatenate Strings in C#

There is an alternate way to concatenate strings in C# and that is using a formatted string. Notice in the example below, we will be using placeholders for variables. When the code executes, the placeholders get replaced by the corresponding variables. To make it clear, consider the following code snippet:

class Program
    {
        static void Main(string[] args)
        {
            int x = 7, y = 5, mul;
            mul = x*y;
            Console.WriteLine("{0} x {1} = {2}", x, y, mul);
        }
    }

When you run the program, {0} will be replaced by x, {1} will be replaced by y, and {2} will be replaced by the multiplication variable mul. As you can see, the approach we used in the above code is more readable and less prone to errors when compared to using the + operator to concatenate strings.

Printing Variables and Literals in C#

The Write() and WriteLine() methods can be used for printing literals and variables as well. The following program demonstrates how you can perform this standard output operation in C#:

    class Program
    {
        static void Main(string[] args)
        {
            int x = 55;
            Console.WriteLine(x);	 // prints variable
            Console.WriteLine(0.006);  // prints literal value
        }
    }

Running the above code results in the following output:

55
0.006

In this code, we first created an integer named x and assigned it the value 55. We then used WriteLine() to print out the value of our variable.

In our next statement, we passed a literal value – 0.006 – to the WriteLine() function, which was subsequently printed to the user’s screen.

Read more C# programming tutorials and software development tips.

The post C# Output appeared first on CodeGuru.

]]>
C# User Input https://www.codeguru.com/csharp/c-sharp-user-input/ Tue, 04 Oct 2022 16:57:34 +0000 https://www.codeguru.com/?p=19468 In this programming tutorial, we will cover how to perform basic Input/Output (IO) operations in C#. In particular, developers will learn how a user provides input to the system in a .NET and C# application. Looking to learn C# in an online course environment? We have a list of the Best Online Courses to Learn […]

The post C# User Input appeared first on CodeGuru.

]]>
C# Programming Guide

In this programming tutorial, we will cover how to perform basic Input/Output (IO) operations in C#. In particular, developers will learn how a user provides input to the system in a .NET and C# application.

Looking to learn C# in an online course environment? We have a list of the Best Online Courses to Learn C# to help get you started.

How to Accept User Input in C#

The simplest method to get input from a user in C# is to use one of these three methods: ReadLine(), ReadKey(), or Read(). They are all contained in the Console class and can be called directly with their class name, as they all are static methods.

C# ReadLine() Method

Let’s start with the most frequently used method to accept user input: ReadLine(). Below is some example code of a .NET Console app built in C# that shows how to get string input from a user with ReadLine():

using System;
namespace InputProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            string text;
            Console.Write("Enter string:");
            text = Console.ReadLine();
            Console.WriteLine("You entered : {text}");
        }
    }
}

When you run the above program in your integrated development environment (IDE) or code editor, you get the following result:

Enter string:  Wish I’m on the Everest
You entered: Wish I’m on the Everest

C# Read() and ReadKey() Methods

Like ReadLine(), the Read() and ReadKey() methods are also used for accepting input data from the user; however, there are some differences in the way these two methods manipulate the received input:

  • Read(): This method reads the next character from the C# input stream – or command line – and returns the ASCII value of that character.
  • ReadKey(): This method obtains only the next key from the input stream. It is also used to hold the screen until the user presses a key. An example is to let the user press Y or N to continue in an interactive application.

The following code example illustrates how to get input from the user using the Read() and ReadKey() methods in C#:

Example of Console.ReadKey():
int text;
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
Console.WriteLine();

The above code snippet results in the following output:

Press any key to continue…

Were there further code below the Console.ReadKey() and Console.WriteLine(), it would be triggered once the user pressed any key on their keyboard. Since there is no further code, the program simply exits once the user presses a key.

Here is an example of how to use the Read() method in C#:

Example of Console.Read():
Console.Write("Enter any character - ");
input = Console.Read();
Console.WriteLine("Ascii Value of given character= {0}", input);

Here, the program prompts a user to ”Enter any character – “. It then accepts whatever text the user enters until the user presses the Enter or Return key. It then takes this value and writes it, and the preceding text (ie; “Ascii Value of given character =”) to the screen.

Read: Working with C# Output

How to Read Numerical Values in C#

C# has easy methods for reading strings or characters – all programmers need to do is to call the corresponding methods, like Read(), ReadKey(), or ReadLine() as shown above. However, dealing with numerical values requires a little more effort on behalf of the developer.

In the next code example, we will use the same method – ReadLine() – to receive input as a string, but we will then do a little extra work to convert the string to an integer or floating-point type.

C# has a Convert class that contains several methods to convert a string type into an integer or floating-point type. The following code examples show how to read numerical values in C# from a user’s input:

Example 1
using System;
namespace TypeCastDemoProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            string input;
            int val;
            Console.Write("Enter an integer value: ");
            input = Console.ReadLine();
            // Converting to integer type
            val = Convert.ToInt32(input);
            Console.WriteLine("You entered: {0}", val);
        }
    }
}

Running this code produces the following output:

Enter an integer value: 
You entered: 

The ToInt32() method we used in the above code snippet belongs to the Convert class, which converts the string provided by the user into an integer type. This process is called typecasting. Note that the output above is blank – if a user were to input data, the converted version would follow the sentence: ”You entered: “.

Here is our second example, showing how to convert to a decimal or floating-point value:

Example 2
using System;
namespace TypeCastDemoProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            string input;
            double val;
            Console.Write("Enter a double value: ");
            input = Console.ReadLine();
            // Converting to double type
            val = Convert.ToDouble(input);
            Console.WriteLine("You entered {0}", val);
        }
    }
}

Here, the ToDouble() method also belongs to the Convert class, which converts the given string into a double type. You can also convert it to other types, as per your needs. If you right-click on the Convert class and go to its definitions, you will come across different methods that allow a user to typecast the given data into the desired type.

Reading Input and Typecasting in C#

There are alternate ways to read numeric value input in C#. In addition to the above, you can perform both operations – reading input and typecasting it – into a single line, as depicted in the following code:

Console.Write("Enter integer value: ");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You entered {0}", x);
Console.Write("Enter double value: ");
double y = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("You entered {0}", y);

This method is more efficient and requires fewer lines of code than our previous examples.

Read more C# programming tutorials and software development guides.

The post C# User Input appeared first on CodeGuru.

]]>
.NET Core versus .NET Framework https://www.codeguru.com/dotnet/net-core-versus-net-framework/ Sat, 17 Sep 2022 02:44:44 +0000 https://www.codeguru.com/?p=19437 Today, we will be discussing the differences between .NET and .NET Core so you can easily choose the right .NET runtime for your next project. In the upcoming sections of this programming tutorial, we will see how we can make the best of each of them. Read: The Top Online Courses to Learn .NET What […]

The post .NET Core versus .NET Framework appeared first on CodeGuru.

]]>
.Net Tutorials

Today, we will be discussing the differences between .NET and .NET Core so you can easily choose the right .NET runtime for your next project. In the upcoming sections of this programming tutorial, we will see how we can make the best of each of them.

Read: The Top Online Courses to Learn .NET

What is the .NET Framework?

In the beginning, the .NET Framework was used only on Windows operating systems. However, with the advent of Mono projects and Xamarin, it can now run on macOS, mobile devices, and Linux operating systems as well.

The .NET architecture is made up of the following components:

  • CLS: The Common Language Specification (CLS) defines the way objects are implemented so they can work everywhere .NET works.
  • CLR: The Common Language Runtime (CLR) is a virtual machine used to run and manage .NET programs.
  • Framework Class Library: A .NET standard library consisting of interfaces, reusable classes, and value types.
  • Visual Studio: Visual Studio is an integrated development environment (IDE) used to create web apps, cloud apps, standalone applications, websites, and web services.

Both .NET and .NET Core runtimes are used for building applications using .NET standards. The .NET Standard comprises a common set of APIs with which code can be shared across different platforms, such as cloud apps and services, desktop applications, web apps, and so forth.

The .NET Framework is primarily used for creating web applications, server-side applications, and desktop applications. On the other hand, .NET Core is used to create server-based applications and web applications that can be developed and deployed cross-platform. .NET Core does not currently support developing desktop applications using a user-interface.

What is .NET Core?

.NET Core is an open-source and cross-platform technology that is the best suitable option for the development of an application that can be run on any platform. .NET Core is also used for developing large enterprise applications and for developing cloud-based applications.

When Should Developers Use .NET Core?

We recommend using .NET Core when the following apply:

  • CLI (Command Line Interface) Tools Are Needed: Some programmers prefer to work with a lightweight and moderate command-based tool. .NET Core has a CLI-based tool that requires minimum installation on the machine, although developers can switch to an IDE, such as Visual Studio or Visual Studio Code, later if they do not want to work with command-based tools.
  • Running multiple .NET versions in Parallel: .NET developers can take the leverage of running multiple services (with different .NET versions) on the same server through .NET Core.
  • Cross-platform Needs: .NET Core code can run efficiently on different platforms, such as macOS, Windows, and Linux. Moreover, Microsoft’s most popular IDE Visual Studio supports all major OS’ today and the list is still growing. Apart from Windows, Visual Studio can be run on macOS with a limited version and on Linux too.
  • Microservices: Microservices are small pieces of software consisting of modular business components. These components contain unique features that can be deployed independently. .NET Core is lightweight and compatible with the creation of these micro-services.
  • Docker Containerization: Container architecture is also lightweight and modular, in the same way as Microservices architecture. .NET Core allows cross-platform server apps to deploy on containers with ease.

Read: The Top Task Management Tools for Developers

When Developers Should Not Use .NET Core

We do not recommend using .NET Core if the following apply.

You encounter a situation where .NET Core might not be a great option. This might be possible due to a lack of support for certain libraries or extensions. Consider the following scenarios:

  • No Support for WPF Applications: If you wish to develop desktop applications on macOS, then you need some other compatible software framework, such as Mono, to work on macOS.
  • .NET Features Are Missing: A few features of .NET are not present in .NET Core. For instance, Entity Framework Core no longer has the same package of features that Entity Framework v6 had.
  • No Current Support for WCF: .NET Core does not support WCF. Instead, you have to use RESTful APIs to carry out the functionality you want to achieve using WCF.

When Developers Should Use .NET Framework

.NET is shipped with Windows. It can be used for building large-scale business applications using different data connection tools. Some of the services provided by the .NET framework include:

  • Memory Management
  • Developing APIs
  • Data Structures
  • Application deployment

Developing applications in .NET is feasible when:

  • You Want to Use a Service Not Available in .NET Core: There are some technologies in .NET which .NET Core does not support, including: ASP.NET Web Forms, ASP.NET SignalR, Windows Communication Foundation, WCF Data Services, and Windows Presentation Foundation.
  • Using Packages and Libraries Not Available in .NET Core: Despite the great popularity of .NET Core, some third-party libraries are not compatible with it, so in this situation developers need to switch to the .NET Framework.
  • Platforms Not Supporting .NET Core: There are some Microsoft and other third-party platforms which still do not support .NET Core. For instance, some of the Azure services are not still compatible with .NET Core.

When Developers Should Not Use .NET Framework

There are some scenarios where using the .NET Framework is not suitable. These include:

  • When an open source project workflow is required.
  • You want to create a cross-platform application.
  • Where high performance and scalability are required.

Platforms Supporting .NET Standards

As we already know, the .NET Standard comprises a common set of APIs that ensures code sharing across mobile applications, desktop applications, and cloud services is possible.

Apart from .NET Framework, and .NET Core, there are so many other platforms that are supported by .NET Standards. They are listed below:

  • Mono: Mono is an open source platform based on the Common Language Infrastructure (CLI). Collaborated by Microsoft, it supports ECMA standards. This platform does not limit .NET developers to only using C#, but they can also use Python, Ruby, Java, and Visual Basic.
  • Windows Phone: Windows Phone was primarily developed for mobile consumers and was based on the .NET Framework. It was replaced by Windows 10 Mobile in 2015.
  • Windows Phone Silverlight: This deprecated mobile application platform was created to run internet applications smoothly on Windows Mobile devices. It is no longer supported.

Read more .NET programming tutorials and software development tips.

The post .NET Core versus .NET Framework appeared first on CodeGuru.

]]>
Creating a Minimal API in .NET Core https://www.codeguru.com/dotnet/dot-net-api/ Wed, 24 Aug 2022 17:48:55 +0000 https://www.codeguru.com/?p=19399 Minimal APIs are HTTP based web APIs that can perform functions with minimal resources. Minimal APIs are a great option for applications that require limited files, fewer features, and the least dependencies. In this programming tutorial, we will discuss the steps involved in creating a minimal API in .NET 5.0. Before seeing what it takes […]

The post Creating a Minimal API in .NET Core appeared first on CodeGuru.

]]>
Minimal APIs are HTTP based web APIs that can perform functions with minimal resources. Minimal APIs are a great option for applications that require limited files, fewer features, and the least dependencies.

In this programming tutorial, we will discuss the steps involved in creating a minimal API in .NET 5.0. Before seeing what it takes to build an API, let’s first look at the basic requirements for building our web application:

  • .NET 5.0 SDK (Software Development Kit)
  • Visual Studio or Visual Studio Code
  • If you are using Visual Studio Code, then you need the C# Extension for Visual Studio Code.

For this project, we are going to create a simple minimal APIs for manipulating country data.

Are you looking to learn how to develop software in .NET in a classroom or online course environment? We have a list of some of the Best Online Courses to Learn .NET to help get you started.

How to Create a .NET API Project

To create a Web API project using .NET, developers need to open a command prompt in a folder where you want to create your project and run this command there:

dotnet new webapi -o WebApiDemo

Here, –o denotes the name of the output directory, which in our case is WebApiDemo; you can give any desired name to the project.

After the project is successfully created, the project template automatically creates a WeatherForecastController.cs file in the Controllers folder of the project, containing the boilerplate code that you need to get started with an API controller. We will come back to the controllers’ part, but for now, let’s get started with creating an entity class.

Creating an Entity Class in .NET

The entity class represents the data for our entity Country. For simplicity, I am using a minimal set of properties, including the Country’s Id and Name.

Create a new folder inside the Project directory with the name Entities. Then, create a new class named Country inside the Entities folder.

Add the two properties depicted below with the following code:

    public class Country
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Create the Countries Controller

Inside the Controllers folder, create a new C# class and give it the name CountriesController.cs. Make sure that you put the Controller suffix in the name of the controller. Add the following code to the newly created controller class:

namespace WebApiDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class CountriesController : ControllerBase
    {
        private List _countries = new List
        {
            new Country { Id = 1, Name = "USA" },
            new Country { Id = 2, Name = "Australia" },
 		  new Country { Id = 3, Name = "Denmark" }
        };

        [HttpGet]
        public IActionResult GetAll()
        {
            return Ok(_countries);
        }

        [HttpGet("{id}")]
        public IActionResult GetById(int id)
        {
            var country = _countries.Find(x => x.Id == id);
            if (country == null)
                return NotFound();
            return Ok(country);
        }
    }
}

Let’s understand, step-by-step, what we have done so far in this C# code. We have created a class, CountriesController, which is derived from a built-in .NET base class, ControllerBase. The ControllerBase class helps developers handle HTTP requests like Ok() and NotFound() using its predefined methods and properties.

Next, we used the ApiController attribute, which is placed just above the class definition:

    [ApiController]
    [Route("[controller]")]
    public class CountriesController : ControllerBase
    {
	…
         }

This attribute helps simplify the API development process by calling the corresponding action method based on parameter name and type (such as [FromBody], [FromQuery], etc.) and sending a bad HTTP response message back to the client in case the request is not processed successfully.

Next, we used the [Route(“Controller”)] attribute: [Route(“[controller]”)] .This attribute allows the controller name to be used as a base route for all the action methods.

Inside the CountriesController class, we used two methods – GetAll() and GetById(int) – to fetch the records conditionally. The former method returns a list of all products with a 200 OK HTTP status code. The [HttpGet] attribute is used here to make sure that it matches only HTTP GET requests. As you can see, there is no route template parameter defined there, so it matches the base path, (i.e. /countries.

Coming to the next method: GetById(int). This method will return a specified country based on the id value, and returns a response with Ok(). If there is no matching record found for that id, then it will return NotFound().

We also used another constraint attribute, which is [HttpGet(“{Id}”]. This attribute works the same way that [HttpGet] does; the only difference here is that the {id} gets automatically bound with the int id parameter of the GetById() method.

Read: Introduction to Web Components API

Starting the API

So far, we have set up our API with minimal resources. The next thing we must do is launch our API. To launch the API, we need to go to the project root folder, open the command line, and then run the following command:

dotnet run

Once the API gets running, you will be able to see a message on the command line something that looks some along the lines of this:

How to Start an API in .NET

How to Test the Web API Using Postman

Now it is time to test our application. We will be using a tool called Postman. If you are not familiar with Postman – it is one of the preferred tools to test APIs by developers.

Fetching Entities from the API

The following steps allow us to fetch all country records from the API using Postman:

  • Open the Postman app, and click on the Plus (+) icon at the end of the tab to create a new request tab.
  • Select the GET method on the left side of the URL input field.
  • In the URL field, paste the address of your local API followed by the countries route, such as: https://localhost:5001/countries.
  • Click the Send button.

You will receive a response containing all the countries in a JSON array format.

.NET API examples

Screenshot depicting the request made to get all countries through Postman

Retrieving a Single Entity from an API in .NET

Developers can retrieve a specified product from the API using the Postman tool by following these steps:

  • Open the Postman app, and click on the Plus (+) icon at the end of the tab to create a new Request tab.
  • Select the GET method on the left side of the URL input field.
  • In the URL field, paste the address of your local API followed by the countries details route, such as: https://localhost:5001/countries/2.
  • Click the Send button

You will receive a response containing the details of a specified country in the JSON object.

C# API Tutorial

Screenshot depicting the request made to get a specified country through Postman.

Read more .NET programming tutorials and software development guides.

The post Creating a Minimal API in .NET Core appeared first on CodeGuru.

]]>