European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core Hosting :: ASP.NET Core 6.0 Middleware

clock July 26, 2022 08:00 by author Peter

Middleware is a component that is assembled into an application pipeline to handle requests and responses. Middleware is linked one after the other, so each gets to choose whether to pass the request to the next middleware and work before and after the next component in the pipeline.

Middleware:
    Sits between the requestor and the target.
    Can directly modify the response.
    Can log things.
    Can use the data within the request to generate the response.

Take look at the diagram below:

ASP.NET 6.0 implements a pipeline consisting of a series of middleware classes.

  • Requests filter down the pipeline until they reach a point where the middleware class creates a response.
  • Responses filter back through the middleware in reverse order until they reach the requestor.

Middleware is a great place to do the following:
    Authorization
    Authentication
    Diagnostics
    Error handling and logging

Each middleware consists of a request delegate. This is a specific kind of object in .NET that can pass execution control to the next object. Let us create a simple Web API project. For this tutorial I’m using the tools below:
    Visual Studio Community Edition 2022 (64-bit) – Preview (Version 17.3.0 Preview 4.0)
    .NET 6.0
    Minimal Web API
    Swagger

Please find the program.cs file part of the minimal API:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.UseSwagger();
    app.UseSwaggerUI();
}
//I have commented out the below codes as we are going to check Use(), Map() and Run()
/* var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateTime.Now.AddDays(index),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast"); */
app.Run();
/*internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

} */


If we run this project, you should get the below output.

Now let's create simple middleware that will return “Hello Readers!” as response. In Program.cs, we add a new middleware using Run() method like below. We normally call it inline middleware.
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.Run(async context => {
        await context.Response.WriteAsync("Hello Readers!");
    });
    app.UseSwagger();
    app.UseSwaggerUI();
}


Run the application. You should get the below output:

While going through each line of code in Program.cs, generally we identify which parts of the code are considered middleware by looking at the methods used to add them to the pipeline. Those methods are Run(), Use() and Map().

Let's look at each method to understand the usage and differences between them.
Run()

This method only receives only context parameter and doesn’t know about the next middleware. These delegates are usually known as terminal delegates because they terminate or end the middleware pipeline.

Let us add another delegate as below and see how it behaves:
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.Run(async context => {
        await context.Response.WriteAsync("Hello Readers!");
    });
    app.Run(async context => {
        await context.Response.WriteAsync("We are learning Middlware!");
    });
    app.UseSwagger();
    app.UseSwaggerUI();
}


Go head and run the application. You should get the below output:

The second delegate didn’t invoke here because the first one terminated the pipeline.
Use()

The whole idea behind middleware is to link one after another. Let us take a look at the Use() method, which helps us to chain the delegates one after the other.

This method will accept two parameters, context and next. Let us create a inline middleware using the Use() method:
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.Use(async (context, next) => {
        await context.Response.WriteAsync($ "Before Request {Environment.NewLine}");
        await next();
        await context.Response.WriteAsync($ "After Request {Environment.NewLine}");
    });
    app.Run(async context => {
        await context.Response.WriteAsync($ "Hello Readers!{Environment.NewLine}");
    });
    app.UseSwagger();
    app.UseSwaggerUI();
}


The output is given below:

This will show us that the middleware has been changed, one after another. Here, the await next() triggered the next middleware, which was implemented using the method Run().

Notes:
    Don’t call next.invoke after the response has been sent to client.
    Writing to the response body after calling next may cause a protocol violation.
    Writing to the response body after calling next may cause the body format

Map()
Map extensions are used for branching the pipeline. Map extensions branch the request pipeline based on matching the given request path. If the request path starts with the given path, the branch is executed.

Let us see two middleware, as below:
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.Map("/BranchOne", MapBranchOne);
app.Map("/BranchTwo", MapBranchTwo);
app.Run();
static void MapBranchOne(IApplicationBuilder app) {
    app.Run(async context => {
        await context.Response.WriteAsync("You are on Branch One!");
    });
}
static void MapBranchTwo(IApplicationBuilder app) {
    app.Run(async context => {
        await context.Response.WriteAsync("You are on Branch Two!");
    });
}


The output should be as below:
http://localhost:1233/branchone

http://localhost:1234/branchtwo


We have covered the basics of middleware. In the upcoming tutorial, I will be covering custom middleware. Thank you for reading my article. Please leave your comments in the comment box below.

HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core Hosting - HostForLIFE :: Testing The Exception Thrown In NUnit C#

clock July 25, 2022 10:11 by author Peter

In this article, we will learn how to test the exception thrown by the test code using NUnit in .Net. While doing Unit testing, we write test cases for every possible positive as well as the negative scenario. In several test cases, there might be a situation or condition which throws an exception. In order to test those scenarios, we have to use Asset.Throws method. Asset.Throws attempts to invoke a code snippet represented as a delegate in order to verify that it throws a particular exception.

For demonstration, I already created a sample application “BankingApp” which is basically a .Net Core Class Library project.

A Test project named “BankingApp.Test” is also added to the Solution. I am using NUnit for writing the Unit Test case. In the Account.cs class, I have a parameterized constructor and two methods in which one is for adding the amount i.e. depositAmount() method, and another for checking the balance amount (i.e. checkBalanceAmount() method). In case the amount to be deposited is either zero or less than that, an exception (ArgumentException) will be thrown.

In AccountTest.cs file, I have written a test case in which the amount to be deposited is “-100” i.e. less than zero.

Now, let’s run the test case from the Test Explorer.

On running the test case, an Argument exception with a message i.e., “Amount to be deposit must be greater than zero” is thrown.

Let’s use the Assert.Throws() method and pass method as a delegate which is throwing the exception. In our case, it is depositAmount(). Assert.Throws require the exact type of exception which can be thrown. It returns the exception as well. With StringAssert.Contains() method, we can verify the expected exception text with the actual exception text.

Now run the test case. You can see that our test case is passed. In this example, we verified that on passing the deposit amount 0 or less than zero, an exception is properly thrown to the user.

HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core Hosting :: Feature Flags In ASP.NET Core

clock July 19, 2022 08:17 by author Peter

Feature flags allow toggling multiple features of an application without having to redeploy the application. One or more feature flags can be defined declaratively as part of the application’s config file that can control feature availability. Feature flag is part of a broader concept of feature management. Feature management provides additional functionality like filtering feature availability based on user groups, devices etc., caching feature flags and managing their states. In this article, we will focus on implementing feature flags using ASP.NET Core feature management package.

Setup
Consider you have a simple ASP.NET 6 MVC application for creating a todo list. To keep this article focused on the subject, I will omit the steps for creating such application. Typically, the application would be capable of adding new todo items to a list of todos and displaying them on the screen.

To work with ASP.NET Core feature management, add Microsoft.FeatureManagement.AspNetCore nuget package to the application. Add the feature management service to the application inside Program.cs
using Microsoft.FeatureManagement;

namespace FeatureFlagDemo;

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        // Add services to the container.
        ...
        builder.Services.AddFeatureManagement();
        ...
        var app = builder.Build();
        ...
    }
}


Adding feature flags to the configuration
We will expose two feature flags – one for enabling edit of the todo item and another for enabling delete of the todo item. Add the feature flags to the appsettings.json file under FeatureManagement section as follows
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "FeatureManagement": {
    "Edit": false,
    "Delete": false
  },
  "AllowedHosts": "*"
}


Note both the features are disabled in the configuration file.

FeatureGate attribute
To enable the feature flags at controller or action level, we can use the FeatureGate attribute as shown below.
[HttpGet]
[FeatureGate("Edit")]
public ActionResult Edit(int id)
{
    ...
}

[HttpPost]
[FeatureGate("Edit")]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, TodoItem todoItem)
{
    ...
}


Applying the attribute for all actions related to the Edit feature will ensure that the actions are available only when the Edit feature flag is enabled.

Add similar code for handling Delete feature.
[HttpGet]
[FeatureGate("Delete")]
public ActionResult Delete(int id)
{
    ...
}

[HttpPost]
[FeatureGate("Delete")]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, TodoItem todoItem)
{
    ...
}


Note: Part of code is omitted for brevity and to remain focused on the topic. In production scenarios, consider appropriate measures for implementing the feature including security, performance etc.
<feature> tag helper

The <feature> tag can be used to conditionally render text on razor views depending upon the state of feature flags. Import the feature management tag helpers inside the _ViewImports.cshtml file.
@using FeatureFlagDemo
@using FeatureFlagDemo.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Microsoft.FeatureManagement.AspNetCore


Inside razor view, use the <feature> tag as follows to conditionally render Edit and Delete options based on the state of their respective feature flags.
<feature name="Edit"><a asp-action="Edit" asp-route-id="@item.Id">Edit</a></feature>
<feature name="Delete"><a asp-action="Delete" asp-route-id="@item.Id">Delete</a></feature>


Toggling feature flags and testing
Initially both the feature flags are disabled. Upon running the application, none of the Actions (Edit / Delete) are visible on the razor view.

