A Three Tier Architecture Project to Read and Write From a Json or Xml Using C#

Table of Content

  • What is three-tier compages?
  • What are the differences between layer and tier?
  • Why is three-tier architecture the near mutual use?
  • How does information technology piece of work?
  • How to build and deploy a three-tier application with C#?
    • Data-tier with SQL Server
    • Application tier with C#
    • Presentation tier with Athwart

Hi, back to the architecture patterns, in the final article I explained what the 3-layer compages is and how to apply it to a project. Today we volition keep to explore the iii-tier architecture which tin exist considered as a distributed system compages.

Practiced products are ofttimes built with a multi-tier architecture, a.1000.a n-tiers. The nearly popular grade of north-tier is the three-tier application. Although the three-tier application is a very well-known and prevalent compages, it's not entirely credible to developers who are new in software projection development. This commodity will explicate each tier of this architecture and share the best practices in our projects with C#.

What is 3-tier architecture?

Iii-tier compages is client-server architecture. The application is separated into physical calculating tiers, which means the business logic, data storage, information access, and user interface are developed and maintained as single modules on separate platforms.

Similarly to the three-layer compages, the 3-tier architecture classifies an application into three main logical components but deploy them on different physical computing tiers:

  • Presentation tier
    The tier is the user interface of the application, where users interact with the application. Its main purpose is to brandish information to and collect data from users. This is the peak-most level in the architecture and can exist run on the spider web browser or a desktop/mobile awarding.
  • Application tier
    This is the eye of the awarding, better known equally the logic tier or middle tier. It coordinates all business organisation logic of the application, prescribes how business organisation objects interact with each other. It handles collected information from the Presentation tier. During the process, this tier may need to access the Data-tier to retrieve or modify the data. In a three-tier application, all communication goes smoothly through the Application tier. The Presentation tier and the Data-tier can non communicate direct with ane another.
  • Data-tier
    The Data-tier is sometimes referred to equally the database tier, where it stores and manages the information processed by the Application tier.

What are the differences between layer and tier?

There are divergent opinions on this consequence. Layer and tier are ofttimes used interchangeably - this is a mistake.

The critical difference between layer and tier is virtually how it is organized. A multi-layer architecture refers to separating the awarding into multiple logical units that run on the same infrastructure. In contrast, a multi-tier architecture refers to separating the application into numerous concrete units that run on separated infrastructures.

Some other departure comes from the responsibleness of the everyman component in each architecture:

  • Data-tier in three-tier architecture: stores and retrieves data.
  • Data Admission layer in three-layer architecture: enforces rules regarding accessing data, providing simplified admission to data stored in persistent storage.

The Data Admission layer does non provide information, so in most cases, it will be in the Application tier (some designs separate it into a tier).

From that betoken of view, a tier can comprise multiple layers. For example, a camera awarding on your phone is n-layer; it also can be called a single-tier application as all of the processes are executed on your phone:

  • Presentation layer: a user interacts with the app to capture an image
  • Business Logic layer: the app handles the captured paradigm past converting it to binary, and then sends the handled information to the Information Access layer.
  • Information Access layer: the app accesses the memory on your device to shop the handled information.

Why is three-tier compages the nearly mutual use?

Because of the logical and physical separation of functionality, each tier can run on a split up hosting environment. Typical servers to deploy a iii-tier awarding are spider web server, awarding server, and database server, each serves appropriate functional requirements. Each tier operates separately, then its services can be customized and optimized without affecting the other tiers.

  • Speed up the development: As each tier tin exist enhanced simultaneously by different teams, so time to market of the product is optimized, and developers tin can use the latest tools and the all-time languages for each tier.
  • Improve the scalability: Past deploying the application on unlike tiers, you are able to scale any tier independently of the others at any given time.
  • Better the reliability: Considering information technology has different tiers, you tin also boost reliability and availability by running disparate parts of your application on singled-out servers and employing cached results.
  • Improve the security: By using a well-designed application tier, it functions as a sort of internal firewall, which will help to forbid SQL injections and other malicious exploits.

How does information technology work?

ThreeTierArchitecture

The Presentation tier - the individual level where the user can interact with the application, collect data from the user, validate them if needed and and so send information technology to the Application tier via an HTTP asking.

The Application tier receives the (validated) data from the Presentation tier, then processes it by relevant business organization logic based on the Presentation requested. During the procedure, the Application tier may admission the Data-tier to query data (call back/alter/store data) if necessary.

The Information-tier receives commands from the Application-tier, executes them, then sends a response back to the Application tier.

The Awarding tier receives the executed result and processes it. In one case the procedure is completed, the Application tier sends the information dorsum candy to the Presentation tier.

The Presentation tier receives the processed information and then presents them to the user.

How to build and deploy a three-tier application with C#?

To guide y'all build and deploy a three-tier application, I have prepared a demo with the following components:

