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



European ASP.NET Core Hosting :: News Feed System Design

clock October 13, 2021 08:43 by author Peter

News Feed is the constantly updating list of stories in the middle of your home page. It includes status updates, photos, videos, links, app activity, and likes from people, pages, and groups that you follow.

There are two main components in the news feed,

  • Publishing the posts
  • Retrieving the posts

Let’s first concentrate on publishing the post.

Publishing a Post

It is pretty straightforward. You log in to the website/app. Under the post, you write the text that you want to post and hit the submit button. As soon as you click on the submit button, the request sends to the server where it first gets authenticated. The server checks whether the user who has to send the request is a valid user or not. The load balancer is used to distribute the traffic to web servers. The web server sends the request data to the post publisher where it gets saved into the database as well as in the post cache for fast retrieval.

Once the post has been saved into the database successfully. Now it’s time to fan out the post.
Fanout

The process of pushing a post to all the followers is called fanout.

There are two ways we can Fanout a post,
    Fanout Read
    Fanout Write

Fanout Read
When you request for news feed, you create a read request to the system. With fanout read, the read request is fanned out to all your followers to read their posts. The feed is created during the read time. Usually, it pulls recent posts of a user.

Pros
    No need to pre-compute the posts for in-active users.
    The cost of the write operations is low.

Cons
    The time taken to load the feed is more as compare to the Fanout Write.
    It can take a lot of time if a user has many followers.
    You cannot update the user feed on a real-time basis. The user has to request the feeds in case he/she wants to see the latest posts.

Fanout Write
In this case, as soon as the post is published, it gets fanned out to all the friends immediately. Most of the work is done at the time of writing to figure out who will get this post. This significantly reduces the read operations on the system. This approach is not recommended if a user has a large number of followers.

Pros
    The cost of the read operation is low.
    Feed is generated in real-time and pushed to all the friends.
    Displaying the feed is faster as compare to the fanout read because it’s pre-computed.

Cons
    It can take significant time if a user has too many friends.

Hybrid
In this approach, we will take the benefits from both the above approaches (Fanout Read and Write). Allowing the users with a less number of followers to use the Fanout Write model whereas the users with a higher number of followers, a Fanout Read model will be used.
Retrieval

When a user sends a request to retrieve a news feed, it lands on the load balancer which distributes the request to different web servers. The news feed service gets the request from the web servers to fetch the news feed from the cache. The news feed cache returned the post ids for the specific user. User cache returns the user-related info and post cache returns the post-related info. Once everything is computed, we send back the response to the web servers that further deliver the content to the user.


Improvement
Scale the System
As the number of users and posts increases, the current system might now be able to handle the load. So we need to scale the system horizontally. There are different ways we can scale the system. We can use Master-Slave System to separate the read and write operations on the system. We can also use Sharding on the data. We can shard the system based on the feed data and posts. The other improvement we can do is to limit the number of requests that we are getting by implementing the Rate Limiting Module at the webserver level.

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 :: HandleError Action Filter In ASP.NET MVC

clock October 6, 2021 07:33 by author Peter

In this article, you will learn how to handleIn all the software Applications, Exception Handling plays a critical role. An exception can also be thrown during runtime, because of some mathematical calculations, some invalid data, or maybe because of network failure etc. ASP.NET MVC has HandleError Attribute (Action Filter), which provides one of the simplest ways to handle errors. HandleError Attribute has a couple of properties which are useful in handling an exception and help in modifying the default behavior of HandleError Attribute.

ExceptionType: Exception Type specifies the type of an exception. If not specified, then HandleError filter handles all the Exception.

View: Specifies the name of view to display when an exception occurs.

Master: Master specifies the name of the master view.

Order: If more than one HandleError attribute is used, then the order specifies the order of the filters applied. We can set an integer from -1 (Highest Priority) to any positive integer. If no order is specified, then the Order value is -1.

In order to use HandleError Attribute, first, we have to enable Custom Error in web.config file.

Let’s Start,
Create a new ASP.NET MVC Project. errors using HandleError Action Filter in ASP.Net MVC.


Select Empty MVC Template and click OK.


    public class HomeController : Controller  
    {  
            // GET: Home  
            public ActionResult Index()  
            {  
                return View();  
            }  
    }  


Right click on View and click on Add View.
    @{  
        ViewBag.Title = "Index";  
    }  
      
    <h2>Home</h2>  
    @Html.ActionLink("About Us","About","Home")  

