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

 


 



European ASP.NET Core Hosting :: Disposable Types - Properly Disposing Objects

clock October 18, 2021 07:12 by author Peter

Microsoft .NET has been around for 20 years and one thing that is very critical for every to know is exactly how memory management works in the runtime. If you don’t, you will cause performance issues but more serious is causing virtual memory leaks. The way that .NET was designed back in the late ’90s is that it does not have memory leaks in the true sense, but it can create virtual memory leaks.

In a nutshell, if your app has a virtual memory leak, the memory is not destroyed correctly properly, and the leak just keeps building up until the app or service crashes. I have even seen it bring down servers on the backend (I have written about this many times before, so I won’t re-tell them here) and in client apps.
This article covers the way to dispose of objects properly for most cases. There are edge cases where Dispose should not be called due to the lifetime of the object. That will be covered in a separate article.

The reason I decided to write a comprehensive set of articles about reference types that implement IDisposable and where you might need to in your types is because of a recent solution I worked on. Unfortunately, this solution has the most issues of any of the millions of lines of code I have analyzed in the past 20 years. I had hoped that after all this time, developers would know how to do this correctly, but sadly it is obvious to me far too many do not, so I hope these articles will help this critical issue.

This solution has a little over a million lines of code. First, I found over 600 places in the code where Dispose() is not being called on Disposable types. Also, I found over 90 types that either did not implement IDisposable correctly or did not implement it when it needed to. For the classes that did implement IDisposable, not even one did it correctly. These changes will cause over 2,000 touchpoints in the code that will need to be changed, code reviewed, tested, and deployed.

The reason I’m sharing these real-world numbers is that if developers do not deal with these types when the code is first written, it will be very, very expensive and time-consuming to fix later down the road (if they even get fixed). Far too many teams do not understand why they must restart servers or services on a regular basis… this is the reason! Please use these articles as a warning for your team and management!

New Code Rules
I feel so strongly about this I made it the topic of a recent New Code Rules segment on my show Rockin’ the Code World with dotNetDave on C# Corner Live. I rant in this video but also give ideas for Microsoft to once and for all solve this issue so developers do not need to worry about it and so apps and services stop failing.

Two Types of Memory Management in .NET
Microsoft .NET handles memory in two very different ways that every developer needs to fully understand. The first is the memory stack where all value types are created. The second is the memory heap where all reference types are created and managed by the garbage collector, and this will be the focus of this article. How do you know if a type is a value or reference type? It’s fairly easy… all types such as DateTime, integer, Boolean, or any of the framework types that are number-based, plus user-defined types (structures), are value types and live on the memory stack. Everything else, including the classes you create, are reference types and live on the memory heap. Essentially if you create a type by using ‘new’, it’s a reference type, including the string type. Reference types are what needs attention, especially if they implement IDisposable or contain any disposable fields.
The Memory Heap

People have been writing about how the memory heap works in .NET since it was released, so I won’t rehash that here since that would be an article (or an eBook) in itself. If you are new to .NET or don’t fully understand how the memory heap and the Garbage Collector works, go here for more detailed information from Microsoft.

I will quickly mention that the reason .NET is very performant is that when objects are created on the heap, they are always created at the top of the heap. When an object is no longer is used, it is marked to be removed from memory by the Garbage Collector (GC). They do not go away at the end of the code block! Then the heap is compacted by the GC. When are they are removed from memory?

Whenever the Garbage Collector wants to!

Well, it’s a lot more complicated than that, but just remember, developers have no real direct control over the GC. All we can do is allocate cautiously, release objects as soon as possible, and most importantly call Dispose on any disposable objects or implement IDisposable for the types we create that contain a field that is a disposable type. In the early days of .NET, I spent a lot of time watching and learning how the GC works, so I understand it well. Also, twice I had one of the engineers who created the GC speak at the user group I ran for 20 years. Listening to him and speaking with him taught me even more about how memory works in .NET and the pitfalls of the GC.
Disposing Disposable Types

First, let us get into what I teach my beginner students when I taught at a university.

It is critically important to call Dispose() on any type that implements IDisposable!

If a type implements IDisposable it means that it has something it needs to clean up like file handles, memory pointers, other disposable types, and more. So, developers MUST call Dispose as soon as the object is done being used. How do you know if a type implements IDisposable? There are two simple ways.

The first is, just type “.Dispose” at the end of the variable for the type, if it comes up in Intellisense, then you need to call it. The other method is to right mouse click on the type and selects ‘Go to Definition’ and see if IDisposable is in the definition of the class. This is exactly what I tell my beginner students. After you deal with disposable types for a while, you will start to remember which ones are. Here are some helpful tips that I use when I first analyze a codebase.

    If the type name ends in “Stream”, it’s disposable.
    If the type name ends in “Writer” or “Reader”, it’s most likely disposable.
    Any types that deal with graphics are most likely disposable such as the Bitmap type.
    If the type deals with connections, such as databases, sockets, HTTP, it’s disposable. This also includes related types such as DataTable and MailMessage and more.

How we dispose of disposable objects has changed since .NET was created. The safest, recommended way is by using the using pattern and statement.

Here is how to properly use the using statement pattern (the code below is from my OSS called Spargine).
public static TResult Deserialize<TResult>(string xml) where TResult: class
{
    using(var sr = new StringReader(xml))
    {
        var xs = new XmlSerializer(typeof(TResult));
        return (TResult) xs.Deserialize(sr);
    }
}


First, the Disposable object is created in the using statement. When the end of that code block is reached, then Dispose of will be called by the runtime. What happens is that the compiler creates a try/finally block and calls Dispose of in the final as shown in the IL code below.

You can also use the simple using statement as shown below,

using var sr = new StringReader(xml);
var xs = new XmlSerializer(typeof(TResult));
return (TResult) xs.Deserialize(sr);

Both using statements do the same thing, but I tend to prefer the original using statement since for me as a code reviewer, it’s easier for me to spot where it’s being used or isn’t being used.
Hidden Disposable Issues

Other “hidden” disposable issues also need to be considered. Some developers who like to put as much code on one line could run into issues. Here is an example.

public static TResult Deserialize<TResult>(string xml) where TResult: class
{
    var xs = new XmlSerializer(typeof(TResult));
    return (TResult) xs.Deserialize(new StringReader(xml));
}

The issue with this is the final line where a new StringReader is created. StringReader is a disposable type and as you can see, there isn’t a call to Dispose in the code or any use of a using statement. Therefore, code like this will cause memory leaks! I can prove that Dispose is not being called by looking at the IL for this method.


As you can see, there isn’t a call to Dispose in the IL. So, it’s very important to not code Disposable types like this but instead using one of the using statements. I wished that Visual Studio and the compilers would not allow disposable types to be created in this manner.

The takeaway from this article is that it is critically important to make sure all your code is properly disposing of disposable types. Not only could this improve the performance of your apps, but more importantly your apps will be free of virtual memory leaks.

I challenge everyone reading this article to do a critical scan of your codebase NOW to ensure that all your disposable types are being disposed of. I would love to hear how many of these issues you found. Just comment below.

Part 2 of this article will tackle how to properly implement the IDisposable interface for types that you create that have field variables that hold disposable types. Part 3 of this article will discuss how to use tools to help you find these issues in your code.



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