Presentation Tier: Athwart

Presentation tier

Awarding tier: Applying the three-layer compages for the Application tier. It is explained in How to build and deploy a three-layer compages application with C#.

Application tier

Data-tier: MS SQL Server

Data tier

To easily follow the article, you can download the demo of the three-tier architecture sample.

The diagram below explains how the application was designed.

ThreeTierAppDesign

Data-tier with SQL Server

Create database project
Let's use the database project template in Visual Studio 2019 and create a database projection.

New projects

Blueprint database
One time the projection is created, design your tables, views, and stored procedures for this database. Also, add a script to initialize the data when the project is published to SQL Server.

Design database

Design Database 1

Design database 2

Design Database 3

Deployment
Right-click on the projection and select Publish.

Deployment

Side by side, specify your SQL Server connection and database name, and then click on Publish.

Database setting

Testing
Open up your SSMS to check for the result.

Testing 3-tier

Application tier with C#

This is the center of the three-tier architecture, which is besides the almost complicated and challenging tier of implementation, so nosotros need a expert pattern to manage and organize the code. That is why I used iii-layer architecture for this tier.

This tier does not interact with users; it volition interact with the other tiers/applications. This ways the Presentation layer (of the Awarding tier) is not a User Interface; information technology is an Application Interface, more than unremarkably known as Application Programming Interface (API).

Please follow How to build and deploy a three-layer architecture application with C# , the Data Access layer (Infrastructure), Domain layer, and Business organization Logic layer (Service) can be reused from this commodity. To accomplish the Presentation layer (of the Application tier), I volition use ASP.NET Core Spider web API as an interface to interact with the Presentation tier (in three-tier compages).

Create WebAPI layer - Asp.Cyberspace Core Web API Application

Let'southward follow this tutorial to create an ASP.Internet Cadre Web API application.

Once the application is developed, create a ServiceCollectionExtensions form under the Extensions folder.

