• Register
262 points
‚óŹ3

What is 3-tier architecture

Three-tier architecture could also be a well-established software application architecture that organizes applications into three logical and physical computing tiers: the presentation tier, or user interface; the appliance tier, where data is processed; and therefore the data tier, where the info related to the appliance is stored and managed.

The 3-tiers in details

  • Presentation tier: The presentation tier is that the interface and communication layer of the appliance, where the top user interacts with the appliance. Its main purpose is to display information to and collect information from the user. This top-level tier can run on an internet browser, as desktop application, or a graphical interface (GUI), for instance. Web presentation tiers are usually developed using HTML, CSS and JavaScript. Desktop applications are often written during a sort of languages counting on the platform. Also WPF and C# Windows Forms Application are considered as presentation layer.
  • Application tier: The application tier, also referred to as the logic tier or middle tier, is that the heart of the appliance. during this tier, information collected within the presentation tier is processed - sometimes against other information within the data tier - using business logic, a selected set of business rules. the appliance tier also can add, delete or modify data within the data tier. The application tier is usually developed using C#, Python, Java, Perl, PHP or Ruby, and communicates with the info tier using API calls.
  • Data tier: The data tier, sometimes called database tier, data access tier or back-end, is where the knowledge processed by the appliance is stored and managed. this will be a electronic database management system like PostgreSQL, MySQL, MariaDB, Oracle, DB2, Informix or Microsoft SQL Server, or during a NoSQL Database server like Cassandra, CouchDB or MongoDB.

In a three-tier application, all communication goes through the appliance tier. The presentation tier and therefore the data tier cannot communicate directly with each other.

3-tier architecture in c# windows application

Firstly we have to design Data tier. To do this:

  • Create a .NET Core Class Library project.
    mkdir DataTier
    cd DataTier
    dotnet new classlib
     
  • Add a domian model.
    using System;
    
    namespace DataTier
    {
        public class Student
        {
            public Guid Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public int RegNo { get; set; }
        }
    }
    

     

  • Add a DbContext Class, Use Entity Framework Core to migrate your application with MS SQL server. Provide a default database connection string in context option builder while you override OnConfiguring() method.

    using Microsoft.EntityFrameworkCore;
    
    namespace DataTier.DbOperation
    {
        public partial class StudentDbContext : DbContext
        {
            public StudentDbContext()
            {
            }
    
            public StudentDbContext(DbContextOptions<StudentDbContext> options)
                : base(options)
            {
            }
    
            public virtual DbSet<Student> Students { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                if (!optionsBuilder.IsConfigured)
                {
                   optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=StudentDB;Integrated Security=True;");
                }
            }
    
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");
    
                modelBuilder.Entity<Student>(entity =>
                {
                    entity.Property(e => e.Id).ValueGeneratedNever();
                });
    
                OnModelCreatingPartial(modelBuilder);
            }
    
            partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
        }
    }
    

Then we have to design a Application -Tier to perform business logics i.e.: Implementation of API Endpoints for CURD operation. To do this:

  • Create a ASP.NET Core WebAPI
    cd ..
    mkdir WebApi
    cd WebApi
    dotnet new webapp

     

  • Add Previously created project to your ASP.NET Core project referance (inside the .csproj file)
      <ItemGroup>
        <ProjectReference Include="..\DataAccess\DataAccess.csproj" />
      </ItemGroup>

     

  • Add DbContext in service registry of your startup file
    public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<StudentDbContext>();
                services.AddControllers();
                ...
            }

    You have to install Entity Framework Core design tools to update database. You can also configure sql server connection here.

  • Create an api controller for Student Domain
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using DataTier;
    using DataTier.DbOperation;
    using Microsoft.EntityFrameworkCore;
    
    namespace ApplicationTier.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class StudentsController : ControllerBase
        {
            private readonly StudentDbContext _context;
    
            public StudentsController(StudentDbContext context)
            {
                _context = context;
            }
    
            // GET: api/Students
            [HttpGet]
            public async Task<ActionResult<IEnumerable<Student>>> GetStudents()
            {
                return await _context.Students.ToListAsync();
            }
    
            // GET: api/Students/5
            [HttpGet("{id}")]
            public async Task<ActionResult<Student>> GetStudent(Guid id)
            {
                var student = await _context.Students.FindAsync(id);
    
                if (student == null)
                {
                    return NotFound();
                }
    
                return student;
            }
    
            // PUT: api/Students/5
            // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
            [HttpPut("{id}")]
            public async Task<IActionResult> PutStudent(Guid id, Student student)
            {
                if (id != student.Id)
                {
                    return BadRequest();
                }
    
                _context.Entry(student).State = EntityState.Modified;
    
                try
                {
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!StudentExists(id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
    
                return NoContent();
            }
    
            // POST: api/Students
            // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
            [HttpPost]
            public async Task<ActionResult<Student>> PostStudent(Student student)
            {
                _context.Students.Add(student);
                await _context.SaveChangesAsync();
    
                return CreatedAtAction(nameof(GetStudent), new { id = student.Id }, student);
            }
    
            // DELETE: api/Students/5
            [HttpDelete("{id}")]
            public async Task<IActionResult> DeleteStudent(Guid id)
            {
                var student = await _context.Students.FindAsync(id);
                if (student == null)
                {
                    return NotFound();
                }
    
                _context.Students.Remove(student);
                await _context.SaveChangesAsync();
    
                return NoContent();
            }
    
            private bool StudentExists(Guid id)
            {
                return _context.Students.Any(e => e.Id == id);
            }
    
        }
    }
    

     

  • Build and run your application in out of process hosting mode.
    dotnet restore
    dotnet build
    dotnet run

    Usually it has run on port 5000

Next: Please follow the Part B of this article