F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\MappingConfig.cs
| using AutoMapper; |
| using MagicVilla_VillaAPI.Models; |
| using MagicVilla_VillaAPI.Models.Dto; |
| |
| namespace MagicVilla_VillaAPI |
| { |
| public class MappingConfig : Profile |
| { |
| public MappingConfig() |
| { |
| CreateMap<Villa, VillaDTO>(); |
| CreateMap<VillaDTO, Villa>(); |
| |
| CreateMap<Villa, VillaCreateDTO>().ReverseMap(); |
| CreateMap<Villa, VillaUpdateDTO>().ReverseMap(); |
| |
| |
| CreateMap<VillaNumber, VillaNumberDTO>().ReverseMap(); |
| CreateMap<VillaNumber, VillaNumberCreateDTO>().ReverseMap(); |
| CreateMap<VillaNumber, VillaNumberUpdateDTO>().ReverseMap(); |
| CreateMap<ApplicationUser, UserDTO>().ReverseMap(); |
| } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Program.cs
| using MagicVilla_VillaAPI; |
| using MagicVilla_VillaAPI.Data; |
| using MagicVilla_VillaAPI.Repository.IRepostiory; |
| using MagicVilla_VillaAPI.Repository; |
| using Microsoft.EntityFrameworkCore; |
| using Microsoft.OpenApi.Models; |
| using Microsoft.AspNetCore.Mvc; |
| |
| var builder = WebApplication.CreateBuilder(args); |
| |
| |
| var configuration = builder.Configuration.GetConnectionString("DefaultSQLConnection"); |
| builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(configuration, ServerVersion.AutoDetect(configuration))); |
| builder.Services.AddResponseCaching(); |
| builder.Services.AddScoped<IVillaRepository, VillaRepository>(); |
| builder.Services.AddScoped<IVillaNumberRepository, VillaNumberRepository>(); |
| builder.Services.AddAutoMapper(typeof(MappingConfig)); |
| |
| |
| builder.Services.AddApiVersioning(options => |
| { |
| options.AssumeDefaultVersionWhenUnspecified = true; |
| options.DefaultApiVersion = new ApiVersion(1, 0); |
| options.ReportApiVersions = true; |
| }); |
| |
| builder.Services.AddVersionedApiExplorer(options => |
| { |
| options.GroupNameFormat = "'v'VVV"; |
| options.SubstituteApiVersionInUrl = true; |
| }); |
| |
| builder.Services.AddControllers(option => |
| { |
| option.CacheProfiles.Add("Default30", |
| new CacheProfile() |
| { |
| Duration = 30 |
| }); |
| |
| }).AddNewtonsoftJson().AddXmlDataContractSerializerFormatters(); |
| |
| |
| builder.Services.AddEndpointsApiExplorer(); |
| |
| |
| builder.Services.AddSwaggerGen(options => |
| { |
| options.SwaggerDoc("v1", new OpenApiInfo |
| { |
| Version = "v1.0", |
| Title = "Magic Villa V1", |
| Description = "API to manage Villa V1", |
| }); |
| |
| |
| options.SwaggerDoc("v2", new OpenApiInfo |
| { |
| Version = "v2.0", |
| Title = "Magic Villa V2", |
| Description = "API to manage Villa V2", |
| }); |
| }); |
| |
| |
| var app = builder.Build(); |
| |
| if (app.Environment.IsDevelopment()) |
| { |
| app.UseSwagger(); |
| app.UseSwaggerUI(options => |
| { |
| options.SwaggerEndpoint("/swagger/v1/swagger.json", "Magic_VillaV1"); |
| options.SwaggerEndpoint("/swagger/v2/swagger.json", "Magic_VillaV2"); |
| }); |
| } |
| |
| app.UseHttpsRedirection(); |
| app.MapControllers(); |
| |
| |
| app.Run(); |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Controllers\v1\VillaAPIController.cs
| using AutoMapper; |
| using MagicVilla_VillaAPI.Data; |
| using MagicVilla_VillaAPI.Models; |
| using MagicVilla_VillaAPI.Models.Dto; |
| using MagicVilla_VillaAPI.Repository.IRepostiory; |
| using Microsoft.AspNetCore.Authorization; |
| using Microsoft.AspNetCore.Http.HttpResults; |
| using Microsoft.AspNetCore.JsonPatch; |
| using Microsoft.AspNetCore.Mvc; |
| using Microsoft.EntityFrameworkCore; |
| using System.Net; |
| using System.Text.Json; |
| |
| namespace MagicVilla_VillaAPI.Controllers.v1 |
| { |
| [Route("api/v{version:apiVersion}/VillaAPI")] |
| [ApiController] |
| [ApiVersion("1.0")] |
| public class VillaAPIController : ControllerBase |
| { |
| protected APIResponse _response; |
| private readonly IVillaRepository _dbVilla; |
| private readonly IMapper _mapper; |
| public VillaAPIController(IVillaRepository dbVilla, IMapper mapper) |
| { |
| _dbVilla = dbVilla; |
| _mapper = mapper; |
| _response = new(); |
| } |
| |
| |
| [HttpGet] |
| [ResponseCache(CacheProfileName = "Default30")] |
| [ProducesResponseType(StatusCodes.Status403Forbidden)] |
| [ProducesResponseType(StatusCodes.Status401Unauthorized)] |
| [ProducesResponseType(StatusCodes.Status200OK)] |
| public async Task<ActionResult<APIResponse>> GetVillas([FromQuery(Name = "filterOccupancy")] int? occupancy, |
| [FromQuery] string? search, int pageSize = 0, int pageNumber = 1) |
| { |
| try |
| { |
| |
| IEnumerable<Villa> villaList; |
| |
| if (occupancy > 0) |
| { |
| villaList = await _dbVilla.GetAllAsync(u => u.Occupancy == occupancy, pageSize: pageSize, |
| pageNumber: pageNumber); |
| } |
| else |
| { |
| villaList = await _dbVilla.GetAllAsync(pageSize: pageSize, |
| pageNumber: pageNumber); |
| } |
| if (!string.IsNullOrEmpty(search)) |
| { |
| villaList = villaList.Where(u => u.Name.ToLower().Contains(search)); |
| } |
| Pagination pagination = new() { PageNumber = pageNumber, PageSize = pageSize }; |
| Response.Headers.Add("X-Pagination", JsonSerializer.Serialize(pagination)); |
| |
| _response.Result = _mapper.Map<List<VillaDTO>>(villaList); |
| _response.StatusCode = HttpStatusCode.OK; |
| return Ok(_response); |
| |
| } |
| catch (Exception ex) |
| { |
| _response.IsSuccess = false; |
| _response.ErrorMessages |
| = new List<string>() { ex.ToString() }; |
| } |
| return _response; |
| |
| } |
| |
| [HttpGet("{id:int}", Name = "GetVilla")] |
| [ProducesResponseType(StatusCodes.Status403Forbidden)] |
| [ProducesResponseType(StatusCodes.Status401Unauthorized)] |
| [ProducesResponseType(StatusCodes.Status200OK)] |
| [ProducesResponseType(StatusCodes.Status400BadRequest)] |
| [ProducesResponseType(StatusCodes.Status404NotFound)] |
| |
| |
| public async Task<ActionResult<APIResponse>> GetVilla(int id) |
| { |
| try |
| { |
| if (id == 0) |
| { |
| _response.StatusCode = HttpStatusCode.BadRequest; |
| return BadRequest(_response); |
| } |
| var villa = await _dbVilla.GetAsync(u => u.Id == id); |
| if (villa == null) |
| { |
| _response.StatusCode = HttpStatusCode.NotFound; |
| return NotFound(_response); |
| } |
| _response.Result = _mapper.Map<VillaDTO>(villa); |
| _response.StatusCode = HttpStatusCode.OK; |
| return Ok(_response); |
| } |
| catch (Exception ex) |
| { |
| _response.IsSuccess = false; |
| _response.ErrorMessages |
| = new List<string>() { ex.ToString() }; |
| } |
| return _response; |
| } |
| |
| [HttpPost] |
| [Authorize(Roles = "admin")] |
| [ProducesResponseType(StatusCodes.Status201Created)] |
| [ProducesResponseType(StatusCodes.Status400BadRequest)] |
| [ProducesResponseType(StatusCodes.Status500InternalServerError)] |
| public async Task<ActionResult<APIResponse>> CreateVilla([FromBody] VillaCreateDTO createDTO) |
| { |
| try |
| { |
| |
| |
| |
| |
| if (await _dbVilla.GetAsync(u => u.Name.ToLower() == createDTO.Name.ToLower()) != null) |
| { |
| ModelState.AddModelError("ErrorMessages", "Villa already Exists!"); |
| return BadRequest(ModelState); |
| } |
| |
| if (createDTO == null) |
| { |
| return BadRequest(createDTO); |
| } |
| |
| |
| |
| |
| Villa villa = _mapper.Map<Villa>(createDTO); |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| await _dbVilla.CreateAsync(villa); |
| _response.Result = _mapper.Map<VillaDTO>(villa); |
| _response.StatusCode = HttpStatusCode.Created; |
| return CreatedAtRoute("GetVilla", new { id = villa.Id }, _response); |
| } |
| catch (Exception ex) |
| { |
| _response.IsSuccess = false; |
| _response.ErrorMessages |
| = new List<string>() { ex.ToString() }; |
| } |
| return _response; |
| } |
| |
| [ProducesResponseType(StatusCodes.Status204NoContent)] |
| [ProducesResponseType(StatusCodes.Status403Forbidden)] |
| [ProducesResponseType(StatusCodes.Status401Unauthorized)] |
| [ProducesResponseType(StatusCodes.Status404NotFound)] |
| [ProducesResponseType(StatusCodes.Status400BadRequest)] |
| [HttpDelete("{id:int}", Name = "DeleteVilla")] |
| [Authorize(Roles = "admin")] |
| public async Task<ActionResult<APIResponse>> DeleteVilla(int id) |
| { |
| try |
| { |
| if (id == 0) |
| { |
| return BadRequest(); |
| } |
| var villa = await _dbVilla.GetAsync(u => u.Id == id); |
| if (villa == null) |
| { |
| return NotFound(); |
| } |
| await _dbVilla.RemoveAsync(villa); |
| _response.StatusCode = HttpStatusCode.NoContent; |
| _response.IsSuccess = true; |
| return Ok(_response); |
| } |
| catch (Exception ex) |
| { |
| _response.IsSuccess = false; |
| _response.ErrorMessages |
| = new List<string>() { ex.ToString() }; |
| } |
| return _response; |
| } |
| [Authorize(Roles = "admin")] |
| [HttpPut("{id:int}", Name = "UpdateVilla")] |
| [ProducesResponseType(StatusCodes.Status204NoContent)] |
| [ProducesResponseType(StatusCodes.Status400BadRequest)] |
| public async Task<ActionResult<APIResponse>> UpdateVilla(int id, [FromBody] VillaUpdateDTO updateDTO) |
| { |
| try |
| { |
| if (updateDTO == null || id != updateDTO.Id) |
| { |
| return BadRequest(); |
| } |
| |
| Villa model = _mapper.Map<Villa>(updateDTO); |
| |
| await _dbVilla.UpdateAsync(model); |
| _response.StatusCode = HttpStatusCode.NoContent; |
| _response.IsSuccess = true; |
| return Ok(_response); |
| } |
| catch (Exception ex) |
| { |
| _response.IsSuccess = false; |
| _response.ErrorMessages |
| = new List<string>() { ex.ToString() }; |
| } |
| return _response; |
| } |
| |
| [HttpPatch("{id:int}", Name = "UpdatePartialVilla")] |
| [ProducesResponseType(StatusCodes.Status204NoContent)] |
| [ProducesResponseType(StatusCodes.Status400BadRequest)] |
| public async Task<IActionResult> UpdatePartialVilla(int id, JsonPatchDocument<VillaUpdateDTO> patchDTO) |
| { |
| if (patchDTO == null || id == 0) |
| { |
| return BadRequest(); |
| } |
| var villa = await _dbVilla.GetAsync(u => u.Id == id, tracked: false); |
| |
| VillaUpdateDTO villaDTO = _mapper.Map<VillaUpdateDTO>(villa); |
| |
| |
| if (villa == null) |
| { |
| return BadRequest(); |
| } |
| patchDTO.ApplyTo(villaDTO, ModelState); |
| Villa model = _mapper.Map<Villa>(villaDTO); |
| |
| await _dbVilla.UpdateAsync(model); |
| |
| if (!ModelState.IsValid) |
| { |
| return BadRequest(ModelState); |
| } |
| return NoContent(); |
| } |
| |
| |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Controllers\v1\VillaNumberAPIController.cs
| using AutoMapper; |
| using MagicVilla_VillaAPI.Data; |
| using MagicVilla_VillaAPI.Models; |
| using MagicVilla_VillaAPI.Models.Dto; |
| using MagicVilla_VillaAPI.Repository.IRepostiory; |
| using Microsoft.AspNetCore.Authorization; |
| using Microsoft.AspNetCore.Http.HttpResults; |
| using Microsoft.AspNetCore.JsonPatch; |
| using Microsoft.AspNetCore.Mvc; |
| using Microsoft.EntityFrameworkCore; |
| using System.Data; |
| using System.Net; |
| |
| namespace MagicVilla_VillaAPI.Controllers.v1 |
| { |
| [Route("api/v{version:apiVersion}/VillaNumberAPI")] |
| [ApiController] |
| [ApiVersion("1.0")] |
| |
| public class VillaNumberAPIController : ControllerBase |
| { |
| protected APIResponse _response; |
| private readonly IVillaNumberRepository _dbVillaNumber; |
| private readonly IVillaRepository _dbVilla; |
| private readonly IMapper _mapper; |
| public VillaNumberAPIController(IVillaNumberRepository dbVillaNumber, IMapper mapper, |
| IVillaRepository dbVilla) |
| { |
| _dbVillaNumber = dbVillaNumber; |
| _mapper = mapper; |
| _response = new(); |
| _dbVilla = dbVilla; |
| } |
| |
| |
| [HttpGet("GetString")] |
| public IEnumerable<string> Get() |
| { |
| return new string[] { "String1", "string2" }; |
| } |
| |
| [HttpGet] |
| |
| [ProducesResponseType(StatusCodes.Status200OK)] |
| public async Task<ActionResult<APIResponse>> GetVillaNumbers() |
| { |
| try |
| { |
| |
| IEnumerable<VillaNumber> villaNumberList = await _dbVillaNumber.GetAllAsync(includeProperties: "Villa"); |
| _response.Result = _mapper.Map<List<VillaNumberDTO>>(villaNumberList); |
| _response.StatusCode = HttpStatusCode.OK; |
| return Ok(_response); |
| |
| } |
| catch (Exception ex) |
| { |
| _response.IsSuccess = false; |
| _response.ErrorMessages |
| = new List<string>() { ex.ToString() }; |
| } |
| return _response; |
| |
| } |
| |
| |
| [HttpGet("{id:int}", Name = "GetVillaNumber")] |
| [ProducesResponseType(StatusCodes.Status200OK)] |
| [ProducesResponseType(StatusCodes.Status400BadRequest)] |
| [ProducesResponseType(StatusCodes.Status404NotFound)] |
| public async Task<ActionResult<APIResponse>> GetVillaNumber(int id) |
| { |
| try |
| { |
| if (id == 0) |
| { |
| _response.StatusCode = HttpStatusCode.BadRequest; |
| return BadRequest(_response); |
| } |
| var villaNumber = await _dbVillaNumber.GetAsync(u => u.VillaNo == id); |
| if (villaNumber == null) |
| { |
| _response.StatusCode = HttpStatusCode.NotFound; |
| return NotFound(_response); |
| } |
| _response.Result = _mapper.Map<VillaNumberDTO>(villaNumber); |
| _response.StatusCode = HttpStatusCode.OK; |
| return Ok(_response); |
| } |
| catch (Exception ex) |
| { |
| _response.IsSuccess = false; |
| _response.ErrorMessages |
| = new List<string>() { ex.ToString() }; |
| } |
| return _response; |
| } |
| [Authorize(Roles = "admin")] |
| [HttpPost] |
| [ProducesResponseType(StatusCodes.Status201Created)] |
| [ProducesResponseType(StatusCodes.Status400BadRequest)] |
| [ProducesResponseType(StatusCodes.Status500InternalServerError)] |
| public async Task<ActionResult<APIResponse>> CreateVillaNumber([FromBody] VillaNumberCreateDTO createDTO) |
| { |
| try |
| { |
| |
| if (await _dbVillaNumber.GetAsync(u => u.VillaNo == createDTO.VillaNo) != null) |
| { |
| ModelState.AddModelError("ErrorMessages", "Villa Number already Exists!"); |
| return BadRequest(ModelState); |
| } |
| if (await _dbVilla.GetAsync(u => u.Id == createDTO.VillaID) == null) |
| { |
| ModelState.AddModelError("ErrorMessages", "Villa ID is Invalid!"); |
| return BadRequest(ModelState); |
| } |
| if (createDTO == null) |
| { |
| return BadRequest(createDTO); |
| } |
| |
| VillaNumber villaNumber = _mapper.Map<VillaNumber>(createDTO); |
| |
| |
| await _dbVillaNumber.CreateAsync(villaNumber); |
| _response.Result = _mapper.Map<VillaNumberDTO>(villaNumber); |
| _response.StatusCode = HttpStatusCode.Created; |
| return CreatedAtRoute("GetVilla", new { id = villaNumber.VillaNo }, _response); |
| } |
| catch (Exception ex) |
| { |
| _response.IsSuccess = false; |
| _response.ErrorMessages |
| = new List<string>() { ex.ToString() }; |
| } |
| return _response; |
| } |
| [Authorize(Roles = "admin")] |
| [ProducesResponseType(StatusCodes.Status200OK)] |
| [ProducesResponseType(StatusCodes.Status404NotFound)] |
| [ProducesResponseType(StatusCodes.Status400BadRequest)] |
| [HttpDelete("{id:int}", Name = "DeleteVillaNumber")] |
| public async Task<ActionResult<APIResponse>> DeleteVillaNumber(int id) |
| { |
| try |
| { |
| if (id == 0) |
| { |
| return BadRequest(); |
| } |
| var villaNumber = await _dbVillaNumber.GetAsync(u => u.VillaNo == id); |
| if (villaNumber == null) |
| { |
| return NotFound(); |
| } |
| await _dbVillaNumber.RemoveAsync(villaNumber); |
| _response.StatusCode = HttpStatusCode.NoContent; |
| _response.IsSuccess = true; |
| return Ok(_response); |
| } |
| catch (Exception ex) |
| { |
| _response.IsSuccess = false; |
| _response.ErrorMessages |
| = new List<string>() { ex.ToString() }; |
| } |
| return _response; |
| } |
| [Authorize(Roles = "admin")] |
| [HttpPut("{id:int}", Name = "UpdateVillaNumber")] |
| [ProducesResponseType(StatusCodes.Status200OK)] |
| [ProducesResponseType(StatusCodes.Status400BadRequest)] |
| public async Task<ActionResult<APIResponse>> UpdateVillaNumber(int id, [FromBody] VillaNumberUpdateDTO updateDTO) |
| { |
| try |
| { |
| if (updateDTO == null || id != updateDTO.VillaNo) |
| { |
| return BadRequest(); |
| } |
| if (await _dbVilla.GetAsync(u => u.Id == updateDTO.VillaID) == null) |
| { |
| ModelState.AddModelError("ErrorMessages", "Villa ID is Invalid!"); |
| return BadRequest(ModelState); |
| } |
| VillaNumber model = _mapper.Map<VillaNumber>(updateDTO); |
| |
| await _dbVillaNumber.UpdateAsync(model); |
| _response.StatusCode = HttpStatusCode.NoContent; |
| _response.IsSuccess = true; |
| return Ok(_response); |
| } |
| catch (Exception ex) |
| { |
| _response.IsSuccess = false; |
| _response.ErrorMessages |
| = new List<string>() { ex.ToString() }; |
| } |
| return _response; |
| } |
| |
| |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Controllers\v2\VillaNumberAPIController.cs
| using AutoMapper; |
| using MagicVilla_VillaAPI.Data; |
| using MagicVilla_VillaAPI.Models; |
| using MagicVilla_VillaAPI.Models.Dto; |
| using MagicVilla_VillaAPI.Repository.IRepostiory; |
| using Microsoft.AspNetCore.Authorization; |
| using Microsoft.AspNetCore.Http.HttpResults; |
| using Microsoft.AspNetCore.JsonPatch; |
| using Microsoft.AspNetCore.Mvc; |
| using Microsoft.EntityFrameworkCore; |
| using System.Data; |
| using System.Net; |
| |
| namespace MagicVilla_VillaAPI.Controllers.v2 |
| { |
| [Route("api/v{version:apiVersion}/VillaNumberAPI")] |
| [ApiController] |
| [ApiVersion("2.0")] |
| public class VillaNumberAPIController : ControllerBase |
| { |
| protected APIResponse _response; |
| private readonly IVillaNumberRepository _dbVillaNumber; |
| private readonly IVillaRepository _dbVilla; |
| private readonly IMapper _mapper; |
| public VillaNumberAPIController(IVillaNumberRepository dbVillaNumber, IMapper mapper, |
| IVillaRepository dbVilla) |
| { |
| _dbVillaNumber = dbVillaNumber; |
| _mapper = mapper; |
| _response = new(); |
| _dbVilla = dbVilla; |
| } |
| |
| |
| |
| [HttpGet("GetString")] |
| public IEnumerable<string> Get() |
| { |
| return new string[] { "Bhrugen", "DotNetMastery" }; |
| } |
| |
| |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Data\ApplicationDbContext.cs
| using MagicVilla_VillaAPI.Models; |
| using Microsoft.AspNetCore.Identity.EntityFrameworkCore; |
| using Microsoft.EntityFrameworkCore; |
| |
| namespace MagicVilla_VillaAPI.Data |
| { |
| public class ApplicationDbContext : IdentityDbContext<ApplicationUser> |
| { |
| public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) |
| : base(options) |
| { |
| } |
| |
| public DbSet<ApplicationUser> ApplicationUsers { get; set; } |
| |
| public DbSet<LocalUser> LocalUsers { get; set; } |
| public DbSet<Villa> Villas { get; set; } |
| public DbSet<VillaNumber> VillaNumbers { get; set; } |
| |
| protected override void OnModelCreating(ModelBuilder modelBuilder) |
| { |
| base.OnModelCreating(modelBuilder); |
| |
| modelBuilder.Entity<Villa>().HasData( |
| |
| |
| new Villa |
| { |
| Id = 1, |
| Name = "Royal Villa", |
| Details = "Fusce 11 tincidunt maximus leo, sed scelerisque massa auctor sit amet. Donec ex mauris, hendrerit quis nibh ac, efficitur fringilla enim.", |
| ImageUrl = "https://dotnetmastery.com/bluevillaimages/villa3.jpg", |
| Occupancy = 4, |
| Rate = 200, |
| Sqft = 550, |
| Amenity = "", |
| CreatedDate = DateTime.Now |
| }, |
| new Villa |
| { |
| Id = 2, |
| Name = "Premium Pool Villa", |
| Details = "Fusce 11 tincidunt maximus leo, sed scelerisque massa auctor sit amet. Donec ex mauris, hendrerit quis nibh ac, efficitur fringilla enim.", |
| ImageUrl = "https://dotnetmastery.com/bluevillaimages/villa1.jpg", |
| Occupancy = 4, |
| Rate = 300, |
| Sqft = 550, |
| Amenity = "", |
| CreatedDate = DateTime.Now |
| }, |
| new Villa |
| { |
| Id = 3, |
| Name = "Luxury Pool Villa", |
| Details = "Fusce 11 tincidunt maximus leo, sed scelerisque massa auctor sit amet. Donec ex mauris, hendrerit quis nibh ac, efficitur fringilla enim.", |
| ImageUrl = "https://dotnetmastery.com/bluevillaimages/villa4.jpg", |
| Occupancy = 4, |
| Rate = 400, |
| Sqft = 750, |
| Amenity = "", |
| CreatedDate = DateTime.Now |
| }, |
| new Villa |
| { |
| Id = 4, |
| Name = "Diamond Villa", |
| Details = "Fusce 11 tincidunt maximus leo, sed scelerisque massa auctor sit amet. Donec ex mauris, hendrerit quis nibh ac, efficitur fringilla enim.", |
| ImageUrl = "https://dotnetmastery.com/bluevillaimages/villa5.jpg", |
| Occupancy = 4, |
| Rate = 550, |
| Sqft = 900, |
| Amenity = "", |
| CreatedDate = DateTime.Now |
| }, |
| new Villa |
| { |
| Id = 5, |
| Name = "Diamond Pool Villa", |
| Details = "Fusce 11 tincidunt maximus leo, sed scelerisque massa auctor sit amet. Donec ex mauris, hendrerit quis nibh ac, efficitur fringilla enim.", |
| ImageUrl = "https://dotnetmastery.com/bluevillaimages/villa2.jpg", |
| Occupancy = 4, |
| Rate = 600, |
| Sqft = 1100, |
| Amenity = "", |
| CreatedDate = DateTime.Now |
| }); |
| |
| |
| } |
| } |
| } |
| |
| |
| |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\APIResponse.cs
| using System.Net; |
| |
| namespace MagicVilla_VillaAPI.Models |
| { |
| public class APIResponse |
| { |
| public APIResponse() |
| { |
| ErrorMessages = new List<string>(); |
| } |
| public HttpStatusCode StatusCode { get; set; } |
| public bool IsSuccess { get; set; } = true; |
| public List<string> ErrorMessages { get; set; } |
| public object Result { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\ApplicationUser.cs
| using Microsoft.AspNetCore.Identity; |
| |
| namespace MagicVilla_VillaAPI.Models |
| { |
| public class ApplicationUser : IdentityUser |
| { |
| public string Name { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\LocalUser.cs
| namespace MagicVilla_VillaAPI.Models |
| { |
| public class LocalUser |
| { |
| public int Id { get; set; } |
| public string UserName { get; set; } |
| public string Name { get; set; } |
| public string Password { get; set; } |
| public string Role { get; set; } |
| } |
| } |
| |
| namespace MagicVilla_VillaAPI.Models |
| { |
| public class Pagination |
| { |
| public int PageNumber { get; set; } |
| public int PageSize { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\Villa.cs
| using System.ComponentModel.DataAnnotations; |
| using System.ComponentModel.DataAnnotations.Schema; |
| |
| namespace MagicVilla_VillaAPI.Models |
| { |
| public class Villa |
| { |
| [Key] |
| [DatabaseGenerated(DatabaseGeneratedOption.Identity)] |
| public int Id { get; set; } |
| [Required] |
| public string Name { get; set; } |
| public string Details { get; set; } |
| public double Rate { get; set; } |
| public int Sqft { get; set; } |
| public int Occupancy { get; set; } |
| public string ImageUrl { get; set; } |
| public string Amenity { get; set; } |
| public DateTime CreatedDate { get; set; } |
| public DateTime UpdatedDate { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\VillaNumber.cs
| using System.ComponentModel.DataAnnotations; |
| using System.ComponentModel.DataAnnotations.Schema; |
| |
| namespace MagicVilla_VillaAPI.Models |
| { |
| public class VillaNumber |
| { |
| [Key, DatabaseGenerated(DatabaseGeneratedOption.None)] |
| public int VillaNo { get; set; } |
| |
| [ForeignKey("Villa")] |
| public int VillaID { get; set; } |
| |
| public Villa Villa { get; set; } |
| |
| public string SpecialDetails { get; set; } |
| public DateTime CreatedDate { get; set; } |
| public DateTime UpdatedDate { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\Dto\LoginRequestDTO.cs
| namespace MagicVilla_VillaAPI.Models.Dto |
| { |
| public class LoginRequestDTO |
| { |
| public string UserName { get; set; } |
| public string Password { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\Dto\LoginResponseDTO.cs
| namespace MagicVilla_VillaAPI.Models.Dto |
| { |
| public class LoginResponseDTO |
| { |
| public UserDTO User { get; set; } |
| public string Token { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\Dto\RegisterationRequestDTO.cs
| namespace MagicVilla_VillaAPI.Models.Dto |
| { |
| public class RegisterationRequestDTO |
| { |
| public string UserName { get; set; } |
| public string Name { get; set; } |
| public string Password { get; set; } |
| public string Role { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\Dto\UserDTO.cs
| namespace MagicVilla_VillaAPI.Models.Dto |
| { |
| public class UserDTO |
| { |
| public string ID { get; set; } |
| public string UserName { get; set; } |
| public string Name { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\Dto\VillaCreateDTO.cs
| using System.ComponentModel.DataAnnotations; |
| |
| namespace MagicVilla_VillaAPI.Models.Dto |
| { |
| public class VillaCreateDTO |
| { |
| [Required] |
| [MaxLength(30)] |
| public string Name { get; set; } |
| public string Details { get; set; } |
| [Required] |
| public double Rate { get; set; } |
| public int Occupancy { get; set; } |
| public int Sqft { get; set; } |
| public string ImageUrl { get; set; } |
| public string Amenity { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\Dto\VillaDTO.cs
| using System.ComponentModel.DataAnnotations; |
| |
| namespace MagicVilla_VillaAPI.Models.Dto |
| { |
| public class VillaDTO |
| { |
| public int Id { get; set; } |
| [Required] |
| [MaxLength(30)] |
| public string Name { get; set; } |
| public string Details { get; set; } |
| [Required] |
| public double Rate { get; set; } |
| public int Occupancy { get; set; } |
| public int Sqft { get; set; } |
| public string ImageUrl { get; set; } |
| public string Amenity { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\Dto\VillaNumberCreateDTO.cs
| using System.ComponentModel.DataAnnotations; |
| |
| namespace MagicVilla_VillaAPI.Models.Dto |
| { |
| public class VillaNumberCreateDTO |
| { |
| [Required] |
| public int VillaNo { get; set; } |
| [Required] |
| public int VillaID { get; set; } |
| public string SpecialDetails { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\Dto\VillaNumberDTO.cs
| using System.ComponentModel.DataAnnotations; |
| |
| namespace MagicVilla_VillaAPI.Models.Dto |
| { |
| public class VillaNumberDTO |
| { |
| [Required] |
| public int VillaNo { get; set; } |
| [Required] |
| public int VillaID { get; set; } |
| public string SpecialDetails { get; set; } |
| public VillaDTO Villa { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\Dto\VillaNumberUpdateDTO.cs
| using System.ComponentModel.DataAnnotations; |
| |
| namespace MagicVilla_VillaAPI.Models.Dto |
| { |
| public class VillaNumberUpdateDTO |
| { |
| [Required] |
| public int VillaNo { get; set; } |
| [Required] |
| public int VillaID { get; set; } |
| public string SpecialDetails { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Models\Dto\VillaUpdateDTO.cs
| using System.ComponentModel.DataAnnotations; |
| |
| namespace MagicVilla_VillaAPI.Models.Dto |
| { |
| public class VillaUpdateDTO |
| { |
| [Required] |
| public int Id { get; set; } |
| [Required] |
| [MaxLength(30)] |
| public string Name { get; set; } |
| public string Details { get; set; } |
| [Required] |
| public double Rate { get; set; } |
| [Required] |
| public int Occupancy { get; set; } |
| [Required] |
| public int Sqft { get; set; } |
| [Required] |
| public string ImageUrl { get; set; } |
| public string Amenity { get; set; } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Repository\Repository.cs
| using MagicVilla_VillaAPI.Data; |
| using MagicVilla_VillaAPI.Models; |
| using MagicVilla_VillaAPI.Repository.IRepostiory; |
| using Microsoft.EntityFrameworkCore; |
| using System.Linq.Expressions; |
| |
| namespace MagicVilla_VillaAPI.Repository |
| { |
| public class Repository<T> : IRepository<T> where T : class |
| { |
| private readonly ApplicationDbContext _db; |
| internal DbSet<T> dbSet; |
| public Repository(ApplicationDbContext db) |
| { |
| _db = db; |
| |
| this.dbSet=_db.Set<T>(); |
| } |
| |
| public async Task CreateAsync(T entity) |
| { |
| await dbSet.AddAsync(entity); |
| await SaveAsync(); |
| } |
| |
| |
| public async Task<T> GetAsync(Expression<Func<T, bool>> filter = null, bool tracked = true, string? includeProperties = null) |
| { |
| IQueryable<T> query = dbSet; |
| if (!tracked) |
| { |
| query = query.AsNoTracking(); |
| } |
| if (filter != null) |
| { |
| query = query.Where(filter); |
| } |
| |
| if (includeProperties != null) |
| { |
| foreach(var includeProp in includeProperties.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries)) |
| { |
| query = query.Include(includeProp); |
| } |
| } |
| return await query.FirstOrDefaultAsync(); |
| } |
| |
| public async Task<List<T>> GetAllAsync(Expression<Func<T, bool>>? filter = null, string? includeProperties = null, |
| int pageSize = 0, int pageNumber = 1) |
| { |
| IQueryable<T> query = dbSet; |
| |
| if (filter != null) |
| { |
| query = query.Where(filter); |
| } |
| if (pageSize > 0) |
| { |
| if (pageSize > 100) |
| { |
| pageSize = 100; |
| } |
| |
| |
| |
| query = query.Skip(pageSize * (pageNumber - 1)).Take(pageSize); |
| } |
| if (includeProperties != null) |
| { |
| foreach (var includeProp in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) |
| { |
| query = query.Include(includeProp); |
| } |
| } |
| return await query.ToListAsync(); |
| } |
| |
| public async Task RemoveAsync(T entity) |
| { |
| dbSet.Remove(entity); |
| await SaveAsync(); |
| } |
| |
| public async Task SaveAsync() |
| { |
| await _db.SaveChangesAsync(); |
| } |
| |
| |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Repository\UserRepository.cs
| using AutoMapper; |
| using MagicVilla_VillaAPI.Data; |
| using MagicVilla_VillaAPI.Models; |
| using MagicVilla_VillaAPI.Models.Dto; |
| using MagicVilla_VillaAPI.Repository.IRepostiory; |
| using Microsoft.AspNetCore.Identity; |
| using Microsoft.IdentityModel.Tokens; |
| using System.IdentityModel.Tokens.Jwt; |
| using System.Security.Claims; |
| using System.Text; |
| |
| namespace MagicVilla_VillaAPI.Repository |
| { |
| public class UserRepository : IUserRepository |
| { |
| private readonly ApplicationDbContext _db; |
| private readonly UserManager<ApplicationUser> _userManager; |
| private readonly RoleManager<IdentityRole> _roleManager; |
| private string secretKey; |
| private readonly IMapper _mapper; |
| |
| public UserRepository(ApplicationDbContext db, IConfiguration configuration, |
| UserManager<ApplicationUser> userManager, IMapper mapper, RoleManager<IdentityRole> roleManager) |
| { |
| _db = db; |
| _mapper = mapper; |
| _userManager = userManager; |
| secretKey = configuration.GetValue<string>("ApiSettings:Secret"); |
| _roleManager = roleManager; |
| } |
| |
| public bool IsUniqueUser(string username) |
| { |
| var user = _db.ApplicationUsers.FirstOrDefault(x => x.UserName == username); |
| if (user == null) |
| { |
| return true; |
| } |
| return false; |
| } |
| |
| public async Task<LoginResponseDTO> Login(LoginRequestDTO loginRequestDTO) |
| { |
| var user = _db.ApplicationUsers |
| .FirstOrDefault(u => u.UserName.ToLower() == loginRequestDTO.UserName.ToLower()); |
| |
| bool isValid = await _userManager.CheckPasswordAsync(user, loginRequestDTO.Password); |
| |
| |
| if (user == null || isValid == false) |
| { |
| return new LoginResponseDTO() |
| { |
| Token = "", |
| User = null |
| }; |
| } |
| |
| |
| var roles = await _userManager.GetRolesAsync(user); |
| var tokenHandler = new JwtSecurityTokenHandler(); |
| var key = Encoding.ASCII.GetBytes(secretKey); |
| |
| var tokenDescriptor = new SecurityTokenDescriptor |
| { |
| Subject = new ClaimsIdentity(new Claim[] |
| { |
| new Claim(ClaimTypes.Name, user.UserName.ToString()), |
| new Claim(ClaimTypes.Role, roles.FirstOrDefault()) |
| }), |
| Expires = DateTime.UtcNow.AddDays(7), |
| SigningCredentials = new(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) |
| }; |
| |
| var token = tokenHandler.CreateToken(tokenDescriptor); |
| LoginResponseDTO loginResponseDTO = new LoginResponseDTO() |
| { |
| Token = tokenHandler.WriteToken(token), |
| User = _mapper.Map<UserDTO>(user), |
| |
| }; |
| return loginResponseDTO; |
| } |
| |
| public async Task<UserDTO> Register(RegisterationRequestDTO registerationRequestDTO) |
| { |
| ApplicationUser user = new() |
| { |
| UserName = registerationRequestDTO.UserName, |
| Email=registerationRequestDTO.UserName, |
| NormalizedEmail=registerationRequestDTO.UserName.ToUpper(), |
| Name = registerationRequestDTO.Name |
| }; |
| |
| try |
| { |
| var result = await _userManager.CreateAsync(user, registerationRequestDTO.Password); |
| if (result.Succeeded) |
| { |
| if (!_roleManager.RoleExistsAsync("admin").GetAwaiter().GetResult()){ |
| await _roleManager.CreateAsync(new IdentityRole("admin")); |
| await _roleManager.CreateAsync(new IdentityRole("customer")); |
| } |
| await _userManager.AddToRoleAsync(user, "admin"); |
| var userToReturn = _db.ApplicationUsers |
| .FirstOrDefault(u => u.UserName == registerationRequestDTO.UserName); |
| return _mapper.Map<UserDTO>(userToReturn); |
| |
| } |
| } |
| catch(Exception e) |
| { |
| |
| } |
| |
| return new UserDTO(); |
| } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Repository\VillaNumberRepository.cs
| using MagicVilla_VillaAPI.Data; |
| using MagicVilla_VillaAPI.Models; |
| using MagicVilla_VillaAPI.Repository.IRepostiory; |
| using Microsoft.EntityFrameworkCore; |
| using System.Linq.Expressions; |
| |
| namespace MagicVilla_VillaAPI.Repository |
| { |
| public class VillaNumberRepository : Repository<VillaNumber>, IVillaNumberRepository |
| { |
| private readonly ApplicationDbContext _db; |
| public VillaNumberRepository(ApplicationDbContext db): base(db) |
| { |
| _db = db; |
| } |
| |
| |
| public async Task<VillaNumber> UpdateAsync(VillaNumber entity) |
| { |
| entity.UpdatedDate = DateTime.Now; |
| _db.VillaNumbers.Update(entity); |
| await _db.SaveChangesAsync(); |
| return entity; |
| } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Repository\VillaRepository.cs
| using MagicVilla_VillaAPI.Data; |
| using MagicVilla_VillaAPI.Models; |
| using MagicVilla_VillaAPI.Repository.IRepostiory; |
| using Microsoft.EntityFrameworkCore; |
| using System.Linq.Expressions; |
| |
| namespace MagicVilla_VillaAPI.Repository |
| { |
| public class VillaRepository : Repository<Villa>, IVillaRepository |
| { |
| private readonly ApplicationDbContext _db; |
| public VillaRepository(ApplicationDbContext db): base(db) |
| { |
| _db = db; |
| } |
| |
| |
| public async Task<Villa> UpdateAsync(Villa entity) |
| { |
| entity.UpdatedDate = DateTime.Now; |
| _db.Villas.Update(entity); |
| await _db.SaveChangesAsync(); |
| return entity; |
| } |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Repository\IRepostiory\IRepository.cs
| using MagicVilla_VillaAPI.Models; |
| using System.Linq.Expressions; |
| |
| namespace MagicVilla_VillaAPI.Repository.IRepostiory |
| { |
| public interface IRepository<T> where T : class |
| { |
| Task<List<T>> GetAllAsync(Expression<Func<T, bool>>? filter = null, string? includeProperties = null, |
| int pageSize = 0, int pageNumber = 1); |
| Task<T> GetAsync(Expression<Func<T, bool>> filter = null, bool tracked = true, string? includeProperties = null); |
| Task CreateAsync(T entity); |
| Task RemoveAsync(T entity); |
| Task SaveAsync(); |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Repository\IRepostiory\IUserRepository.cs
| using MagicVilla_VillaAPI.Models; |
| using MagicVilla_VillaAPI.Models.Dto; |
| |
| namespace MagicVilla_VillaAPI.Repository.IRepostiory |
| { |
| public interface IUserRepository |
| { |
| bool IsUniqueUser(string username); |
| Task<LoginResponseDTO> Login(LoginRequestDTO loginRequestDTO); |
| Task<UserDTO> Register(RegisterationRequestDTO registerationRequestDTO); |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Repository\IRepostiory\IVillaNumberRepository.cs
| using MagicVilla_VillaAPI.Models; |
| using System.Linq.Expressions; |
| |
| namespace MagicVilla_VillaAPI.Repository.IRepostiory |
| { |
| public interface IVillaNumberRepository : IRepository<VillaNumber> |
| { |
| |
| Task<VillaNumber> UpdateAsync(VillaNumber entity); |
| |
| } |
| } |
| |
F:\song_csharp\MagicVilla_API-master\MagicVilla_VillaAPI\Repository\IRepostiory\IVillaRepository.cs
| using MagicVilla_VillaAPI.Models; |
| using System.Linq.Expressions; |
| |
| namespace MagicVilla_VillaAPI.Repository.IRepostiory |
| { |
| public interface IVillaRepository : IRepository<Villa> |
| { |
| |
| Task<Villa> UpdateAsync(Villa entity); |
| |
| } |
| } |
| |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战