.NET Archives | CodeGuru https://www.codeguru.com/dotnet/ 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.

]]>
Intro to Intel oneDAL and ML.NET https://www.codeguru.com/dotnet/intel-onedal-ml-net/ Mon, 16 Jan 2023 22:03:18 +0000 https://www.codeguru.com/?p=19643 Microsoft and Intel are teaming up for the latest upcoming release of ML.NET 3.0. We will briefly discuss what ML.NET is and its role in machine learning and software development. Read: Microsoft Teams Review What is Machine Learning? Machine learning (ML) is the scientific study of algorithms and models that computers use to perform tasks […]

The post Intro to Intel oneDAL and ML.NET appeared first on CodeGuru.

]]>
ML.NET tutorials

Microsoft and Intel are teaming up for the latest upcoming release of ML.NET 3.0. We will briefly discuss what ML.NET is and its role in machine learning and software development.

Read: Microsoft Teams Review

What is Machine Learning?

Machine learning (ML) is the scientific study of algorithms and models that computers use to perform tasks without using explicit instructions, relying solely instead on patterns and inference. Machine learning algorithms build models based on training data, to make decisions without being explicitly programmed to do so.

Common machine learning methods include:

  • Supervised machine learning algorithms: Apply what has been learned to new data by using labels to predict future events.
  • Unsupervised machine learning algorithms: Used when the training information provided is not classified or labeled.
  • Semi-supervised machine learning algorithms: Uses both labeled and unlabeled data for training.
  • Reinforcement machine learning algorithms: Interacts with its environment by producing actions.

What is ML.NET?

ML.NET is a free software machine learning library for C#, VB.NET, and F#. ML.NET includes transforms for feature engineering, such as n-gram creation. ML.NET also includes transforms for learners to handle binary classification, multi-class classification, and regression tasks. ML.NET also includes anomaly detection, recommendation systems, and deep learning (DL).

What is Intel oneAPI Data Analytics Library (oneDAL)

Intel oneAPI Data Analytics Library is a library that speeds up data analysis. This is done by providing optimized algorithmic building blocks for all stages of both the data analytics and the machine learning process.

oneDAL makes use of the EXPLAIN SIMD extensions in 64-bit architectures featured in Intel and AMD CPUs.

oneDAL Components in ML.NET

By integrating with ML.NET, oneDAL accelerates existing trainers during training, using the following trainer extensions:

  • Ordinary Least Squares (OLS): Used for regression
  • L-BFGS (Limited-Memory Broyden-Fletcher-Goldfarb-Shanno Algorithm): Used for classification
  • FastTree: Used for regression and classification
  • FastForest: Used for regression and classification

In order to get started, programmer will need to install the latest Microsoft.ML 3.0 preview version. Note: you may also need to install the Microsoft.ML.Mkl.Components package for OLS: Microsoft.ML.Mkl.Components.

In addition, you may need to install the Microsoft.ML.FastTree package if you are planning to use FastTree: Microsoft.ML.FastTree.

After that, developers will want to install the Microsoft.ML.OneDAL NuGet package: Microsoft.ML.OneDAL.

Finally, you will need to set the system’s MLNET_BACKEND environment variable to ONEDAL. You can use the quick code snippet below to do so:

Environment.SetEnvironmentVariable("MLNET_BACKEND", "ONEDAL");

ML.NET and oneDAL Example

Below is a quick example of how to make use of ML.NET and oneDAL by setting its trainers:

var trainer = ML.BinaryClassification.Trainers.FastForest(options);
var model = trainer.Fit(preprocessedTrainingData);
var trainingPredictions = model.Transform(preprocessedTrainingData);
var trainingMetrics = ML.BinaryClassification.EvaluateNonCalibrated(trainingPredictions, labelColumnName: "target");
var testingPredictions = model.Transform(preprocessedTestingData);
var testingMetrics = ML.BinaryClassification.EvaluateNonCalibrated(testingPredictions, labelColumnName: "target");

GitHub has a more detailed example of how to get started with oneDAL and ML.NET to help you get started.

Read more C# programming tutorials and software development tips.