Enable Edit feature by toggling the Edit feature flag in the appsettings.json file
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "FeatureManagement": {
    "Edit": true,
    "Delete": false
  },
  "AllowedHosts": "*"
}


Refresh the page and you should be able to see Edit feature enabled. Upon clicking edit link you can also confirm that the actions related to edit feature are being executed as per the implementation.

Enable Delete feature by toggling the Delete feature flag in the appsettings.json file
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "FeatureManagement": {
    "Edit": true,
    "Delete": true
  },
  "AllowedHosts": "*"
}


Refresh the page and you should be able to see Delete feature enabled. Upon clicking delete link you can also confirm that the actions related to delete feature are being executed as per the implementation.

HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



European ASP.NET Core Hosting :: Label Control In ASP.NET

clock July 15, 2022 08:39 by author Peter

In this article, you will learn how to use Label in ASP.NET Framework and how Label works.

What are Label Controls

    The label control is used to display text on a website.
    It is primarily used to generate captions for other controls such as textboxes.
    Labels typically assist the user in entering data into text boxes by providing written instructions.
    Labels are controls on the server-side.
    The Label class can be found in the System.Web.UI.WebControls namespace.

Adding Label Control
    To create a label, we can either write code or use Visual Studio's drag and drop feature.
    This is a server-side control, and asp provides its own tag for label creation.

The following is an example and syntax to add label control.
<asp:Label_ID="LabelNew" runat="'server" Text="Label_Control"></asp:Label>
here Runat='Server' Indicates the accessibility of the control at Serverside

Properties of Label Control
Label Control has its own properties that will be used to improve it. (Syntax for each label control property is given in ASP.NET code)

AccessKey

Accesskey is used to add the keyboard shortcut for the label.
<asp:webcontrol id="id" AccessKey="accessKey" runat="server" />

Tablndex
It determines the webserver's tab control index.
<asp:TextBox ID="txtName" runat="server" TabIndex="0"></asp:TextBox>

BackColor
This property is used to change the look and make it with different colours.
<asp:webcontrol id="id" BackColor="color" runat="server" />

BorderColor
We can use this property to change the colour of the label border.
<asp:webcontrol id="id" BorderColor="color" runat="server" />

BorderWidth
This property will allow us to specify the width of the label border.
<asp:webcontrol id="id" BorderWidth="length" runat="server" />

Font
This property will allow us to specify the width of the label border.
<asp:webcontrol id="id" font-subproperty="value" runat="server" />

Forecolor
It's used to change the colour of the label text.
<asp:webcontrol id="id" ForeColor="color" runat="server" />

Text
This property makes use of text that must be displayed for the label.
<asp:HyperLink Text="string" runat="server" />

ToolTip
It specifies the text that will be displayed when we move the mouse over a label.
<asp:webcontrol id="id" ToolTip="string" runat="server" />

Visible
It will allow us to customise the control's visibility on the web form.
<asp:webcontrol id="id" Visible="True|False" runat="server" />

Height
It allows us to customise the height of the label control.
<asp:Image ID="Image1" runat="server" Height="value" />

Width
It allows us to adjust the width of the label control.
<asp:Image ID="Image1" runat="server"  Width="value" />

BorderStyle
The border of the label control can be designed to meet the needs of the application.
<asp:webcontrol id="id" BorderStyle="style" runat="server" />

CssClass
It gives us the CSS class of the label control.
<asp:webcontrol id="id" CssClass="style" runat="server" />

Events for Label Controls
DataBinding

When the server control binds to a data source, this is referred to as data binding.

Disposed
When an ASP.NET page is requested, a server control is released from memory, which is the final stage of the server control lifecycle.

Init
Occurs during the initialization of the server control, which is the first step in its lifecycle.

Load
When the server control is loaded into the Page object, this event occurs.

PreRender
This occurs after the Control object has been loaded but before rendering.

Unload
This happens when the server control is loaded from memory.

Methods for Label Control
DataBind()
Binds a data source to the server control that was invoked and all of its child controls.

Dispose()
Allows a server control to perform final cleanup before releasing it from memory.

Equals(Object)
Checks whether the specified object is the same as the current object.

Focus()
Sets a control's input focus.

OnLoad(EventArgs)
The Load event is raised.

ToString()
This method returns a string that represents the current object.

Conclusion
Here, we have learned how label works in ASP.NET Framework and how label controls are useful for us to use.

If you have any queries/suggestions on the article, please leave your questions and thoughts in the comment section below. Follow C# Corner to learn more new and amazing things about ASP.NET or to explore more technologies.

HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in