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 :: How To Add JWT Bearer Token Authorization Functionality In Swagger?

clock December 1, 2021 07:18 by author Peter

Swagger (Open API) is a language-agnostic specification for describing and documenting the REST API. Swagger Allows both the Machine and Developer to understand the working and capabilities of the Machine without direct access to the source code of the project. The main objectives of swagger (Open API) are to:

    Minimize the workload to connect with Microservice.
    Reduce the Time Needed to accurately document the Microservice.

Default Addition of Swagger in .NET 5 & .NET 6
Swagger open API is used for developing APIs using ASP.Net Core versions .Net 5 and .Net 6. We can test our all-API Endpoints in a default functionality because it's directly integrated with our API for testing like.

Swagger revealed all our endpoints in the Default view, and we can test them using JSON Schema. Like

However, we have a challenge in that we wish to retrieve data from a secured endpoint that requires a Token as well as a Role-based Token. After submitting a JWT Token and a Role, the endpoint shown below will return data.

[HttpGet]
[Authorize(Roles = "Admin")]
public IEnumerable < WeatherForecast > Get() {
    var rng = new Random();
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast {
        Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
    }).ToArray();
}

Demo
We'll test the endpoint listed below without a token or a role.

After hitting the endpoint, we have the output like


Unauthorized Access because the endpoint requires a JWT Token and a Role in order to access data from the database. By default, Swagger does not provide capability for token-based authorization of endpoints. We are currently adding JWT Token-based functionality to our API.

Default View


Adding JWT Token Functionality in Our API
First and foremost, you must change the default swagger functionality in our startup.cs class