The post Intro to Intel oneDAL and ML.NET 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.

]]>
Best Microsoft Certifications for Developers https://www.codeguru.com/dotnet/microsoft-developer-certifications/ Tue, 01 Nov 2022 13:21:45 +0000 https://www.codeguru.com/?p=19512 Are you a developer looking to boost your resume and your bottom line? Getting a Microsoft certification can help you do just that. Here are some of the best Microsoft certifications for developers. Do you want to learn how to program C# in an online setting? We have a list of the Best Online Courses […]

The post Best Microsoft Certifications for Developers appeared first on CodeGuru.

]]>
Microsoft Certifications

Are you a developer looking to boost your resume and your bottom line? Getting a Microsoft certification can help you do just that. Here are some of the best Microsoft certifications for developers.

Do you want to learn how to program C# in an online setting? We have a list of the Best Online Courses to Learn C#.

The Top Microsoft Certifications For Developers

Whether you are an aspiring developer or an experienced one, there are several reasons to get a Microsoft certification. First, Microsoft sits near the top of the tech industry since so many people use its products. In other words, it looks to stay relevant well into the future. Second, a Microsoft certification is a great way to enhance your resume, which can help if you are looking to break into the development field or want to move on to bigger and better things with another company. Third, a Microsoft certification can increase your earning power. Fourth, it can give you job security and keep you ahead of the competition looking to get hired by your employer and possibly take your job. And, lastly, the path to getting a Microsoft certification can teach you essential skills along the way by either strengthening your current skill set and knowledge or teaching you some entirely new things.

What are some Microsoft certifications for developers that are worth looking into? Here is a list of some of the best of the bunch that are highly sought after by employers.

Microsoft Certified: Azure Developer Associate

The Azure Developer Associate certification is worth going after if you already have one of the following certifications or are working towards them: MCSD: App Builder, MCSA: Web Applications, or MCSA: Universal Windows Platform. You should also consider getting the Azure Developer Associate certification if your current position has you working with all cloud development phases, such as development, requirements definition and design, monitoring, deployment, performance tuning, and maintenance.

Developers can begin training for the Azure Developer Associate certification via the Exam AZ-204: Developing Solutions for Microsoft Azure study guide. It will tell you what to expect on the exam and give you a summary of topics that the test may cover. The study guide also features additional resources, such as practice tests, that can help you fine-tune your knowledge before taking the exam. Microsoft Learn also offers self-paced training to help you prep for Exam AZ-204 with several modules on Azure development. There is also an option for instructor-led training through Course AZ-204T00: Developing Solutions for Microsoft Azure. This intermediate-level course takes five days to complete and teaches you how to develop end-to-end solutions in Azure. Lastly, the Microsoft Learn Exam Readiness Zone is filled with tons of tips and tricks from experts to help you prepare for the Azure Developer Associate exam.

Once ready, you can take and pass Exam AZ-204 (it costs $165) to earn your certification. It will measure several skills to ensure you are proficient in the material, such as developing for Azure storage, developing Azure compute solutions, connecting to and consuming Azure and third-party services, monitoring, troubleshooting, and optimizing Azure solutions, and implementing Azure security.

Once you get this certification, you can get hired as an Azure developer who designs, builds, tests, and maintains cloud apps and services.

Microsoft Certified: Dynamics 365: Finance and Operations Apps Developer Associate

Are you a developer who specializes in finance and operations apps? Or can you answer yes to these questions?:

  • Do you have the MB6-894 Financial Management in Microsoft Dynamics 365 for Finance and Operations certification?
  • Do you configure options, security, and processes for Finance and Operations apps?
  • Do you develop and test code?
  • Do you apply dev tools to integrate and manage data solutions, implement reporting, and perform data migration?

Then the Microsoft Certified: Dynamics 365: Finance and Operations Apps Developer Associate certification might be right up your alley.

Training for the Finance and Operations Apps Developer Associate certification involves the following. You can choose your desired path:

With training finished, you can first take the MB-300 exam, which costs $165 and measures skills like managing finance and operations data, configuring administrative features and workflows, and describing finance and operations apps and extending apps via Microsoft Power Platform technologies.

After the MB-300, you will need to pass the $165 MB-500 exam to get your certification. It will measure skills like implementing reporting, implementing security and optimizing performance, developing and testing code, applying developer tools, planning architecture and solution design, and integrating and managing data solutions.

