How To Add Dal File In Windows Form Application
Introduction
In this article, I will discuss the complete procedure of crud operation in Asp.Cyberspace Core five Web API projection. Nosotros will send the complete JSON object to the POST endpoint and then we will update the data in the database using PUT Endpoint. Basically, in this project we will perform the consummate Crud operation using Asp.Net 5 Architecture. We volition perform the following operation like POST PUT DELETE GET operations. POST Method is used for sending the JSON Data to database PUT Method is used to update the Data in Database DELETE Method is used to delete the information from the database either based on Id OR Compete Data from Database Go Method is used for Getting all the record from the database either on the bases of Id or All Data in the form of JSON objects. I will apply the repository pattern in this project CRUDAspNetCore5Web API
Resources can be downloaded from Article Resource Department.
Projection Setup
Add together Asp.Cyberspace Core five Projection
Outset the Asp.Internet Core project using the Visual Studio in Asp.cyberspace Core with the latest version .Net Core Version 5.
Add together DAL_CRUD Asp.cyberspace Core Course Library
Add the .Net class Library for DAL (Data Access Layer) in Information Access Layer we will connect our ORM With Database and we will define some methods for doing our all logic in the business access layer.
Add together BAL_CRUD Asp.net Cadre Course Library
Add the .Internet class Library for DAL (Business Access Layer). In the Business organisation Access layer, we will use the basic structure of our ORM that is already defined in the information admission layer. In our business organisation admission layer, we volition perform our all logic about our Grime Operations similar Mail GET PUT AND Delete.
Information Admission Layer
In the Data Admission layer we will perform the following steps,
Application Db Context
First, add the connection string in the awarding Setting.JSON file and so connect the connection cord with Application Db Class and then call the string connection in Startup. cs class for establishing the connexion with the database.
- using CRUD_DAL.Models;
- using Microsoft.EntityFrameworkCore;
- using System;
- using Organization.Collections.Generic;
- using System.Text;
- namespace CRUD_DAL.Information
- {
- public grade ApplicationDbContext : DbContext
- {
- public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
- {
- }
- protected override void OnModelCreating(ModelBuilder builder)
- {
- base.OnModelCreating(builder);
- }
- public DbSet<Person> Persons { get; set; }
- }
- }
Application Setting.JSON file
- {
- "Logging" : {
- "LogLevel" : {
- "Default" : "Data" ,
- "Microsoft" : "Warning" ,
- "Microsoft.Hosting.Lifetime" : "Information"
- }
- },
- "AllowedHosts" : "*" ,
- "ConnectionStrings" : {
- "DefaultConnection" : "Server=SARDARMUDASSARA\\SQLEXPRESS;Database=CRUDAspNetCore5WebAPI;Trusted_Connection=True"
- }
- }
Start-Up File
- using CRUD_BAL.Service;
- using CRUD_DAL.Information;
- using CRUD_DAL.Interface;
- using CRUD_DAL.Models;
- using CRUD_DAL.Repository;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.HttpsPolicy;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using Microsoft.OpenApi.Models;
- using Organisation;
- using System.Collections.Generic;
- using Arrangement.Linq;
- using Organization.Threading.Tasks;
- namespace CRUDAspNetCore5WebAPI
- {
- public form Startup
- {
- private readonly IConfiguration _configuration;
- public Startup(IConfiguration configuration)
- {
- _configuration = configuration;
- }
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection" )));
- services.AddControllers();
- services.AddHttpClient();
- services.AddTransient<IRepository<Person>, RepositoryPerson>();
- services.AddTransient<PersonService, PersonService>();
- services.AddControllers();
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1" , new OpenApiInfo { Title = "CRUDAspNetCore5WebAPI" , Version = "v1" });
- });
- }
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- app.UseSwagger();
- app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json" , "CRUDAspNetCore5WebAPI v1" ));
- }
- app.UseHttpsRedirection();
- app.UseRouting();
- app.UseAuthorization();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }
- }
Application Db Context Grade
- using CRUD_DAL.Models;
- using Microsoft.EntityFrameworkCore;
- using System;
- using System.Collections.Generic;
- using Organisation.Text;
- namespace CRUD_DAL.Data
- {
- public class ApplicationDbContext : DbContext
- {
- public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base (options)
- {
- }
- protected override void OnModelCreating(ModelBuilder builder)
- {
- base .OnModelCreating(builder);
- }
- public DbSet<Person> Persons { go ; set ; }
- }
- }
Model
Add the model grade in which define the entity for the database and his attributes like Id Name, and Person Telephone No.
- using Arrangement;
- using System.Collections.Generic;
- using Organization.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Text;
- namespace CRUD_DAL.Models
- {
- [Tabular array("Persons" , Schema = "dbo" )]
- public class Person
- {
- [Cardinal]
- [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- public int Id { become ; set ; }
- [Required]
- [Display(Name ="UserName" )]
- public cord UserName { go ; set ; }
- [Required]
- [Brandish(Proper name ="UserPassword" )]
- public string UserPassword { become ; set ; }
- [Required]
- [Display(Proper noun ="UserEmail" )]
- public string UserEmail { go ; set ; }
- [Required]
- [Display(Proper name ="CreatedOn" )]
- public DateTime CreatedOn { get ; set ; } = DateTime.Now;
- [Required]
- [Display(Name ="IsDeleted" )]
- public bool IsDeleted { go ; set ; } = false ;
- }
- }
Migration
Now Add the migration for the cosmos of the database and afterwards adding migration Update the database. Select the DAL projection for the migration of Data
Interface
Add together the interface binder and then add the Interface in the information admission layer In Interface and Define the Methods that you want to perform in the repository blueprint.
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading.Tasks;
- namespace CRUD_DAL.Interface
- {
- public interface IRepository<T>
- {
- public Task<T> Create(T _object);
- public void Update(T _object);
- public IEnumerable<T> GetAll();
- public T GetById( int Id);
- public void Delete(T _object);
- }
- }
Repository
Add the Repository Person Class Which Implements the Interface and performs the office defined in the interface like getting All Data, Delete All Data Update Information, Update data past userId similar this.
- using CRUD_DAL.Data;
- using CRUD_DAL.Interface;
- using CRUD_DAL.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using Arrangement.Text;
- using Organisation.Threading.Tasks;
- namespace CRUD_DAL.Repository
- {
- public class RepositoryPerson : IRepository<Person>
- {
- ApplicationDbContext _dbContext;
- public RepositoryPerson(ApplicationDbContext applicationDbContext)
- {
- _dbContext = applicationDbContext;
- }
- public async Chore<Person> Create(Person _object)
- {
- var obj = await _dbContext.Persons.AddAsync(_object);
- _dbContext.SaveChanges();
- return obj.Entity;
- }
- public void Delete(Person _object)
- {
- _dbContext.Remove(_object);
- _dbContext.SaveChanges();
- }
- public IEnumerable<Person> GetAll()
- {
- endeavour
- {
- return _dbContext.Persons.Where(x => 10.IsDeleted == faux ).ToList();
- }
- take hold of (Exception ee)
- {
- throw ;
- }
- }
- public Person GetById( int Id)
- {
- return _dbContext.Persons.Where(x => x.IsDeleted == false && x.Id == Id).FirstOrDefault();
- }
- public void Update(Person _object)
- {
- _dbContext.Persons.Update(_object);
- _dbContext.SaveChanges();
- }
- }
- }
Business concern Access Layer
Add Project Reference of Data Access Layer
Before Staring the Work on Person Service Class Kickoff Add the Reference of Data Access grade library project in the Business access layer.
Person Service
In-Person Service We will apply the Data Admission Class Library in which we have already defined the Methods similar Update Data Delete Data etc. But in business access, we will write all the business organization logic like getting all the data with a specific Id, update the complete object using userId, Soft Deletion of data.
Add together the service folder in the business access layer then add the person service grade.
- using CRUD_DAL.Interface;
- using CRUD_DAL.Models;
- using System;
- using Organization.Collections.Generic;
- using System.Linq;
- using Organisation.Text;
- using Arrangement.Threading.Tasks;
- namespace CRUD_BAL.Service
- {
- public class PersonService
- {
- private readonly IRepository<Person> _person;
- public PersonService(IRepository<Person> perosn)
- {
- _person = perosn;
- }
- public IEnumerable<Person> GetPersonByUserId( cord UserId)
- {
- return _person.GetAll().Where(ten => ten.UserEmail == UserId).ToList();
- }
- public IEnumerable<Person> GetAllPersons()
- {
- try
- {
- return _person.GetAll().ToList();
- }
- catch (Exception)
- {
- throw ;
- }
- }
- public Person GetPersonByUserName( string UserName)
- {
- return _person.GetAll().Where(x => x.UserEmail == UserName).FirstOrDefault();
- }
- public async Task<Person> AddPerson(Person Person)
- {
- return await _person.Create(Person);
- }
- public bool DeletePerson( string UserEmail)
- {
- try
- {
- var DataList = _person.GetAll().Where(10 => x.UserEmail == UserEmail).ToList();
- foreach (var detail in DataList)
- {
- _person.Delete(item);
- }
- return true ;
- }
- catch (Exception)
- {
- return true ;
- }
- }
- public bool UpdatePerson(Person person)
- {
- try
- {
- var DataList = _person.GetAll().Where(ten => x.IsDeleted !=true ).ToList();
- foreach (var item in DataList)
- {
- _person.Update(item);
- }
- return truthful ;
- }
- catch (Exception)
- {
- render true ;
- }
- }
- }
- }
API in Asp.Internet Core five Web API
Add together Project Reference of Business concern Access Layer
Before Staring in API Controllers commencement add together the business access layer BAL Class library project reference in API Project.
Add the Transient in Startup Class
Modify the startup class like add the transient in the Startup class for adding the dependency injection transient services created whenever they are injected or requested.
- using CRUD_BAL.Service;
- using CRUD_DAL.Data;
- using CRUD_DAL.Interface;
- using CRUD_DAL.Models;
- using CRUD_DAL.Repository;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.HttpsPolicy;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using Microsoft.OpenApi.Models;
- using System;
- using Arrangement.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- namespace CRUDAspNetCore5WebAPI
- {
- public class Startup
- {
- private readonly IConfiguration _configuration;
- public Startup(IConfiguration configuration)
- {
- _configuration = configuration;
- }
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection" )));
- services.AddControllers();
- services.AddHttpClient();
- services.AddTransient<IRepository<Person>, RepositoryPerson>();
- services.AddTransient<PersonService, PersonService>();
- services.AddControllers();
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1" , new OpenApiInfo { Title = "CRUDAspNetCore5WebAPI" , Version = "v1" });
- });
- }
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- app.UseSwagger();
- app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json" , "CRUDAspNetCore5WebAPI v1" ));
- }
- app.UseHttpsRedirection();
- app.UseRouting();
- app.UseAuthorization();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }
- }
API Controller
In API Controller We will Ascertain Our GET PUT POST AND DELETE Endpoints for achieving our CRUD operation Goals.
- using CRUD_BAL.Service;
- using CRUD_DAL.Interface;
- using CRUD_DAL.Models;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Newtonsoft.Json;
- using Organisation;
- using System.Collections.Generic;
- using System.Linq;
- using Organization.Threading.Tasks;
- namespace CRUDAspNetCore5WebAPI.Controllers
- {
- [Route("api/[controller]" )]
- [ApiController]
- public form PersonDetailsController : ControllerBase
- {
- private readonly PersonService _personService;
- private readonly IRepository<Person> _Person;
- public PersonDetailsController(IRepository<Person> Person, PersonService ProductService)
- {
- _personService = ProductService;
- _Person = Person;
- }
- [HttpPost("AddPerson" )]
- public async Task<Object> AddPerson([FromBody] Person person)
- {
- try
- {
- await _personService.AddPerson(person);
- return true ;
- }
- take hold of (Exception)
- {
- render faux ;
- }
- }
- [HttpDelete("DeletePerson" )]
- public bool DeletePerson( string UserEmail)
- {
- try
- {
- _personService.DeletePerson(UserEmail);
- return true ;
- }
- catch (Exception)
- {
- return fake ;
- }
- }
- [HttpPut("UpdatePerson" )]
- public bool UpdatePerson(Person Object)
- {
- try
- {
- _personService.UpdatePerson(Object);
- return truthful ;
- }
- catch (Exception)
- {
- render false ;
- }
- }
- [HttpGet("GetAllPersonByName" )]
- public Object GetAllPersonByName( string UserEmail)
- {
- var data = _personService.GetPersonByUserName(UserEmail);
- var json = JsonConvert.SerializeObject(data, Formatting.Indented,
- new JsonSerializerSettings()
- {
- ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
- }
- );
- render json;
- }
- [HttpGet("GetAllPersons" )]
- public Object GetAllPersons()
- {
- var information = _personService.GetAllPersons();
- var json = JsonConvert.SerializeObject(data, Formatting.Indented,
- new JsonSerializerSettings()
- {
- ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
- }
- );
- return json;
- }
- }
- }
TESTING THE API
for Testing of API, I will Discuss the consummate procedure in a separate commodity
Project Resource Guideline
- First, download the given Project from my GitHub repository / from article resource.
- Open the project using visual studio
- Go to parcel managing director panel
- Add the migration
- Update the database
- Run the project
- Enjoy the beauty of web service API with swagger UI
"Happy API Evolution"
Determination
As a software engineer, my opinion about RESTful web services is that it is a lightweight, maintainable, and scalable service that is built on the Rest architecture. RESTful compages provides us the best manner to develop cross platforms applications using the Asp.net Core Web API. I suggest all the online communities that develop your Web application using RESTfull Spider web compages and follow the best practices of coding for high efficiency of the application.
How To Add Dal File In Windows Form Application,
Source: https://www.c-sharpcorner.com/article/crud-operation-in-asp-net-core-5-web-api/
Posted by: bastarachemeself.blogspot.com
0 Response to "How To Add Dal File In Windows Form Application"
Post a Comment