I have also added About Action method in HomeController. For demonstration purposes, I will throw an exception on calling About Action Method.
    public ActionResult About()  
    {  
                //Throws an exception for demonstration  
                throw new Exception("Some unknown error encountered!");  
                return View();  
     }  


On clicking About us link, you will see the exception is thrown and Yellow Screen of death appears.


Hackers can easily take advantage of the yellow screen of death, because it shows some valuable/secret code. In order to prevent the Yellow screen of death, we have to add Custom Error in web.config file.
    <system.web>  
        <customErrors mode="On"></customErrors>  
    </system.web>  


Add HandleError Attribute on About Action method of HomeController.
    [HandleError]  
    public ActionResult About()  
    {  
                //Throws an exception for demonstration  
                throw new Exception("Some unknown error encountered!");  
                return View();  
    }  


Add shared folder in Views and then add an Error View (error.cshtml), which will be shown when an exception is thrown.

    @{  
        Layout = "~/Views/Shared/_Layout.cshtml";  
    }  
      
    <h3>An error occurred while processing your request. Please contact the administrator.</h3>  

Preview


We can also declare HandleError attribute on the Controller level as well as on Action method. Declare HandleError attribute on an Action method.


Declare HandleError attribute on the Controller level.


Using View property of HandleError attribute, we can show the specified view on getting unhandled exceptions.
    [HandleError(View = "Error")]  

Adding more than One HandleError attribute

We can control the view to be displayed based upon ExceptionType.
    //If Format Exception thrown then SpecificError View is displayed  
    //If Divide by Zero Exception thrown then Error View is displayed  
    [HandleError(View = "SpecificError", ExceptionType = typeof(FormatException))]  
    [HandleError(Order = 2, View = "Error", ExceptionType = typeof(DivideByZeroException))]  
    public ActionResult About()  
    {  
           //Throws an Exception for demonstration  
           throw new FormatException();  
           return View();  
    }  


In the example shown above, if FormatException Occurs, then it will Show SpecificError.cshtml error view or if DivideByZeroException Exception occurs, then it will show Error.cshtml View.
 
Show Error Details
We can also show error detail on getting an exception. HandleErrorInfo class provides information for handling an error that is thrown by the Action method. HandleErrorInfo has several properties like ActionName, ControllerName, and Exception, which help in getting additional information about the exception.
    [HandleError(View = "DetailedError")]  
    public ActionResult About()  
    {  
           //Throwing an Exception for demonstration  
           throw new DivideByZeroException();  
           return View();  
    }  


In the code, shown above, we set DetailedError View for showing the exception.
    @model System.Web.Mvc.HandleErrorInfo  
      
    @{  
        Layout = "~/Views/Shared/_Layout.cshtml";  
    }  
      

    <h4>Error Details:</h4>  
    <p>Controller Name: @Model.ControllerName</p>  
    <p>Action Name: @Model.ActionName</p>  
    <p>Exception: @Model.Exception</p>  


Preview


Setting HandleError Attribute as a Global Filter
We can register HandleError attribute as a global error handling filter. Open Global.asax file and add the code, given below:
    protected void Application_Start()  
    {  
           AreaRegistration.RegisterAllAreas();  
           GlobalFilters.Filters.Add(new HandleErrorAttribute());  
           RouteConfig.RegisterRoutes(RouteTable.Routes);  
    }  

Now, remove all the HandleError attributes from HomeController, build and run the Application.
 
Handle Errors related to Http Status Code
If we visit the path that doesn’t exist it will throw an HTTP 404 exception.

In order to handle it, first, we have to add an Action Method (NotFound in my case), which will return the NotFound.cshtml view.
    public ActionResult NotFound()  
    {  
           return View();  
    }  

NotFound.cshtml Code
    @{  
        Layout = "~/Views/Shared/_Layout.cshtml";  
    }  
      
    <h4>HTTP 404. The resource you are looking for doesn’t exist or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.</h4>  

Now, open web.config file and add the following line of code:
    <customErrors mode="On">  
          <error statusCode="404" redirect="~/Home/NotFound"/>  
    </customErrors>  


Preview


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 :: Save Request And Response Headers In ASP.NET 5 Core

clock October 4, 2021 07:36 by author Peter

In a typical request-response cycle, the request and response headers contain a lot of additional information. This article talks about how to retrieve them and store them in a database. In this article, we’ll use PostgreSQL as the database and connect to it using dotConnect for PostgreSQL.

To be able to work with the code examples demonstrated in this article, you should have the following installed in your system:
    Visual Studio 2019 Community Edition
    PostgreSQL
    dotConnect for PostgreSQL