With both exams passed, you can now become a developer who works with finance and operations apps in Microsoft Dynamics 365 to implement and extend apps to meet the business’ requirements.

Microsoft 365 Certified: Teams Application Developer Associate

The Microsoft 365 Certified: Teams Application Developer Associate certification is a good fit if you are a developer or responsible for apps that help your organization collaborate or boost productivity. If you design, build, test, or maintain solutions that serve such a purpose or already work as a developer, give this certification a strong look, as it could significantly help your career.

You will need to pass the $165 Exam MS-600 to get this certification so you can become a Team Application Developer Associate. It will measure such skills as implementing Microsoft identity, extending Microsoft Teams, building apps with Microsoft Graph, extending and customizing Microsoft 365 with SharePoint Framework, designing collaborative app solutions and existing app integration, and more.

How can you obtain and sharpen such skills? By going online and soaking up free Microsoft Learn modules, attending Microsoft Virtual Training days, or by going through five-day, instructor-led training in Course MS-600T00: Building Applications and Solutions with Microsoft 365 Core Services. All of these training options should serve as sufficient prep for the Exam MS-600. Pass it, and you can start designing, building, testing, and maintaining the latest enterprise-grade apps and solutions with Microsoft Teams that focus on helping organizations collaborate and become more productive.

Microsoft Certified: Power Platform Developer Associate

The Microsoft Certified: Power Platform Developer Associate certification is intended for developers, those who have a fundamental understanding of DevOps practices for Microsoft Power Platform, or those who have a solid applied knowledge of Microsoft Power Platform services, like capabilities, boundaries, and complaints.

The path to this certification involves passing the $165 Exam PL-400, which measures skills like configuring Dataverse, developing integrations, extending the user experience and platform, creating and configuring Power apps, creating a technical design, and more. You can prep for the exam with free online resources from Microsoft Learn or instructor-led training over five days via Course PL-400T00-A: Microsoft Power Platform Developer.

Pass the Exam PL-400, and you can officially become a Power Platform Developer Associate who develops, secures, and troubleshoots Power Platform solutions. Do not stop there, though, as you can continue to level up your skills and career by going for the Microsoft Certified: Power Platform Solution Architect Expert certification next.

Read more C# programming tutorials and software development tips.

The post Best Microsoft Certifications for Developers appeared first on CodeGuru.

]]>
Working With Cookies in ASP.NET 6 Core https://www.codeguru.com/dotnet/asp-net-cookies/ Tue, 18 Oct 2022 15:10:54 +0000 https://www.codeguru.com/?p=19481 The term cookie refers to a piece of data that is saved on the computer of a user and is generally used to record information about the user. Most browsers store each cookie as a small file, but Firefox stores them all in a single file. Cookies are made up of two parts: a key […]

The post Working With Cookies in ASP.NET 6 Core appeared first on CodeGuru.

]]>
ASP.Net Tutorials

The term cookie refers to a piece of data that is saved on the computer of a user and is generally used to record information about the user. Most browsers store each cookie as a small file, but Firefox stores them all in a single file. Cookies are made up of two parts: a key and a value.

ASP.NET 6 Core uses cookies to maintain user session state and for authentication purposes. ASP.NET Core uses the Microsoft.AspNetCore.Http.Cookie middleware to work with cookies. This middleware can be used to set, get, and delete cookies.

In this programming tutorial, we will be discussing cookies in ASP.NET 6 Core. We will cover what a cookie is, how to create and manipulate a cookie, and some of the security implications to keep in mind when working with cookies in ASP.NET.

Read: Best Online Courses to Learn .NET

What is a Cookie in ASP.NET?

In basic terms, a cookie is a smaller piece of information stored on a computer, usually as a text file. It keeps the information about you and your activities, like your preferred language or country. Cookies can also help web developers track user behaviour to improve our services and web sites.

To better understand this, consider the following example. If you have been performing searches for one particular type of product or service, but then start searching for something different, as a webmaster we might need to show more relevant search results to help get you closer to finding what you want.

Additionally, if you visit a website and add items to your shopping cart, but do not complete the purchase, the website will “remember” what you added to your cart so that when you come back later, your shopping cart will still contain those items.

Cookies allow web developers to customize content based on how people use our site — for example, by recognizing when they return after logging out of their account. This customization allows us to make better decisions and understand how visitors interact with our content to optimize future experiences accordingly.