public void ConfigureServices(IServiceCollection services) {
    services.AddDbContext < ApplicationDbContext > (options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
    services.AddControllers();
    services.AddControllers();
    //Default Functionality Added by Swagger
    services.AddSwaggerGen();
    // For Entity Framework
    // For Identity
    services.AddIdentity < ApplicationUser, IdentityRole > ().AddEntityFrameworkStores < ApplicationDbContext > ().AddDefaultTokenProviders();
    // Adding Authentication
    services.AddAuthentication(options => {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        // Adding Jwt Bearer
        .AddJwtBearer(options => {
            options.SaveToken = true;
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters = new TokenValidationParameters() {
                ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidAudience = Configuration["JWT:ValidAudience"],
                    ValidIssuer = Configuration["JWT:ValidIssuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))
            };
        });
    //services.AddTransient<PersonService, PersonService>();
}

Modifying the Functionality
Just add given below line and replace the,
services.AddSwaggerGen();

With given below lines,
services.AddSwaggerGen(c => {
    c.SwaggerDoc("v1", new OpenApiInfo {
        Title = "JWTToken_Auth_API", Version = "v1"
    });
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() {
        Name = "Authorization",
            Type = SecuritySchemeType.ApiKey,
            Scheme = "Bearer",
            BearerFormat = "JWT",
            In = ParameterLocation.Header,
            Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 1safsfsdfdfd\"",
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement {
        {
            new OpenApiSecurityScheme {
                Reference = new OpenApiReference {
                    Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
});


Now we can see the Authorize Option for JWT Token Authorization

Step 1
Get the JWT Token for the user by hitting the Login endpoints:
How To Add JWT Bearer Token Authorization Functionality in Swagger

Step 2
Get the JWT Token using Login EndPoint:
How To Add JWT Bearer Token Authorization Functionality in Swagger


We now have the token, which we will add to our application using the Swagger JWT Token Authorization functionality.


Step 3
Hit the Authorize Button and add JWT Token in your application:


 

Now our all endpoints are authorized,


View after adding JWT Token Authentication in Application,


Now you see that we have the lock sign with all our endpoints so let’s try to access the same endpoint data now.


Now you can see that we have a JWT Token and that we have accessed data from a secured API using this token.


After adding the JWT Function in our Application now you can test all the secured endpoint using JWT Token Authentication

We covered how to enable JWT token capabilities in our application and then how to retrieve data from a secured endpoint in this article.

JWT Token Authentication in Asp.net Web API will be the subject of the next article.

“Happy Coding”

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 :: How To Enable SSL In Visual Studio?

clock November 26, 2021 06:43 by author Peter

What is SSL Certificate?
SSL stands for Secure Sockets Layer, a global standard security technology that enables encrypted communication between a web browser and a web server.
Create ASP.NET Web Application

  • Start Visual Studio 2019 and select Create a new project.
  • In the Create a new project dialog, select ASP.NET Web Application (.NET Framework) > Next.
  • In the Configure your new project dialog, enter SSLSample for Project name. It's important to name the project SSLSample. Capitalization needs to match each namespace when code is copied.
  • Select Framework (.NET Framework 4.7.2)
  • Select Create.
  • In the Additional Information dialog, select MVC
  • Select Create.

There are two ways, you can configure SSL in your application. If you are creating your application from scratch, then select the option Configure for HTTPs when creating a new project. For this sample, please uncheck Configure for HTTPs.

In this article, we are going to discuss if your application is already built, and you are planning to enable SSL in Visual Studio.
So, when you run your application, you see the URL like this (http://localhost:44345/):

But we would like to see like this (https://localhost:44345/). Let’s configure SSL in our application.
The first step is easy. You just select the project name in the solution and locate the property called “SSL Enabled” in properties window:

The same properties window will also show the HTTPS URL for the application. In the above example, it’s https://localhost:65440/. Copy that URL and go to the project properties window. Locate the Web tab and override the Project URL property with the https address:

After that, you need to setup a trusted certificate for Visual Studio. You can locate the certificate in the Personal folder of the computer-level certificates in the certificates snap-in:

If you double-click the certificate, you’ll see that it’s not trusted:

The message also provides the solution: the certificate must be imported into the trusted root certification authority’s folder. You’ll see that as a folder in the same snap-in just below “Personal”. So how can we do that?

EXPORT

  • Right-click the certificate
  • Select All Tasks
  • Export… from the context menu.
  • Click Next on the certificate export wizard.
  • Leave the “Do not export the private key” option untouched, click Next.
  • Accept the default on the next screen, i.e., “DER encoded binary X.509” should stay selected, then click Next.
  • Provide a name and a location for the exported file. Call it “localhost” and save it in a location where you can easily find it.
  • Click Next and then Finish.

There should be a popup message saying that the export was successful.

IMPORT

  • Next right-click the folder called Trusted Root Certification Authorities and select All Tasks
  • Import… from the context menu.
  • Leave the “Local Machine” option untouched in the certificate import wizard, click Next.
  • Browse to the certificate you saved just before.
  • Click Next and accept all the default values along the way until you reach the end of the wizard.

There should be a message saying that the import was successful.

OK, let’s start the .NET web project again, the opening page should open without any warning. If you still see the same issue, then test it in a brand-new browser session.

You can also view the extracted certificate from the browser window. Here’s an example:


As you can see, the website URL is SSL secured and protected.

Conclusion
In this article, we have learned how to setup an SSL certificate in Visual studio for Local applications.

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 :: How To Consume Web API In An ASP.NET Gridview Using HttpClient?

clock November 24, 2021 09:02 by author Peter

Integrating Web API and ASP.NET has been the subject in many discussions and for this, I wrote this article to demonstrate an example of how to consume Web API in an ASP.NET website and how to view the information in a GridView.

If you are not familiar with ASP.NET and Visual Studio and how to setup an environment please refer to the following article.

Now, let's start consuming the Web API in an asp.net website step by step.

Step 1 - Create ASP.NET Website
Search "All Programs" and select "Microsoft Visual Studio 2022".
Click "Create a new project". Select "ASP.NET Empty Web Site", click "Next", give the website a name and click ok.
The following window will appear.

The next step creates the empty ASP.NET Web Site without adding the default page, and the project will look like the following.

Step 2 - Install HttpClient library from NuGet
In order to consume HttpClient, this library needs to be installed from package manager as in the following picture.

Step 3 - Install WebAPI.Client library from NuGet
This package adds support for formatting and content negotiation to System.Net.Http, To install, go to package manager and search for "Microsoft.AspNet.WebApi.Client" and click install as in the following image.

Installing the previous two packages will allow us to consume Web API in our project. Now, let's move to the next steps.

Step 4 - Create A New Web Form
Now, right-click on the project node and go to "Add" and then "Add New Item", choose "Web Form" and click add, the solution explorer will look like the following.

Step 5 - Add GridView To Web Form
Go to Toolbox on the left hand menu and choose "GridView", drag it to the HTML page, and click save as in the following picture.

Step 6 - Add Class to Web Form Page
Now, let's add the class and code to consume to Web API to Web Form Page.

After modifying the code of Default.aspx.cs class, the code will look like the following.

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Data;
public partial class _Default: System.Web.UI.Page {
    public class DataObject {
        public string Version {
            get;
            set;
        }
        public string Key {
            get;
            set;
        }
        public string Type {
            get;
            set;
        }
        public string Rank {
            get;
            set;
        }
        public string EnglishName {
            get;
            set;
        }
    }
    protected void Page_Load(object sender, EventArgs e) {
        populateWebApiGridView();
    }
    public void populateWebApiGridView() {
        string URL = "API_URL";
        string urlParameters = "API_KEY";
        DataTable dt = new DataTable();
        dt.Columns.Add("Version", typeof(string));
        dt.Columns.Add("Key", typeof(string));
        dt.Columns.Add("Type", typeof(string));
        dt.Columns.Add("Rank", typeof(string));
        dt.Columns.Add("City", typeof(string));
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(URL);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response = client.GetAsync(urlParameters).Result;
        if (response.IsSuccessStatusCode) {
            var dataObjects = response.Content.ReadAsAsync < IEnumerable < DataObject >> ().Result;
            foreach(var d in dataObjects) {
                dt.Rows.Add(d.Version);
                dt.Rows.Add(d.Key);
                dt.Rows.Add(d.Type);
                dt.Rows.Add(d.Rank);
                dt.Rows.Add(d.EnglishName);
            }
        } else {
            System.Diagnostics.Debug.WriteLine("{ 0} ({1})", (int) response.StatusCode, response.ReasonPhrase);
        }
        client.Dispose();
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

Step 7 - Run the Web Site

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 :: Using Log4net To Log Exceptions In ASP.NET

clock November 22, 2021 09:05 by author Peter

Log4net is an amazing library to perform logging in our applications in a petty simple way.

To start with log4net in ASP.NET we need to install the nuget package.
dotnet add package log4net

Then we need to include the log4net.config file. This is an XML file that contains all the settings for our Log. We can specify the format, filename, maximum file size, and others.

This is an example,
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <log4net>
        <root>
            <level value="ALL" />
            <appender-ref ref="RollingLogFileAppender" />
        </root>
        <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
            <file value="api.log" />
            <appendToFile value="true" />
            <rollingStyle value="Composite" />
            <maxSizeRollBackups value="5" />
            <maximumFileSize value="10MB" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date %5level %class - MESSAGE: %message%newline"/>
            </layout>
        </appender>
    </log4net>
</configuration>


Markup
    file: Name of the file created with the log
    level: Used to Specify the level error to save in the log. Other levels are going to be ignored and ALL includes all the levels.
    maximumFileSize: Maximum size of the log file if the log exceeds this limit, log4net is going to create a new file.

This is an example where the file is located,

Now, we need to set up the log in the program.cs class to start the log when the API starts.  
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
ILoggerRepository repository = log4net.LogManager.GetRepository(Assembly.GetEntryAssembly());
var fileInfo = new FileInfo(@"log4net.config");
log4net.Config.XmlConfigurator.Configure(repository, fileInfo);
host.Run();
}


Finally, we are ready to create a filter in our project in order to catch all the possible exceptions in our application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using log4net;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace Api.Attributes
{
public class LogFilterAttribute : ExceptionFilterAttribute
{
    ILog logger;
    public LogFilterAttribute()
    {
        logger =  LogManager.GetLogger(typeof(LogFilterAttribute));
    }
    public override void OnException(ExceptionContext Context)
    {
        logger.Error(Context.Exception.Message + " - "  + Context.Exception.StackTrace);
    }
}
}


Add to the services the filter created:
services.AddControllersWithViews(p=> p.Filters.Add(new LogFilterAttribute()));

Now, all the exceptions are going to be saved in the log file. This log is on Api\bin\Debug\net5.0

Log Example

You still can use the .NET Logger class when you want to log something manually.

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 :: Comparison Of Unit Testing Tools In .NET

clock November 19, 2021 12:35 by author Peter

Unit testing helps developers to test their code written whether it meets design & requirements and behaves as expected before delivering to QA testing. This will help to identify problems at early stages of the development even though it can’t be replaced with integration testing & performance testing.
 
There are many unit testing frameworks available in the industry. To decide on which one to go for will always be a challenge and we need to choose the right one for our applications. Rewriting the unit test code again later in the lifecycle of the project will become costlier. Decision is a purely personal preference that is best suited for your application/project needs. Listed some of the tools for C# with pros & cons to compare and decide on which one to use for your applications.

Tool Description Pros Cons
CSUnit XUnit based framework which supports all .NET languages and integrated with Resharper
. Easy to use GUI
 
. Open Source
 
. Search capabilities across test, output & statistics 
 
. Statistics per test
 
. Rich set of attributes & assertions
 
. Parameterized & data-based testing
. No autogeneration of test code 
 
. Doesn’t support .NET 4.0 but does for .Net 3.5 & earlier versions
 
. No automatic linking of bugs and need configuration
NUnit xUnit based framework and supports all .NET languages. One of the popular & reliable tools. This is integrated with Resharper
. Independent test runner 
.Open Source
 
. Integration with 3rd Party tools for continuous Integration( Jenkins etc)
 
. Reliable tool 
 
. Fast
 
. Selective running of test cases
 
. Asynchronous execution
 
. Reports generation
. Not tightly integrated with Visual Studio
 
. No auto-generation of test code
 
. No automatic linking of bugs and need configuration
MSTest Command-line visual studio unit framework for executing visual studio generated unit tests . Integrates with Visual Studio
 
. Code Coverage is integrated
 
. Build Server is integrated
 
. Auto-generation of unit tests
 
. Automatically links bugs in Team Foundation Server
. Slower
 
. Tricky to integrate with 3rd party tools for Continuous integration
 
. Rich Reporting not available
 
. No asynchronous test execution
XUnit.Net Free and community-based .NET unit testing tool . Freshly written framework for the evolved .NET platform
 
. Flexible & cleaner code
 
. Create Test as Objects instead of methods
 
. Integrated tightly with MSBuild and stop the build in case of any failures in a test run
 
. Features lot similar to NUnit
. Lack of documentation
 
. Can’t run ignore test manually like Nunit
 
. Don’t provide a text message for the failed assertion
 
. No auto-generation of test code

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 :: Uploading Files With React.js And .NET

clock November 16, 2021 09:01 by author Peter

React.js + .NET is an amazing stack to create scaleable and high performance full stack applications. A common scenario is when we need to send files to a server in order to save them in a cloud service like Amazon S3 or Azure blob storage.

In this article, you will learn how to send files to .NET API from a React.js application.

First, In .NET we will create and endpoint with this
[HttpPost("ImportFile")]
public async Task < IActionResult > ImportFile([FromForm] IFormFile file) {
    string name = file.FileName;
    string extension = Path.GetExtension(file.FileName);
    //read the file
    using(var memoryStream = new MemoryStream()) {
        file.CopyTo(memoryStream);
    }
    //do something with the file here
}


If you want to try this endpoint you can use Postman with the following settings:

With this endpoint, we can read the file, all its properties and do something else like save it in Amazon S3.

Now, let's implement the client code.


import React, { useState } from "react";
import axios from "axios";

export const FileUpload = () => {
  const [fileSelected, setFileSelected] = useState();

  const saveFileSelected= (e) => {
    //in case you wan to print the file selected
    //console.log(e.target.files[0]);
    setFile(e.target.files[0]);
  };

  const importFile= async (e) => {
    const formData = new FormData();
    formData.append("file", fileSelected);
    try {
      const res = await axios.post("https://localhost:44323/api/importfile", formData);
    } catch (ex) {
      console.log(ex);
    }
  };

  return (
    <>
      <input type="file" onChange={saveFileSelected} />
      <input type="button" value="upload" onClick={importFile} />
    </>
  );
};

FormData helps us to send information with Content-Type:multipart/form-data and send files in HtmlForm format.

Also, you can add a format filter in the input file if you need it.
<input type="file" accept=".jpg, .png" onChange={saveFileSelected} />

With this approach, you can upload files to the server in a simple and save way.

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 :: Introduction Of ASP.NET Unique Architecture (AUA)

clock November 12, 2021 06:40 by author Peter

Software projects require constant changes and updates. If the structure develops in the wrong way, it will prevent changes and extensions, and most of the time will lead to task duplication or rewriting of the project from scratch. To get rid of the complexity and task duplication that most programmers and developers face, which is also caused by the inconsistency of code at different levels of the program, we need a simple consistent structure for writing software projects so that we can hide some of the complexity and focus on business of the task. For example, the Bootstrap framework is a very useful framework for Front End, but few people would prefer to use frameworks like Bootstrap for design, and write all of their design with CSS from the beginning. For the Back End section, however, a simple, general-purpose framework can save time and cost and produce high-quality code and a uniform architecture. This framework allows developers to develop their projects based on an appropriate integrated pattern. The framework must be flexible enough to allow the programmer to apply any changes needed, relying on its robust structure.

Why Framework?
One of the problems of software companies is the lack of the right structure for developing their projects. As a result, they have often produced such complex and nested code that creating changes in one part of the project severely affects or disrupts other parts. Therefore, the lack of the right structure for development makes it impossible to update the previous code and reduces the efficiency of the team to almost zero. The reason for this is the difference in coding and the lack of structure and architecture. The development team must first agree on a set of rules and structures. Architectural patterns are not the result of a programmer's experiences; they have resulted from the experiences of hundreds of programmers and design professionals over years. These frameworks are not innovations or inventions, but are feedbacks on redesign and recoding that programmers have been involved with in order to achieve the highest levels of flexibility, extensibility, and reusability. Their use makes the produced codes more simple, flexible, and extensible. The use of a framework can help us save time and cost and make it easier to document and maintain the system.

Asp.Net Unique Architecture(AUA) Framework
Using the AUA ( Asp.Net Unique Architecture ) Framework, you can easily have better, faster, and more orderly and focused coding. This framework is based on new and up-to-date concepts, structures, and architectures, including Clean Architecture, Clean Code, Domain-driven design (DDD), Lmax Architecture, SOLID Principle, Code Refactoring, GRASP (object-oriented design principle)AUA is a simple, lightweight framework for producing projects of any size(small and large). It can be applied in all architectures (Microservice, CQRS, etc.) due to its transparency in structure. It is also full of different design patterns, thus a great source for software architects and developers.
    Domain Driven Design (DDD)
    EF 6 and EF Core 3.0,3.1
    The ability to develop software in a simple and fast way
    Based on SOLID Principles
    Modular design
    Layered architecture

AUA Framework'sVersions
    Asp.Net MVC(.net framework and ef6)
    Asp.Net MVCCore 3.0,3.1
    Asp.Net Web API Core 3.0,3.1
    Asp.Net 5

AUA Framework's Overall Structure

The different layers of the AUA framework are as follows,

Layer's Name Use
Common Layer This layer contains common items used in other layers, such as Enums, Consts, Extensions,… ØŒTools
Data Layer This layer contains items associated with the data source, including Entity Framework Context, Db Extensions, Search Filters, Unit of Work Pattern, Configuration Tools, and Dapper Context
Domain EntityLayer This layer contains the entities and their configuration.
ModelsLayer This layer contains DTOs, View Models, and Config mapping: EntitiesDto, ReportModels, View Models,…
Service Infrastructure Layer The overall infrastructure of Services and Repository is written and becomes ready for use in this layer.
Service Layer This layer includes all the business services of your project, including BaseServices, BusinessService, EntitiesService, ReportService, etc.
WebApi or Ui Mvc Layer This is an interface user layer that can be written with General MVC- WebApi- GraphQl- Grapc.
Test Layer This layer is designed for writing Unit Tests (ToDo)
External web service Layer This layer is for calling external services. (ToDo)

Adding New Entity

Entity is the main concept, and indeed at the heart of the architecture of, the AUA framework. Each entity is defined by a class that contains its features and its relation to other entities. Each entity has an identifier that can be of any Data Type allowed in .NET, or it can be a combination of two or more Data Types allowed therein (combination key).

Entity Class
Each entity inherits from the DomainEntity class, to which a primary key field called Id and one or more monitoring fields (depending on the setting type) are added.

public class Student: DomainEntity {

    public string FirstName {

        get;

        set;

    }

    public string LastName {

        get;

        set;

    }

    public int Age {

        get;

        set;

    }

}

It should be specified if the primary key has a data type other than the int data type (e.g. the Long data type is considered under the primary key)

public class Student: DomainEntity < long > {
    public string FirstName {
        get;
        set;
    }
    public string LastName {
        get;
        set;
    }
    public int Age {
        get;
        set;
    }
}

By default, the following fields are added to each entity. The Id key of the primary key and its data type can be specified when defining an entity. The IsActive field shows whether the entity is active or inactive and it has a bool data type. The RegDate displays the date and time the entity is created (automatically created inside SQL Server) and does not need to be filled in and sent.

public class DomainEntity < TPrimaryKey > : BaseDomainEntity < TPrimaryKey > , IAuditInfo {
    public DateTime RegDate {
        get;
        set;
    }
}

public class BaseDomainEntity < TPrimaryKey > : IDomainEntity < TPrimaryKey > {
    public TPrimaryKey Id {
        get;
        set;
    }
    public bool IsActive {
        get;
        set;
    }
}

Entity Configs
There is a configuration class for each entity that can specify the length of field settings for it.
public class StudentConfig: IEntityTypeConfiguration < Student > {
    public void Configure(EntityTypeBuilder < Student > builder) {
        builder.Property(p => p.FirstName).HasMaxLength(LengthConsts.MaxStringLen50);
        builder.Property(p => p.LastName).HasMaxLength(LengthConsts.MaxStringLen50);
    }
}


Naming Pattern
Every company or project should have its own naming pattern to help us easily understand the previous concepts and add new concepts to the project. Good and consistent naming creates a good flow in your project, thereby increasing code readability and durability. An important feature of a good framework is having a good naming pattern, which all programmers should follow. In this framework, all components are named, such as: folder, file, class, function, variable, etc.

"You should name a variable with the same care we do in naming a first-born child" (Uncle Bob in Clean Code).


Each team must use a specific naming pattern, such that if any file is separated from the project, all programmers can specify the exact address of the file from the file name. For the AUA framework, we have suggested the following naming pattern.

Services
All business is implemented in the form of services and created in the service layer. The service layer uses the Service Infrastructure layer and automatically connects to each service in its own Repository. The advantage of this approach is that the developer is not involved in the two concepts of repository and service and focuses only on the service itself. The service has its own built-in Repository, which is one of the most important features of the AUA framework architecture. For example, if we want to write a service for StudentEntity, we must first create an interface for Student Entity which inherits from the IGenericEntityService class.
public interface IStudentService: IGenericEntityService < Student, StudentDto > {}

Service Types

Service Description
Entities Service These types of services are for working with entities and have a repository inside, Moreover, the business related to each entity is written in each service.
Business Service This type of service is intended for the implementation of businesses.
General Service General services that are used throughout the application, such as the login service - JWT Token service.
List Service Quick Report Service - To write quick operational reports.
Report Service A service used for getting Enterprise reports.
SQL Function Service A service used for access to SQL Function and Stored procedure.
Validation Service Services to validate the view models sent by clients.
Log Service Logging service.
InMemory Service Services used for working with in-memory data.
Views Service Services used for working with SQL Service views.
External Service Services used for working with the external service.
External Service Provider

Services to cover and match external services with the Core Domain.

Reporting

Reporting is the end product of operations and is especially important for users and managers of organizations and companies to use reports to meet their needs and users, faster and more dynamically.

This type of report is a quick and simple report that can be used for quick reporting and applying various filters to any entity. Creating this type of report is very simple and has a simple structure, and it is easy to apply various and professional filters. This type of report has one input model view and one output model view. Its Input model view includes filters that must be applied, but the report can have no filters and inputs. You can easily report from different tables and have a variety of reports. These types of operational reports are known as ListService in the structure of the AUA framework. In each report, if a non-zero value is sent to TotalCount from the input. The framework will not perform the TotalCount computations and will return the value with no change.

First: Create SearchVm
public class AppUserSearchVm: BaseSearchVm {
    public string FirstName {
        get;
        set;
    }
    public string LastName {
        get;
        set;
    }
    public string UserName {
        get;
        set;
    }
    public bool ? IsActive {
        get;
        set;
    }
}


Second: Create ListDto (to return the output)
public class AppUserListDto: IHaveCustomMappings {
    public string FirstName {
        get;
        set;
    }
    public string LastName {
        get;
        set;
    }
    public string UserName {
        get;
        set;
    }
    public string FullName => $ "{FirstName} {LastName}";
    public string Password {
        get;
        set;
    }
    public string Phone {
        get;
        set;
    }
    public string Email {
        get;
        set;
    }
    public DateTime RegistrationDate {
        get;
        set;
    }
    public string RegistrationDatePersian => RegistrationDate.ToPersianDate();
    public ICollection < RoleDto > UserRoleDtos {
        get;
        set;
    }
    public void ConfigureMapping(Profile configuration) {
        configuration.CreateMap < AppUser, AppUserListDto > ().ForMember(p => p.UserRoleDtos, p => p.MapFrom(q => q.UserRoles.Select(r => r.Role)));
    }
}


Third: Create interface (To Injection)
public interface IAppUserListService : IBaseListService<AppUser, AppUserListDto>
{
    Task<ListResultVm<AppUserListDto>> ListAsync(AppUserSearchVm appUserSearchVm);
}


Fourth: Create ListService (To apply filters)
public sealed class AppUserListService: BaseListService < AppUser, AppUserListDto, AppUserSearchVm > , IAppUserListService {
    public AppUserListService(IUnitOfWork unitOfWork, IMapper mapperInstance): base(unitOfWork, mapperInstance) {}
    public async Task < ListResultVm < AppUserListDto >> ListAsync(AppUserSearchVm appUserSearchVm) {
        SetSearchVm(appUserSearchVm);
        ApplyUserNameFilter();
        ApplyLastNameFilter();
        ApplyFirstNameFilter();
        ApplyIsActiveFilters();
        return await CreateListVmResultAsync();
    }
    private void ApplyUserNameFilter() {
        if (string.IsNullOrWhiteSpace(SearchVm.UserName)) return;
        Query = Query.Where(p => p.UserName.Contains(SearchVm.UserName));
    }
    private void ApplyLastNameFilter() {
        if (string.IsNullOrWhiteSpace(SearchVm.LastName)) return;
        Query = Query.Where(p => p.LastName.Contains(SearchVm.LastName));
    }
    private void ApplyFirstNameFilter() {
        if (string.IsNullOrWhiteSpace(SearchVm.FirstName)) return;
        Query = Query.Where(p => p.FirstName.Contains(SearchVm.FirstName));
    }
    private void ApplyIsActiveFilters() {
        if (!SearchVm.IsActive.HasValue) return;
        Query = Query.Where(p => p.IsActive == SearchVm.IsActive);
    }
}


You can inject reporting and use it.

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 :: Two Ways To Create Minimal APIs In .NET 6

clock November 2, 2021 10:21 by author Peter

Minimal API is a new template that uses all the C# 10 features and .NET 6 to create simple services with less complexity, layers, classes or using the traditional MVC template with controllers. This is inspired by other technologies like node.js, python, and go.

To create a minimal API, you can use the command dotnet new web in Dotnet CLI, or in Visual Studio 2022 (or higher), there is an empty template that creates the same structure.

 

All the logic and architecture are on one file, which is Program.cs where you will include the logic, classes, endpoints, and services. The template includes an endpoint with helloword example. Thanks to C# 10 features we don't need namespaces or the main method and class.


There are 2 ways to create the endpoints for Minimal APIs. First, using the endpoint methods directly where we have to manually get the services, the response, and parameters. In the following example, it's getting TodoDbContext from RequestServices and it is writing the response using WriteAsJsonAsync.
app.MapGet("/todoitems", async (http) => {
    var dbContext = http.RequestServices.GetService < TodoDbContext > ();
    var todoItems = await dbContext.TodoItems.ToListAsync();
    await http.Response.WriteAsJsonAsync(todoItems);
});


If you want to return a specific status code and get the parameter, you have to manually set it or get it. In the following example, it returns 400 when the id is not valid and 204 when it updates the record, also it is getting the context (TodoDbContext) from RequestServices again.

app.MapPut("/todoitems/{id}", async (http) => {
    if (!http.Request.RouteValues.TryGetValue("id", out
            var id)) {
        http.Response.StatusCode = 400;
        return;
    }
    var dbContext = http.RequestServices.GetService < TodoDbContext > ();
    var todoItem = await dbContext.TodoItems.FindAsync(int.Parse(id.ToString()));
    if (todoItem == null) {
        http.Response.StatusCode = 404;
        return;
    }
    var inputTodoItem = await http.Request.ReadFromJsonAsync < TodoItem > ();
    todoItem.IsCompleted = inputTodoItem.IsCompleted;
    await dbContext.SaveChangesAsync();
    http.Response.StatusCode = 204;
});


The second way is to use the attributes and results object. This looks very similar to the traditional APIs using MVC and controllers. [FromServices] get the services in the configuration.
app.MapGet("/todoitems/{id}", async ([FromServices] TodoDbContext dbContext, int id) => {
    var todoItem = await dbContext.TodoItems.FindAsync(id);
    if (todoItem == null) {
        return Results.NotFound();
    }
    return Results.Ok(todoItem);
});

To use results and the FromServices attribute you have to add using Microsoft.AspNetCore.Mvc; in the file.

Full code: Mteheran/DotnetMinimalApi (github.com)

Both methods are correct, but finally, if you want to use something easier to read, the second way, where we use decorators and result functions, is much better.



European ASP.NET Core Hosting :: IActionResult Vs ActionResult

clock October 25, 2021 10:04 by author Peter

IActionResult is an interface and ActionResult is an implementation of that interface.

ActionResults is an abstract class and action results like ViewResult, PartialViewResult, JsonResult, etc., derive from ActionResult.

Let's say you want to create an action result not catered to by MVC, say an XML result.

IActionResult is an interface, we can create a custom response as a return, when you use ActionResult you can return only predefined ones for returning a View or a resource. With IActionResult we can return a response, or error as well. On the other hand, ActionResult is an abstract class, and you would need to make a custom class that inherits.

For example see below,
    publicNoContentResultNoContentActionResult() {  
        returnNoContent();  
    }  
    publicIActionResult NoContentActionResult() {  
        returnNoContent();  
    }  
    OR  
    publicIActionResult JsonActionResult() {  
        returnNotFound();  
    }  
    publicJsonResult JsonActionResult() {  
        returnNotFound(); // This line will give Error  
    }  


From the above examples we can return NoContent() OR NotFound() from IActionResult. But if you want to use such type of return values with ActionResults, you need to use particular ActionResults, NoContentResult And JsonResult.

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 :: Error Message 401.2. - Unauthorized - Logon Failed Due To Server Config

clock October 21, 2021 08:14 by author Peter

Sometimes, we get this error message after publishing the solution in IIS. This error is quite common.

Exact Error
Error message 401.2.: Unauthorized: Logon failed due to server configuration. Verify that you have permission to view this directory or page based on the credentials you supplied and the authentication methods enabled on the Web server. Contact the Web server’s administrator for additional assistance

This particular error happens mostly because of the authentication setting in IIS.

Solution
Open the IIS.

Select the site you are facing the issue.

Select Authentication Setting as shown,

Error Message 401.2.: Unauthorized: Logon failed due to server config

 

Based on your application requirement, you can update authentication options.

In my case, the application needs to set windows authentication, therefore, I set it to enabled and Anonymous Authentication Disabled.

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