Skip to content

Commit

Permalink
update epplus lib 7.18
Browse files Browse the repository at this point in the history
  • Loading branch information
dong-nguyen-hd committed Jul 18, 2022
1 parent e843a69 commit 42acc62
Show file tree
Hide file tree
Showing 10 changed files with 211 additions and 5 deletions.
5 changes: 3 additions & 2 deletions BE/API/Controllers/ImageController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Business.Data;

namespace API.Controllers
{
Expand Down Expand Up @@ -33,8 +34,8 @@ public IActionResult GetDefaultUriAsync()
{
var path = new
{
OriginalImagePath = _uriService.GetRouteUri($"{_hostResource.OriginalImagePath}default.jpg"),
ThumbnailImagePath = _uriService.GetRouteUri($"{_hostResource.ThumbnailImagePath}default.jpg")
OriginalImagePath = _uriService.GetRouteUri($"{_hostResource.OriginalImagePath}{Constant.DefaultAvatar}"),
ThumbnailImagePath = _uriService.GetRouteUri($"{_hostResource.ThumbnailImagePath}{Constant.DefaultAvatar}")
};

return Ok(new BaseResponse<object>(path));
Expand Down
72 changes: 72 additions & 0 deletions BE/API/Controllers/TimesheetController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using Business.Communication;
using Business.Domain.Services;
using Business.Resources;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace API.Controllers
{
[ApiController]
[Route("api/v1/timesheet")]
public class TimesheetController : ControllerBase
{
#region Property
private readonly ITimesheetService _timesheetService;
protected readonly ResponseMessage ResponseMessage;
#endregion

#region Constructor
public TimesheetController(ITimesheetService timesheetService,
IOptionsMonitor<ResponseMessage> responseMessage)
{
this._timesheetService = timesheetService;
this.ResponseMessage = responseMessage.CurrentValue;
}
#endregion

#region Action
[HttpPost("import")]
[AllowAnonymous]
[ProducesResponseType(typeof(BaseResponse<>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(BaseResponse<>), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ImportAsync([FromForm] IFormFile file)
{
// Validate file import
var validateResult = ValidateTimesheet(file);
if (!validateResult.isSuccess) return BadRequest(validateResult.result);

var filePath = Path.GetTempFileName();

var stream = new FileStream(filePath, FileMode.Create);
await file.CopyToAsync(stream);
stream.Position = 0;

var result = await _timesheetService.ImportAsync(stream);
stream.Dispose();

// Clean temp-file
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath);

if (result.Success)
return Ok(result);

return BadRequest(result);
}
#endregion

#region Private work
private (bool isSuccess, BaseResponse<object> result) ValidateTimesheet(IFormFile file)
{
if (file == null || file.Length <= 0)
return (false, new BaseResponse<object>(ResponseMessage.Values["File_Empty"]));

if (!Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
return (false, new BaseResponse<object>(ResponseMessage.Values["Not_Support_File"]));

return (true, new BaseResponse<object>(true));
}
#endregion
}
}
2 changes: 2 additions & 0 deletions BE/API/Extensions/AddServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ public static void AddDependencyInjection(this IServiceCollection services)

services.AddScoped<ITokenManagementService, TokenManagementService>();

services.AddScoped<ITimesheetService, TimesheetService>();

services.AddScoped<ITokenRepository, TokenRepository>();

services.AddScoped<IImageService, ImageService>(); // ImageCrossPlatformService (use for other OSs except Windows)
Expand Down
8 changes: 7 additions & 1 deletion BE/API/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,19 @@
},
"PathConfig": {
"OriginalImagePath": "/Images/Original/",
"ThumbnailImagePath": "/Images/Thumbnail/"
"ThumbnailImagePath": "/Images/Thumbnail/",
"TimesheetPath": "/Timesheet/"
},
"JwtConfig": {
"secret": "dong-nguyen-hd-secret-more-than-16-characters",
"issuer": "https://github.com/dong-nguyen-hd",
"audience": "https://github.com/dong-nguyen-hd",
"accessTokenExpiration": 50,
"refreshTokenExpiration": 100
},
"EPPlus": {
"ExcelPackage": {
"LicenseContext": "NonCommercial"
}
}
}
4 changes: 4 additions & 0 deletions BE/API/responsemessage.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,15 @@
"Updating_Error": "An error occurred when updating",
"Deleting_Error": "An error occurred when deleting",
"Swapping_Error": "An error occurred when swapping",
"Not_Support_File": "Not Support file extension",
"File_Empty": "File is empty",

"Token_Invalid": "User name or password is incorrect",
"Token_Not_Permitted": "Refresh Token not permitted",
"Token_Saving_Error": "An error occurred when saving the Token",

"Timesheet_Invalid": "An error occurred when reading the Timesheet",

"Image_NoData": "There is no image.",
"Image_Format_Error": "Image format is not supported.",
"Image_Bigger_Error": "Image cannot be bigger than 5 MB",
Expand Down
5 changes: 3 additions & 2 deletions BE/Business/Business.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,16 @@
<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="11.0.0" />
<PackageReference Include="Cronos" Version="0.7.1" />
<PackageReference Include="EPPlus" Version="6.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Cryptography.KeyDerivation" Version="6.0.3" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Serilog.AspNetCore" Version="5.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="6.0.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
<PackageReference Include="Serilog.Enrichers.Process" Version="2.0.2" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="2.1.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="2.1.3" />
<PackageReference Include="System.Drawing.Common" Version="7.0.0-preview.2.22152.2" />
</ItemGroup>

Expand Down
10 changes: 10 additions & 0 deletions BE/Business/Domain/Services/ITimesheetService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using Business.Communication;
using Business.Resources.Timesheet;

namespace Business.Domain.Services
{
public interface ITimesheetService
{
Task<BaseResponse<TimesheetResource>> ImportAsync(Stream stream);
}
}
1 change: 1 addition & 0 deletions BE/Business/Resources/Information/HostResource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ public sealed class HostResource
#region Property
public string OriginalImagePath { get; set; }
public string ThumbnailImagePath { get; set; }
public string TimesheetPath { get; set; }
#endregion
}
}
25 changes: 25 additions & 0 deletions BE/Business/Resources/Timesheet/TimesheetResource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System.ComponentModel.DataAnnotations;

namespace Business.Resources.Timesheet
{
public class TimesheetResource
{
public int Id { get; set; }

[Display(Name = "Total Work Day")]
public float TotalWorkDay { get; set; }

[Display(Name = "Work Day")]
public float WorkDay { get; set; }
public float? Absent { get; set; }
public float? Holiday { get; set; }

[Display(Name = "Unpaid Leave")]
public float? UnpaidLeave { get; set; }

[Display(Name = "Paid Leave")]
public float? PaidLeave { get; set; }
public string TimesheetJSON { get; set; }
public DateTime Date { get; set; }
}
}
84 changes: 84 additions & 0 deletions BE/Business/Services/TimesheetService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using AutoMapper;
using Business.Communication;
using Business.Domain.Repositories;
using Business.Domain.Services;
using Business.Resources;
using Business.Resources.Information;
using Business.Resources.Timesheet;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Options;
using OfficeOpenXml;

namespace Business.Services
{
public class TimesheetService : ResponseMessageService, ITimesheetService
{
#region Property
protected readonly IMapper Mapper;
protected readonly IUnitOfWork UnitOfWork;
private readonly HostResource _hostResource;
private readonly IWebHostEnvironment _env;
#endregion

#region Constructor
public TimesheetService(
IMapper mapper,
IUnitOfWork unitOfWork,
IWebHostEnvironment env,
IOptionsMonitor<HostResource> hostResource,
IOptionsMonitor<ResponseMessage> responseMessage) : base(responseMessage)
{
this.Mapper = mapper;
this.UnitOfWork = unitOfWork;
this._hostResource = hostResource.CurrentValue;
this._env = env;
}
#endregion

#region Method
public async Task<BaseResponse<TimesheetResource>> ImportAsync(Stream stream)
{
using (ExcelPackage package = new ExcelPackage())
{
await package.LoadAsync(stream);

// Get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];

var year = (double?)worksheet.Cells[3, 2].Value;
var month = (double?)worksheet.Cells[3, 4].Value;

if (year == null || month == null)
return new BaseResponse<TimesheetResource>(ResponseMessage.Values["Timesheet_Invalid"]);

Console.WriteLine($"Timesheet - Year: {year}");
Console.WriteLine($"Timesheet - Month: {month}");

//int col = 2; // Column 2 is the item description
//for (int row = 2; row < 5; row++)
// Console.WriteLine("\tCell({0},{1}).Value={2}", row, col, worksheet.Cells[row, col].Value);

string newPath = GetRootPath($"{year}-{month}.xlsx");
if (File.Exists(newPath))
File.Delete(newPath);

await package.SaveAsAsync(newPath);
}

return new BaseResponse<TimesheetResource>(true);
}

#region Private work
private string GetRootPath(string timesheetFileName)
{
string timesheetPath = string.Format($"{_hostResource.TimesheetPath}{timesheetFileName}");
string rootPath = string.Concat(_env.WebRootPath, timesheetPath);

return rootPath;
}
#endregion

#endregion
}

}

0 comments on commit 42acc62

Please sign in to comment.