What are the Different Types of Cookies?

Basically, cookies can be divided into two types, namely session cookies and persistent cookies. When you visit a website, session cookies are stored on your computer only for the duration of your visit. A session cookie is destroyed when you leave your browser or move away from a web page.

As the name suggests, persistent cookies dwell on your computer even after you have closed your web browser. Persistent cookies can store information accessible across multiple sessions. Generally, these cookies store login information or preferences.

How to Create a Cookie in ASP.NET

Creating a cookie in ASP.NET Core is simple. First, create a new CookieOptions object as shown in the code example given below:

var cookieOptions = new CookieOptions(); 

Next, set the expiration date and path of the cookie, as shown below:

cookieOptions.Expires = DateTime.Now.AddDays(1);
cookieOptions.Path = "/"; 

Lastly, add the cookie to the response object, as shown below:

Response.Cookies.Append("SomeCookie", "SomeValue", cookieOptions);

You can view your web browser’s cookie cache to determine whether a cookie has been written correctly.

Read: The Top Task Management Software for Developers

How to Read a Cookie in ASP.NET

In ASP.NET 6 Core, you can take advantage of the Request object’s Cookies collection to read a cookie. This collection is an instance of the HttpCookieCollection class. To read a cookie, use the indexer of this class to retrieve the HttpCookie object for a given cookie name:

var cookie = Request.Cookies["cookieName"]; 

If the cookie does not exist, the indexer returns null. You can also use the Cookies collection’s Get method to retrieve a cookie:

var cookie = Request.Cookies.Get("cookieName"); 

If the cookie does not exist, this method returns null as well.

How to Update a Cookie in ASP.NET

To update a cookie in ASP.NET 6 Core, you will need to retrieve the cookie from the Request object using the following piece of code:

var cookie = Request.GetCookies("cookieName"); 

You can then modify the cookie value as desired. Lastly, you can write the updated cookie back to the Response object using the SetCookie method, as shown below:

Response.SetCookie(cookie);

Delete a Cookie in ASP.NET

When using ASP.NET Core 6, there are two ways to delete a cookie. The first way is to use the Delete method of the Cookie object as shown below:

Response.Cookies.Delete(somekey); 

The second way is to use the Response object and set the Expires property of the cookie to a date in the past as shown in the ASP.NET code example below:

Response.Cookies["cookieName"].Expires = DateTime.Now.AddDays(-1);

You can use the Clear method to clear all cookies as shown here:

Response.Cookies.Clear();

How to Access Cookies in the Controller Method

To access cookies in the Controller method, developers should register an instance of type IHttpContextAccessor in the Program.cs file as shown below:

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

To read or write cookie data in your controller methods, you will need to inject an instance of type IHttpContextAccessor in the constructor of your controller. The code example given below illustrates how this can be achieved:

public class SomeController : Controller
{
  private readonly IHttpContextAccessor _httpContextAccessor;
  public SomeController(IHttpContextAccessor httpContextAccessor)
  {
     this._httpContextAccessor = httpContextAccessor;
  }   
  //Write your action methods here
}

You can now use the following piece of code to access the Cookies object in your controller methods:

CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddSeconds(30);
_httpContextAccessor.HttpContext.Response.Cookies.Append("someKey", "someValue", options);

Final Thoughts on Cookies in ASP.NET

If you would like to use cookies to store sensitive information, it is important to ensure that your cookies are properly secured using SSL/TLS encryption. In this web development tutorial, we examined how programmers can work with cookies in ASP.NET 6 Core. We also explored the different types of cookies and how to create, read, and update them programmatically.

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

The post Working With Cookies in ASP.NET 6 Core 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.

]]>
.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.

]]>
Best Practices to Avoid Memory Leaks in ASP.NET https://www.codeguru.com/dotnet/asp-net-memory-leaks/ Thu, 08 Sep 2022 17:22:13 +0000 https://www.codeguru.com/?p=19420 While the .Net Common Language Runtime (CLR) abstracts away memory management from developers, memory leaks are still possible. This programming tutorial talks about memory leaks, why they occur, and the best practices that can be followed to avoid them in ASP.NET applications. Looking to learn .NET in a classroom or online course environment? Check out […]