Create a new ASP.NET Core 5.0 Project in Visual Studio 2019

Assuming that the necessary software has been installed on your computer, follow the steps outlined below to create a new ASP.NET Core Web API project.

  • First off, open the Visual Studio 2019 IDE
  • Next, click "Create a new project" once the IDE has loaded
  • In the "Create a new project" screen, select “ASP.NET Core Web API” as the project template.
  • Click the "Next" button
  • Specify the project name and location - where it should be stored in your system
  • Optionally, click the "Place solution and project in the same directory" checkbox.
  • Next, click the "Create" button
  • In the "Create a new ASP.NET Core Web Application" dialog window that is shown next, select "API" as the project template.
  • In the “Additional Information” screen, .NET 5.0 is the framework version.
  • You should disable the "Configure for HTTPS" and "Enable Docker Support" options by disabling the respective checkboxes.
  • Since we'll not be using authentication in this example, specify authentication as "No Authentication".
  • Finally, click on the "Create" button to finish the process.

This will create a new ASP.NET Core Web API project in Visual Studio.

Install NuGet Package(s)
To work with dotConnect for PostgreSQL in ASP.NET Core 5, you should install the following package into your project:
Devart.Data.PostgreSQL

You have two options for installing this package: either via the NuGet Package Manager or through the Package Manager Console Window by running the following command.
PM> Install-Package Devart.Data.PostgreSQL

Request and Response Headers in ASP.NET Core
Request headers provide more information about the requested resource or the client who is requesting it. You can take advantage of request headers to add extra information to the HTTP Request.

The response headers contain additional information about the response, such as its location and the server. It is an HTTP header that can only be used in an HTTP response and doesn't have to do anything with the content of the message. To provide more context to the response, you can use response headers like Age, Server, and Location.

Both Request headers and Response headers are represented as a collection of key-value pairs that can be passed back and forward between the client and the server.

Reading Request and Response Headers in ASP.NET Core
You can read request and response headers using the Request and Response properties of the HttpContext class. These properties are of HttpRequest and HttpResponse types respectively.

You can use the following code to retrieve the request headers in ASP.NET:
List < string > AllRequestHeaders = new List < string > ();
var requestHeaders = httpContext.Request.Headers.Where(x => AllRequestHeaders.All(h => h != x.Key)).Select(x => x.Key);


The following code snippet can be used to retrieve all response headers:
List < string > AllResponseHeaders = new List < string > ();
var uniqueResponseHeaders = httpContext.Response.Headers.Where(x => AllResponseHeaders.All(h => h != x.Key)).Select(x => x.Key);


Building a Middleware to Read Request and Response Headers

A middleware is a software component that processes requests and responds. ASP.Net Core typically has a series of middleware components - these middleware components either process requests or pass them to the next component in the request processing pipeline.

Create a new class in your project's root and name it as RequestResponseHeaderMiddleware. Next, replace the default code with the following:
public class RequestResponseHeadersMiddleware {
    private readonly RequestDelegate _next;
    public RequestResponseHeadersMiddleware(RequestDelegate next) {
        _next = next;
    }
    public async Task Invoke(HttpContext httpContext) {
        await _next.Invoke(httpContext);
    }
}

This is a minimalistic implementation of middleware in ASP.NET Core. However, it doesn’t do anything other than passing the control to the next component in the pipeline.

We need to add the logic of reading requests and response headers. We’ve already written the code in the previous section. Here’s the updated version of our middleware:
public class RequestResponseHeadersMiddleware {
    private readonly RequestDelegate _next;
    public readonly List < string > AllRequestHeaders = new List < string > ();
    public readonly List < string > AllResponseHeaders = new List < string > ();
    public RequestResponseHeadersMiddleware(RequestDelegate next) {
        _next = next;
    }
    public async Task Invoke(HttpContext httpContext) {
        var requestHeaders = httpContext.Request.Headers.Where(x => AllRequestHeaders.All(h => h != x.Key)).Select(x => x.Key);
        AllRequestHeaders.AddRange(requestHeaders);
        await this._next.Invoke(httpContext);
        var uniqueResponseHeaders = httpContext.Response.Headers.Where(x => AllResponseHeaders.All(h => h != x.Key)).Select(x => x.Key);
        AllResponseHeaders.AddRange(uniqueResponseHeaders);
        await _next.Invoke(httpContext);
    }
}


