Skip to content

Commit

Permalink
Create Api Document: Add, Delete,Update,ListALl, Detail
Browse files Browse the repository at this point in the history
  • Loading branch information
vuanh25 committed Nov 17, 2023
1 parent 99ab056 commit aa232ad
Show file tree
Hide file tree
Showing 15 changed files with 2,435 additions and 28 deletions.
19 changes: 19 additions & 0 deletions VNH.Application/DTOs/Catalog/Document/CreateDocumentDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VNH.Application.DTOs.Catalog.Document
{
public class CreateDocumentDto
{

public string? Id { get; set; } = Guid.NewGuid().ToString();
public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public IFormFile? FileName { get; set; }

}
}
25 changes: 25 additions & 0 deletions VNH.Application/DTOs/Catalog/Document/DocumentReponseDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VNH.Application.DTOs.Catalog.Users;

namespace VNH.Application.DTOs.Catalog.Document
{
public class DocumentReponseDto
{
public string Id { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;

public string FileName { get; set; } = string.Empty;

public DateTime? CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
public UserShortDto UserShort { get; set; } = new UserShortDto();
public int ViewNumber { get; set; } = 0;
public int DownloadNumber { get; set; } = 0;
public int PageNumber { get; set; } = 0;
}
}
16 changes: 16 additions & 0 deletions VNH.Application/Interfaces/Catalog/Documents/IDocumentService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using VNH.Application.DTOs.Catalog.Document;
using VNH.Application.DTOs.Catalog.Posts;
using VNH.Application.DTOs.Common.ResponseNotification;

namespace VNH.Application.Interfaces.Documents
{
public interface IDocumentService
{
Task<ApiResult<DocumentReponseDto>> Create(CreateDocumentDto requestDto, string name);
Task<ApiResult<DocumentReponseDto>> Update(CreateDocumentDto requestDto, string name);
Task<ApiResult<DocumentReponseDto>> Detail(string Id);
Task<ApiResult<List<DocumentReponseDto>>> GetAll();
Task<ApiResult<string>> Delete(string id, string email);

}
}
20 changes: 20 additions & 0 deletions VNH.Application/Interfaces/Common/IFileService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VNH.Application.Interfaces.Common
{
public interface IFileService
{
Task<string> SaveFile(IFormFile file);

Task<byte[]> ConvertFormFileToByteArray(IFormFile formFile);

string ConvertByteArrayToString(byte[]? byteArray, Encoding encoding);
byte[] CompressImage(byte[] originalImage, int KbNumber);

}
}
18 changes: 18 additions & 0 deletions VNH.Application/Mappers/DocumentMapper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using AutoMapper;
using VNH.Application.DTOs.Catalog.Document;
using VNH.Application.DTOs.Catalog.Posts;
using VNH.Domain;

namespace VNH.Application.Mappers
{
public class DocumentMapper : Profile
{
public DocumentMapper
()
{
CreateMap<CreateDocumentDto, Document>()
.ForMember(dest => dest.FileName, opt => opt.Ignore());
CreateMap<Document,DocumentReponseDto>().ForMember(dest => dest.FileName, opt => opt.Ignore());
}
}
}
8 changes: 2 additions & 6 deletions VNH.Domain/Entities/Document.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,15 @@ public Document()
public string Title { get; set; }
[StringLength(500)]
public string Description { get; set; }
[StringLength(255)]
[Unicode(false)]
public string Image { get; set; } = string.Empty;
[StringLength(255)]
[Unicode(false)]

public string FileName { get; set; }
[StringLength(255)]
[Unicode(false)]
public string ContentType { get; set; }
public byte[] Content { get; set; }
public Guid? UserId { get; set; }
[Column(TypeName = "datetime")]
public DateTime? CreatedAt { get; set; }
public DateTime CreatedAt { get; set; }
[Column(TypeName = "datetime")]
public DateTime? UpdatedAt { get; set; }

Expand Down
4 changes: 4 additions & 0 deletions VNH.Infrastructure/DependencyInjectionInfrastructure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
using VNH.Infrastructure.Implement.Catalog.HashTags;
using VNH.Application.Interfaces.Catalog.Reports;
using VNH.Infrastructure.Implement.Catalog.Reports;
using VNH.Application.Interfaces.Documents;
using VNH.Infrastructure.Implement.Catalog.Documents;

namespace VNH.Infrastructure
{
Expand Down Expand Up @@ -127,6 +129,8 @@ public static IServiceCollection AddInfrastructure(this IServiceCollection servi
services.AddScoped<ITopicService, TopicService>();
services.AddScoped<IPostService, PostService>();
services.AddScoped<IReportService, ReportService>();
services.AddScoped<IDocumentService, DocumentService>();
services.AddScoped<IFileService, FileService>();
services.AddSignalR();


Expand Down
222 changes: 222 additions & 0 deletions VNH.Infrastructure/Implement/Catalog/Documents/DocumentService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
using AutoMapper;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using VNH.Application.DTOs.Catalog.Document;
using VNH.Application.DTOs.Catalog.Users;
using VNH.Application.DTOs.Common.ResponseNotification;
using VNH.Application.Interfaces.Documents;
using VNH.Application.Interfaces.Common;
using VNH.Domain;
using VNH.Infrastructure.Presenters.Migrations;
using Microsoft.EntityFrameworkCore;
using VNH.Application.DTOs.Catalog.HashTags;
using VNH.Domain.Entities;
using VNH.Application.DTOs.Catalog.Posts;

namespace VNH.Infrastructure.Implement.Catalog.Documents
{
public class DocumentService : IDocumentService
{

private readonly UserManager<User> _userManager;
private readonly VietNamHistoryContext _dataContext;
private readonly IFileService _document;
private readonly IStorageService _storageService;
private readonly IMapper _mapper;

public DocumentService(UserManager<User> userManager,IMapper mapper,IFileService document,
VietNamHistoryContext vietNamHistoryContext,IStorageService storageService)
{
_userManager = userManager;
_mapper = mapper;
_document = document;
_dataContext = vietNamHistoryContext;
_storageService = storageService;
}

public async Task<ApiResult<DocumentReponseDto>> Create(CreateDocumentDto requestDto,string name)
{
var user = await _userManager.FindByEmailAsync(name);
var document = _mapper.Map<Document>(requestDto);
document.FileName = await _document.SaveFile(requestDto.FileName);
document.CreatedAt = DateTime.Now;
document.UserId = user.Id;
string formattedDateTime = document.CreatedAt.ToString("HH:mm:ss.fff-dd-MM-yyyy");
var Id = SanitizeString(document.Title);
try
{
_dataContext.Documents.Add(document);
await _dataContext.SaveChangesAsync();
var documentReponse = _mapper.Map<DocumentReponseDto>(document);

documentReponse.FileName = document.FileName;
var userDto = new UserShortDto()
{
FullName = user.Fullname,
Id = user.Id,
Image = user.Image,
};
documentReponse.UserShort = userDto;


return new ApiSuccessResult<DocumentReponseDto>(documentReponse);
}
catch (Exception ex)
{
return new ApiErrorResult<DocumentReponseDto>("Lỗi lưu tài liệu : " + ex.Message);
}

}


private static string RemoveDiacritics(string input)
{
string normalizedString = input.Normalize(NormalizationForm.FormD);
StringBuilder stringBuilder = new StringBuilder();

foreach (char c in normalizedString)
{
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}

return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
private static string SanitizeString(string input)
{
string withoutDiacritics = RemoveDiacritics(input).Trim().Replace(" ", "-");
string sanitizedString = Regex.Replace(withoutDiacritics, "[^a-zA-Z0-9-]", "");

return sanitizedString;
}

public async Task<ApiResult<DocumentReponseDto>> Update(CreateDocumentDto requestDto, string name)
{
var user = await _userManager.FindByEmailAsync(name);

var updateDocument = _dataContext.Documents
.FirstOrDefault(x => x.Id.Equals(Guid.Parse(requestDto.Id)));
if (updateDocument is null)
{
return new ApiErrorResult<DocumentReponseDto>("Lỗi :Tài liệu không được cập nhập (không tìm thấy tài liệu)");
}
if (updateDocument.FileName != string.Empty)
{
await _storageService.DeleteFileAsync(updateDocument.FileName);
}
updateDocument.FileName = await _document.SaveFile(requestDto.FileName);
updateDocument.UpdatedAt = DateTime.Now;
updateDocument.Description = requestDto.Description;
string formattedDateTime = DateTime.Now.ToString("HH:mm:ss.fff-dd-MM-yyyy");
try
{
_dataContext.Documents.Update(updateDocument);
await _dataContext.SaveChangesAsync();


var documentResponse = _mapper.Map<DocumentReponseDto>(updateDocument);

documentResponse.FileName = updateDocument.FileName;
var useDto = new UserShortDto()
{
FullName = user.Fullname,
Id = user.Id,
Image = user.Image
};
documentResponse.UserShort = useDto;



return new ApiSuccessResult<DocumentReponseDto>(documentResponse);
}
catch (Exception ex)
{
return new ApiErrorResult<DocumentReponseDto>("Lỗi lưu tài liệu : " + ex.Message);
}
}

public async Task<ApiResult<List<DocumentReponseDto>>> GetAll()
{
var documents = await _dataContext.Documents.ToListAsync();
var users = await _dataContext.User.ToListAsync();

var result = new List<DocumentReponseDto>();
foreach (var item in documents)
{
var document = _mapper.Map<DocumentReponseDto>(item);
var userShort = users.First(x => x.Id == item.UserId);
if (userShort is not null)
{
document.UserShort.FullName = userShort.Fullname;
document.UserShort.Id = userShort.Id;
document.UserShort.Image = userShort.Image;
}
document.FileName = item.FileName;

result.Add(document);
}

return new ApiSuccessResult<List<DocumentReponseDto>>(result);
}



public async Task<ApiResult<DocumentReponseDto>> Detail(string Id)
{
var document = await _dataContext.Documents.FirstOrDefaultAsync(x => x.Id.Equals(Guid.Parse
(Id)));
if (document is null)
{
return new ApiErrorResult<DocumentReponseDto>("Không tìm thấy tài liệu");
}
var user = await _userManager.FindByIdAsync(document
.UserId.ToString());
var documentResponse = _mapper.Map<DocumentReponseDto>(document);
documentResponse.FileName = document.FileName;



documentResponse
.UserShort = new()
{
FullName = user.Fullname,
Id = user.Id,
Image = user.Image
};

// _dataContext.Documents.Update(document);
await _dataContext.SaveChangesAsync();
return new ApiSuccessResult<DocumentReponseDto>(documentResponse);
}

public async Task<ApiResult<string>> Delete(string id, string userId)
{
var document = await _dataContext.Documents.FirstOrDefaultAsync(x => x.Id.Equals(Guid.Parse(id)) && x.UserId.ToString().Equals(userId));
if (document is null)
{
return new ApiErrorResult<string>("Không tìm thấy tài liệu");
}
if (document.FileName != string.Empty)
{
await _storageService.DeleteFileAsync(document.FileName
);
}
_dataContext.Documents.Remove(document
);

await _dataContext.SaveChangesAsync();

return new ApiSuccessResult<string>("Đã xóa tài liệu");
}


}
}
Loading

0 comments on commit aa232ad

Please sign in to comment.