The post Best Practices to Avoid Memory Leaks in ASP.NET appeared first on CodeGuru.

]]>
ASP.Net Tutorials

While the .Net Common Language Runtime (CLR) abstracts away memory management from developers, memory leaks are still possible. This programming tutorial talks about memory leaks, why they occur, and the best practices that can be followed to avoid them in ASP.NET applications.

Looking to learn .NET in a classroom or online course environment? Check out our list of the Top Online Courses to Learn .NET.

What are Memory Leaks and Why Do They Occur?

A memory leak happens when an application cannot correctly manage memory allocations and deallocations. Once a memory leak has occurred, the Garbage Collector (GC) cannot remove objects that are no longer in use from memory. Typically, a memory leak happens when an application fails to release memory for objects no longer needed, leading to memory fragmentation and degraded performance.

If the application frequently allocates memory to new objects, but fails to deallocate it when it is no longer needed, memory use grows over time, which may cause an application to crash at some point.

Memory leaks can occur in managed heaps, unmanaged heaps, and even stacks. As soon as the execution of a method is completed, the memory allocated in the stack is usually recovered.

Often a stack frame may not be released particularly if your app extensively uses the stack. When this happens, the stack might be leaked by your application’s threads.

A memory leak can also happen when unmanaged code fails to deallocate unavailable memory, which may not have been allocated anymore by any process at the point of the allocation.

What Happens When a Memory Leak Occurs?

When memory leaks occur, references to objects persist even if those objects are no longer used. Rather than recovering the memory, the GC promotes the objects to higher generations since they are still alive and referenced.

This type of promotion is not only expensive, but it also keeps the GC overburdened. Whenever memory leaks occur, more and more memory is used until there is no more available memory. As a result, the Garbage Collector must perform more frequent collections to free up memory.

How to Avoid Memory Leaks in ASP.NET and .NET

Below are a few best practices programmers can use to avoid memory leaks in their ASP.NET, C#, and .NET applications.

Release Objects as Soon as You’re Done Using Them

Developers must avoid keeping references to managed and unmanaged objects longer than necessary. While this may not seem like a memory leak, memory usage grows when an application retains references for longer than required, and an “Out of Memory”</b exception may be thrown. Once you are done using an object (managed or unmanaged), you must set it to null.

If you are using a managed object, this will make your object ready for garbage collection. If you are using an unmanaged object, by setting the object to null, the resources occupied by the object would be released soon after. The golden guideline to remember is to acquire resources late and release them early.

Avoid Large Object Heap Fragmentation

In .NET, the Large Object Heap (LOH) is a segment of memory that is used to store large objects – typically objects that are larger than 85K in size. The LOH is part of the managed heap and can be accessed using the System.Runtime.InteropServices.Marshal class. Note that, contrary to the Small Object Heap (where objects less than 85K are stored), the Large Object Heap is never compacted by the CLR.

Large object heap fragmentation is a condition where the LOH has become broken up into many small blocks, rather than being stored in one continuous block of memory. This can make it difficult to store new large objects or reuse existing ones, because they have to be stored in small fragments instead of one large block.

The fragmentation of large object heap occurs when the objects are not stored contiguously in memory and the space allocated for the large objects is broken into small chunks, which are not enough to store large objects. This leads to wastage of space and also increases the time taken for garbage collection because more pages need to be moved during garbage collection if they are not stored contiguously on disk or RAM.

The main reason for fragmentation of large object heaps is due to frequent allocation and deallocation of memory. This results in an increase in time spent by the garbage collector during minor collections and major collections because it needs to relocate objects within the LOH to make room for other objects being allocated into it, which could greatly affect performance.

Reducing fragmentation of large object heaps is important to ensure that you have an optimal application performance. Developers can avoid large object heap fragmentation by pinning and compaction. However, the best practice is to avoid creating objects in the large object heap by creating smaller objects (i.e., objects that have a size less than 85K). To prevent fragmentation of the Large Object Heap, you can use the “Large Object Heap Compaction” feature.

To prevent fragmentation, programmers can use two methods: Use pinning, or, pre-allocating large objects on their own section of memory, which prevents them from being moved around within their allocated space so they can be accessed quickly without having to recreate them each time they are needed again later on down the road; use compacting techniques where allocating fewer small objects will prevent them from fragmenting at all times.