Create an Extension Method for the Middleware
We’ll now create an extension method for our middleware to be able to conveniently configure the middleware in the Configure method of the Startup class.

To do this, create a new class named RequestResponseHeadersMiddlewareExtensions in a file called RequestResponseHeadersMiddlewareExtensions.cs with the following code in there:
public static class RequestResponseHeadersMiddlewareExtensions {
    public static IApplicationBuilder UseRequestResponseHeadersMiddleware(this IApplicationBuilder builder) {
        return builder.UseMiddleware < RequestResponseHeadersMiddleware > ();
    }
}


Configure the Middleware in the Startup Class
You can write the following code in the Configure method of the Startup class to enable the custom middleware we have built thus far.
app.UseRequestResponseHeadersMiddleware();

Create the Model
Now create the following class in a file of the same name having an extension .cs. We'll use it to store request and response header values.
public class RequestResponseHeader {
    public string RequestHeader {
        get;
        set;
    }
    public string ResponseHeader {
        get;
        set;
    }
}


Create the DbManager Class
The DbManager class wraps all calls made to the database using dotConnect for Postgresql. It has just one method named Save to persist the request and response header values in the Postgresql database.
public class DbManager {
    private readonly string connectionString = "Some connection string...";
    public int Save(RequestResponseHeader requestResponseHeader) {
        try {
            using(PgSqlConnection pgSqlConnection = new PgSqlConnection(connectionString)) {
                using(PgSqlCommand cmd = new PgSqlCommand()) {
                    cmd.CommandText = "INSERT INTO
                    public.requestresponseheaders " +
                    "(requestheader, responseheader) " + "VALUES (@requestheader, @responseheader)";
                    cmd.Connection = pgSqlConnection;
                    cmd.Parameters.AddWithValue("requestkey", requestResponseHeader.RequestHeader);
                    cmd.Parameters.AddWithValue("responsevalue", requestResponseHeader.ResponseHeader);
                    if (pgSqlConnection.State != System.Data.ConnectionState.Open) pgSqlConnection.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
        } catch {
            throw;
        }
    }
}


Call the Save Method from the Middleware
We’ll now modify the middleware we’ve implemented to store the request and response headers in a PostgreSQL database using dotConnect for PostgreSQL.

You can use the following code snippet to call the Save method of the DbManager class from the middleware we implemented earlier.
for (int index = 0; index < AllRequestHeaders.Count; index++) {
    RequestResponseHeader requestResponseHeader = new
    RequestResponseHeader();
    requestResponseHeader.RequestHeader = AllRequestHeaders[index];
    requestResponseHeader.ResponseHeader = AllResponseHeaders[index];
    dbManager.Save(requestResponseHeader);
}

As you can see here, there are two string collections namely AllRequestHeaders and AllResponseHeaders that hold the request and response header values respectively. We saw how it is done earlier in the article.

In this code snippet, an instance of RequestResponseHeader is created, its properties initialized and then this instance is passed as a parameter to the Save method.

Here is the complete code of the middleware for your reference:
public class RequestResponseHeadersMiddleware {
    private readonly RequestDelegate _next;
    public readonly List < string > AllRequestHeaders = new List < string > ();
    public readonly List < string > AllResponseHeaders = new List < string > ();
    private readonly DbManager dbManager = new DbManager();
    public RequestResponseHeadersMiddleware(RequestDelegate next) {
        _next = next;
    }
    public async Task Invoke(HttpContext httpContext) {
        var requestHeaders = httpContext.Request.Headers.Where(x => AllRequestHeaders.All(h => h != x.Key)).Select(x => x.Key);
        AllRequestHeaders.AddRange(requestHeaders);
        await this._next.Invoke(httpContext);
        var uniqueResponseHeaders = httpContext.Response.Headers.Where(x => AllResponseHeaders.All(h => h != x.Key)).Select(x => x.Key);
        AllResponseHeaders.AddRange(uniqueResponseHeaders);
        await _next.Invoke(httpContext);
        for (int index = 0; index < AllRequestHeaders.Count; index++) {
            RequestResponseHeader requestResponseHeader = new
            RequestResponseHeader();
            requestResponseHeader.RequestHeader = AllRequestHeaders[index];
            requestResponseHeader.ResponseHeader = AllResponseHeaders[index];
            dbManager.Save(requestResponseHeader);
        }
    }
}


In ASP.NET Core, you can read request and response headers in your application easily. Request headers allow you to work with optional data that is stored as key-value pairs. Response headers include extra information about the response that allows for a more comprehensive context of the response to be sent to the client.

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