using AsbCloudApp.Data.User;
using AsbCloudWebApi.Converters;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
using AsbCloudApp.Data;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Requests.ParserOptions;
using AsbCloudWebApi.Controllers.Interfaces;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Mvc
{
public static class Extentions
{
public static int? GetCompanyId(this ClaimsPrincipal user)
{
var claimIdCompany = user.FindFirst(nameof(UserDto.IdCompany));
if (claimIdCompany is null)
return null;
return int.TryParse(claimIdCompany.Value, out int uid)
? uid
: null;
}
public static int? GetUserId(this ClaimsPrincipal user)
{
var userId = user.FindFirst(nameof(UserDto.Id));
if (userId is null)
return null;
return int.TryParse(userId.Value, out int uid)
? uid
: null;
}
///
///
/// Returns BadRequest with ValidationProblemDetails as body
///
///
/// Используйте этот метод только если валидацию нельзя сделать через
/// атрибуты валидации или IValidatableObject модели.
///
///
///
///
///
///
public static BadRequestObjectResult ValidationBadRequest(this ControllerBase controller, string paramName, string error)
{
var errors = new Dictionary {
{ paramName, new[]{ error } }
};
var problem = new ValidationProblemDetails(errors);
return controller.BadRequest(problem);
}
///
///
/// Returns BadRequest with ValidationProblemDetails as body
///
///
/// Используйте этот метод только если валидацию нельзя сделать через
/// атрибуты валидации или IValidatableObject модели.
///
///
///
///
///
public static BadRequestObjectResult ValidationBadRequest(this ControllerBase controller, IEnumerable validationResults)
{
var errors = validationResults
.SelectMany(e => e.MemberNames.Select(name=> new { name, e.ErrorMessage }))
.ToDictionary(e => e.name, e => new[] { e.ErrorMessage ?? string.Empty });
var problem = new ValidationProblemDetails(errors);
return controller.BadRequest(problem);
}
public static MvcOptions UseDateOnlyTimeOnlyStringConverters(this MvcOptions options)
{
TypeDescriptor.AddAttributes(typeof(DateOnly), new TypeConverterAttribute(typeof(DateOnlyTypeConverter)));
return options;
}
public static ActionResult> ParseExcelFile(
this IControllerWithParser controller,
IFormFileCollection files,
TOptions options)
where TDto : class, IId
where TOptions : class, IParserOptionsRequest
{
using var file = GetExcelFile(files);
return controller.Parse(file, options);
}
private static Stream GetExcelFile(IFormFileCollection files)
{
if (files.Count < 1)
throw new ArgumentInvalidException(nameof(files), "Нет файла");
var file = files[0];
if (Path.GetExtension(file.FileName).ToLower() != ".xlsx")
throw new ArgumentInvalidException(nameof(files), "Требуется .xlsx файл.");
return file.OpenReadStream();
}
}
}