You can force large object heap compaction in ASP.NET using the following code example:

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();

However, this is not recommended and should be avoided because of performance impacts.

Looking for a tool to help monitor application performance? We have a list of the Top Application Performance Monitoring (APM) Tools to help you get started.

Avoid Using Static References

In an application, objects referenced by static references reside in memory until the application is active. These objects reside in memory for the application’s lifetime or until the reference to the static object is marked as null.

It should be noted that GC does not collect GC Root objects and the GC considers static variables as GC Root objects. This explains why static variables are not garbage collected during a garbage collection cycle.

The takeaway here is to avoid using static references unless essential. When you use static references, be cautious about marking them as null when they are no longer required.

Delete Unmanaged Objects When You Are Done Using Them

While objects residing in the managed heap are deleted by the garbage collector, unmanaged objects are not cleaned by the garbage collector. Hence, developers must delete unmanaged objects (file handles, database connections, COM objects, etc) explicitly once they are done using them. In other words, if your application makes use of unmanaged objects, you must take special care to ensure that they are disposed in your code, ideally using the Dispose method. It is important to note that finalizers are not guaranteed to be invoked by the CLR.

Final Thoughts on ASP.NET Memory Leaks

In addition to performance concerns, memory leaks also create GC pressure, negatively impacting application performance. Many developers use the Windows Task Manager to confirm whether or not an app has memory leaks. There are cases where your app crashes without returning the OutOfMemoryError message, which makes diagnosing a memory leak a problem more difficult to identify and detect.

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

The post Best Practices to Avoid Memory Leaks in ASP.NET appeared first on CodeGuru.

]]>
Implementing Basic Authentication in ASP.NET 6 https://www.codeguru.com/dotnet/authentication-asp-net/ Thu, 25 Aug 2022 18:04:15 +0000 https://www.codeguru.com/?p=19404 Basic authentication, as the name suggests, is the simplest authentication technique of validating a user’s credentials. This programming tutorial talks about basic authentication and how it can be implemented in ASP.NET 6 Core. What is Basic Authentication in ASP.NET? Basic authentication is a mechanism that transmits credentials as plain text. It is supported by most […]

The post Implementing Basic Authentication in ASP.NET 6 appeared first on CodeGuru.

]]>
Basic authentication, as the name suggests, is the simplest authentication technique of validating a user’s credentials. This programming tutorial talks about basic authentication and how it can be implemented in ASP.NET 6 Core.

What is Basic Authentication in ASP.NET?

Basic authentication is a mechanism that transmits credentials as plain text. It is supported by most web browsers, and it sends user name and password encoded in base64. Basic authentication is simple and effective way to protect your site from unauthorized access without requiring you to create an entirely new system.

Basic authentication is not as secure as other forms of authentication primarily because credentials are transmitted to the server in plain text, so they can be intercepted by anyone on the network. Almost all browsers and server platforms support basic authentication, making it a good choice for protecting simple web applications.

Read: Best Application Performance Monitoring (APM) Tools

How Does Authentication Work in ASP.NET?

The user’s credentials are transmitted over the wire unencrypted in basic authentication. Hence, developers must ensure that a secure socket layer protects your API. When using basic authentication, if the user’s credentials passed in the request header are valid, the server application generates an authentication token and sends it back to the client.

For all subsequent requests originating from the client, you must pass this token in the request header. The service running on the server side would need to parse the request header to get the authentication token. If the request is invalid, the server will respond with HTTP status code 401, which indicates an unlawful response.

How to Implement Basic Authentication in ASP.NET 6

In this section, we will examine how we can implement basic authentication in ASP.NET 6 applications. First off, create a new ASP.NET 6 Core Web API application in Visual Studio 2022.

Once the project has been created, you will see a default controller named WeatherForecastController created in your project. We will not use this controller. Instead, we will create our own custom controller. We will come back to this in a while, just make note of it here.

Create a Model in ASP.NET

Create a new model class named User and write the following code in there:

    public class User
    {
        public int Id { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }

Create the Repository

Create an interface named IUserRepository with the following code in there:

  public interface IUserRepository
    {
        Task Authenticate(string username, string password);
        Task<List> GetUserNames();
    }

The UserRepository class extends the IUserRepository interface and implements its methods:

    public class UserRepository: IUserRepository
    {
        private List _users = new List
        {
            new User 
            {
                Id = 1, Username = "peter", Password = "peter123"            
            },
            new User
            {
                Id = 2, Username = "joydip", Password = "joydip123"
            },
            new User
            {
                Id = 3, Username = "james", Password = "james123"
            }
        };
        public async Task Authenticate(string username, string password)
        {
            if(await Task.FromResult(_users.SingleOrDefault(x => x.Username == username && x.Password == password)) != null)
            {
                return true;
            }
            return false;
        }
        public async Task<List> GetUserNames()
        {
            List users = new List();
            foreach(var user in _users)
            {
                users.Add(user.Username);
            }
            return await Task.FromResult(users);
        }
    }

Read: Best Online Courses for .NET Developers

Create the Controller

We will now create an API controller class that would have just one action method. Now create a new API controller named UsersController and write the following code in there:

  [Route("api/[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        private readonly IUserRepository _userRepository;
        public UsersController(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }
        [HttpGet]
        [Authorize]
        public async Task<List> Get()
        {
            return await _userRepository.GetUserNames();
        }
    }

Note how an instance of type IUserRepository has been injected in the constructor of the UsersController class. The GetUserNames method is called inside the Get action method. This method returns all user names.

How to Create an Authentication Handler in ASP.NET

Next, we will implement a handler that would be called earlier in the pipeline with every request. This handler will check if the user’s credentials passed in the request header are valid. If the credentials are valid, the request is allowed, else a corresponding response code is assigned (401 in our example) and an error message sent back to the client:

public class BasicAuthenticationHandler : AuthenticationHandler
    {
        private readonly IUserRepository _userRepository;
        public BasicAuthenticationHandler(
            IOptionsMonitor options,
            ILoggerFactory logger,
            UrlEncoder encoder,
            ISystemClock clock, IUserRepository userRepository) : 
           base(options, logger, encoder, clock)
        {
            _userRepository = userRepository;
        }

        protected async override Task HandleAuthenticateAsync()
        {
            var authorizationHeader = Request.Headers["Authorization"].ToString();
            if (authorizationHeader != null && authorizationHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
            {
                var token = authorizationHeader.Substring("Basic ".Length).Trim();
                var credentialsAsEncodedString = Encoding.UTF8.GetString(Convert.FromBase64String(token));
                var credentials = credentialsAsEncodedString.Split(':');
                if (await _userRepository.Authenticate(credentials[0], credentials[1]))
                {
                    var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
                    var identity = new ClaimsIdentity(claims, "Basic");
                    var claimsPrincipal = new ClaimsPrincipal(identity);
                    return await Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(claimsPrincipal, Scheme.Name)));
                }
            }
            Response.StatusCode = 401;
            Response.Headers.Add("WWW-Authenticate", "Basic realm=\"joydipkanjilal.com\"");
            return await Task.FromResult(AuthenticateResult.Fail("Invalid Authorization Header"));
        }
    }

Add Services to the Container

To take advantage of dependency injection as we did earlier in the UsersController class using an instance of type IUserRepository, you should register an instance of type IUserRepository in the Program.cs file. To do this, you should write the following code in the Program.cs file:

builder.Services.AddScoped<IUserRepository, UserRepository>();

Likewise, you should write the following code in the Program.cs file to add authentication services to the container:

builder.Services.AddAuthentication("BasicAuthentication").
            AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>
            ("BasicAuthentication", null);

Execute the Application

Lastly, run the application and execute the Get endpoint of the UsersController via Postman. Assuming that you have specified the correct credentials, here’s how the output would look:

ASP.NET Authentication

If the credentials are not valid, you will be presented with an HTTP 401 error.

Final Thoughts on Authentication in ASP.NET

In this programming tutorial, we have implemented basic authentication in an ASP.NET 6 Core application. Remember that basic authentication is not secure – you can take advantage of more secure authentication techniques to keep your ASP.NET 6 application and its data secure. You can use basic authentication to secure internal company websites where only users with accounts on your system are most likely to access the site.

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

The post Implementing Basic Authentication in ASP.NET 6 appeared first on CodeGuru.

]]>