ApplicationTier.API/Extensions/ServiceCollectionExtensions.cs

  • AddDatabase: annals the database instances
  • AddServices: register service instances
  • AddCORS: access from external applications to this application(via API layer)
                            using              System;              using              ApplicationTier.Domain.Interfaces;              using              ApplicationTier.Domain.Interfaces.Services;              using              ApplicationTier.Domain.Models;              using              ApplicationTier.Infrastructure;              using              ApplicationTier.Service;              using              Microsoft.EntityFrameworkCore;              using              Microsoft.Extensions.DependencyInjection;              namespace              ApplicationTier.API.Extensions              {              public              static              class              ServiceCollectionExtensions              {                              ///                                            ///                Add needed instances for database                              ///                                            ///                                            ///                                            public                static                IServiceCollection                AddDatabase(                  this                  IServiceCollection services)              {              // Configure DbContext with Scoped lifetime                            services.AddDbContext(options =>                 {                     options.UseSqlServer(AppSettings.ConnectionString,                         sqlOptions => sqlOptions.CommandTimeout(120));                     options.UseLazyLoadingProxies();                 }             );               services.AddScoped<Func>((provider) => () => provider.GetService());             services.AddScoped();             services.AddScoped<IUnitOfWork, UnitOfWork>();              return              services;         }                              ///                                            ///                Add instances of in-utilize services                              ///                                            ///                                            ///                                            public                static                IServiceCollection                AddServices(                  this                  IServiceCollection services)              {              render              services.AddScoped<IWorkService, WorkService>();         }                              ///                                            ///                Add CORS policy to allow external accesses                              ///                                            ///                                            ///                                            public                static                IServiceCollection                AddCORS(                  this                  IServiceCollection services)              {              render              // CORS              services.AddCors(options => {                  options.AddPolicy("CorsPolicy",                         builder => {                             builder.WithOrigins(AppSettings.CORS)                                 .AllowAnyMethod()                                 .AllowAnyHeader()                                 .AllowCredentials();                         });                 });         }     } }                                      Lawmaking language:              C#              (              cs              )                      

Open your AppSettings.cs grade in the Domain layer, and so update the following codes.

ApplicationTier.Domain/Models/AppSettings.cs

                          namespace              ApplicationTier.Domain.Models              {              public              class              AppSettings              {              public              static              string              ConnectionString {              get;              private              ready; }              public              static              string[] CORS {              get;              private              set; }     } }                                      Code linguistic communication:              C#              (              cs              )                      

Update some values to your appsettings.json file.

ApplicationTier.API/appsettings.js

  • ConnectionString: the connectedness string to the database on Data-tier.
  • CORS: the domain list of applications that you let access to the application.
                          {              "Logging": {              "LogLevel": {              "Default":              "Data",              "Microsoft":              "Warning",              "Microsoft.Hosting.Lifetime":              "Information"              }   },              "AppSettings": {              "ConnectionString":              "Data Source=(local);Initial Catalog=DataTier.SqlServer;Persist Security Info=True;User ID=sa;Password=Countersign;MultipleActiveResultSets=Truthful",              "CORS": [              "http://localhost:4200"              ]   },              "AllowedHosts":              "*"              }                                      Code language:              C#              (              cs              )                      

Open the Startup.cs file, then add together the following codes.

ApplicationTier.API/StartUp.cs

  • StartUp(constructor): read data from appsettings.json, then store it in the AppSettings class.
  • ConfigureServices: register instances for DataContext, its Factory, UnitOfWork, WorkService, and CORS policy to the awarding (using extension methods in the ServiceCollectionExtensions class).
                          using              Microsoft.AspNetCore.Builder;              using              Microsoft.AspNetCore.Hosting;              using              Microsoft.Extensions.Configuration;              using              Microsoft.Extensions.DependencyInjection;              using              Microsoft.Extensions.Hosting;              using              Microsoft.OpenApi.Models;              using              System;              using              ApplicationTier.API.Extensions;              using              ApplicationTier.Domain.Models;              namespace              ApplicationTier.API              {              public              class              Startup              {                              public                Startup(IWebHostEnvironment env)              {             Configuration = InitConfiguration(env);         }              public              IConfiguration Configuration {              get; }              // This method gets called past the runtime. Use this method to add services to the container.                              public                void                ConfigureServices(IServiceCollection services)              {             services                 .AddDatabase()                 .AddServices()                 .AddCORS();               services.AddControllers();             services.AddSwaggerGen(c =>             {                 c.SwaggerDoc("v1",              new              OpenApiInfo { Title =              "ApplicationTier.API", Version =              "v1"              });             });         }              // This method gets called by the runtime. Use this method to configure the HTTP asking pipeline.                              public                void                Configure(IApplicationBuilder app, IWebHostEnvironment env)              {              if              (env.IsDevelopment())             {                 app.UseDeveloperExceptionPage();              // Move swagger out of this if block if employ want to utilize it on production              app.UseSwagger();                 app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json",              "ApplicationTier.API v1"));             }              // Auto redirect to https              //app.UseHttpsRedirection();              // Allow external access;              app.UseCors("CorsPolicy");             app.UseRouting();               app.UseAuthorization();               app.UseEndpoints(endpoints =>             {                 endpoints.MapControllers();             });         }                              private                IConfiguration                InitConfiguration(IWebHostEnvironment env)              {              // Config the app to read values from appsettings base on current environment value.              var              configuration =              new              ConfigurationBuilder()                 .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)                 .AddJsonFile("appsettings.json",              false,              true)                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json",              truthful,              true)                 .AddEnvironmentVariables().Build();              //              // Map AppSettings section in appsettings.json file value to AppSetting model              configuration.GetSection("AppSettings").Get(options => options.BindNonPublicProperties =              truthful);              return              configuration;         }     } }                                      Code language:              C#              (              cs              )                      

Create a WorkController, add the following code to inject the interface of WorkService into the controller, and so use information technology to implement some basic APIs.

ApplicationTier.API/Controllers/WorkController.cs

                          using              System.Collections.Generic;              using              Organization.Threading.Tasks;              using              ApplicationTier.Domain.Entities;              using              ApplicationTier.Domain.Interfaces.Services;              using              Microsoft.AspNetCore.Mvc;              namespace              ApplicationTier.API.Controllers              {     [Route("api/[controller]")]     [ApiController]              public              class              WorkController              :              ControllerBase              {              individual              readonly              IWorkService _workService;                              public                WorkController(IWorkService workService)              {             _workService = workService;         }              #region                CRUD              [HttpGet]                              public                async                Task<IList>                GetAll()              {              return              wait              _workService.GetAll();         }           [HttpPut]                              public                async                Job                Update(Work piece of work)              {              await              _workService.Update(work);         }           [HttpGet("{id:int}")]                              public                async                Task                GetOne([FromRoute]                  int                  id)              {              return              await              _workService.GetOne(id);         }           [HttpPost]                              public                async                Task                Add together(Work piece of work)              {              await              _workService.Add(piece of work);         }           [HttpDelete("{id}")]                              public                async                Task                Delete([FromRoute]                  int                  id)              {              await              _workService.Delete(id);         }              #endregion                            } }                                      Code language:              C#              (              cs              )                      

Testing
Run your application to test the API via Swagger UI (already integrated when creating ASP.NET Cadre API app).

Testing API

Or by a specific API endpoint.

3-tier application

Deployment
In the machine where you want to store the Application tier creates a folder to store the source lawmaking.

Notes: Brand sure this motorcar has installed .NET 5 Packet.

Application tier 1

On the same machine, open your IIS to create a website every bit below.

Application tier 2

Open your solution in your Visual Studio, then follow these steps:

Correct-click on ApplicationTier.API, select Publish.

Application tier API publish

Select "Folder".

Application 4 publish

Enter "Binder location" following the path of the created source lawmaking binder.

Publish

Click to publish the project.

Publish the project

Testing
Notes:  Please exam on a specific URL with the suffix "api/work" equally the app in this case has been configured for this road only.

Application tier API

Presentation tier with Angular

Create an Angular application
Open your UI folder, then run this command to create a new Angular project. "enlab-software" is the project'south name; you can name whatever you want.

Angular

Afterward creating, some files should be added to your project every bit below, or y'all can download a hero sample via the Angular portal. Then extract the file to your UI binder.

Next, motility cmd to the created project folder and install all UI packages by running " npm install " control. Please ensure you lot have installed Node.js before running this command.
Wait until all packages have been installed; you lot can see the following illustration.

Enlab software

Next, run "npm showtime" to launch the project.

Enlab software 3-tier application

Open your browser on http://localhost:4200 ; the result is shown beneath.

Enlab software demo

Modify the application
Now open up your editor to modify the app (I am using Webstorm).

src/environments/environment.ts (localhost)
src/environments/surroundings.prod.ts (production)

Fix URL of the deployed Application tier to baseUrl value.

Modify the application

src/app/app.component.ts

                          import {Component}              from              '@angular/core'; import {HttpClient}              from              '@angular/common/http'; import {surroundings}              from              '../environments/environment';   @Component({   selector:              'app-root',   templateUrl:              './app.component.html',   styleUrls: ['./app.component.scss'] }) export              grade              AppComponent              {   title =              'Enlab Sofware Demo';   works: any;     constructor(individual              httpClient: HttpClient) {              this.httpClient.get(`${environs.baseUrl}/api/piece of work`)     .subscribe(works => {              this.works = works;     });   } }                                      Lawmaking language:              C#              (              cs              )                      

src/app/app.component.html

                          <!--The content below              is              simply a placeholder and can exist replaced.--></code></pre> <div mode="text-align: center"> <h2>Welcome to <a href="https://enlabsoftware.com"              target="_blank"              rel="noopener">{{ title }}!</a></h2> </div> <pre              class="wp-cake-code"><code></code></pre> <table> <tbody> <tr> <th manner="width: 50px;text-marshal: left">Id</th> <th manner="width: 100px;text-align: left">Proper name</th> </tr> <tr> <td>{{work.id}}</td> <td>{{work.name}}</td> </tr> </tbody> </table> <pre              class="wp-cake-code"><code>                                      Code language:              C#              (              cs              )                      

Testing
Save all codes, then double-check your page on the browser.

Enlab software demo 1

Deployment

Publish the site

Deployment 2

On the same machine, open IIS, then create a site to host the UI app. In this demo, I created the site on the aforementioned machine every bit the Application machine. Despite the separation of this tier, you can deploy it to any machine you desire. I set the port to 1234.

Presentation tier Angular

Open your cmd at the Angular project folder, then run " npm run build".

Angular project

Afterward, open the "dist" folder inside the angular project, copy all files, and paste information technology to the AngularUI site's source binder in IIS.

AngularUI site

Then reload the UI site. Oops. Something went wrong!

Config CORS policy

Enlab demo

This happened considering nosotros have not told you about the Awarding tier that it should accept requests from the Presentation tier. To solve this problem, please follow these steps:

Open the appsettings.json file in the source lawmaking folder of the Application tier, then add together the domain URL of the Presentation tier to the CORS parameter.

Presentation tier to CORS parameter

On the Application machine, open up IIS and restart the Application site.

Application tier API 1

Finally, reload the Presentation site on the browser. The site works now.

Enlab demo 2

Decision

The three-tier architecture is a well-designed architecture widely used in the software industry considering of its scalability, reliability, and high security. It is suitable for building large applications, which handle heavy business logic, require high-load, high security, and availability, such as e-commerce websites, SaaS (Software-every bit-a-Service), online payment gateway, etc.

Well, that is all I want to share about three-tier architecture. Hopefully, it is helpful to you lot if y'all are going to beginning building a three-tier architecture application.

Cheers for reading, and happy coding!

CTA Enlab Software

References

  • IBM Deject Education, What is Iii-Tier Compages, world wide web.ibm.com, 2020.
  • Scott Hanselman, A reminder on "Three/Multi-Tier/Layer Architecture/Design" brought to you by my late nighttime frustrations, world wide web.hanselman.com, 2004.
  • Multitier architecture, www.en.wikipedia.org.

valentinodiany1971.blogspot.com

Source: https://enlabsoftware.com/development/how-to-build-and-deploy-a-three-tier-architecture-application-with-c-sharp.html

0 Response to "A Three Tier Architecture Project to Read and Write From a Json or Xml Using C#"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel