You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

94 lines
3.6 KiB

using Magicodes.ExporterAndImporter.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.IdentityModel.Tokens;
using System.Globalization;
using System.Reflection;
using Wood.Util.ExtensionMethods;
using static Dapper.SqlMapper;
namespace Wood.Service
{
public static class ValidationHelper
{
public static List<string> ValidateDataLength<T>(IList<T> dataList, DbContext dbContext) where T : class
{
var errors = new List<string>();
var entityType = dbContext.Model.FindEntityType(typeof(T));
int rowNum = 2;
foreach (var data in dataList)
{
foreach (var property in entityType.GetProperties())
{
var maxLength = property.GetMaxLength();
if (maxLength > 0 && property.ClrType == typeof(string))
{
var value = property.PropertyInfo.GetValue(data) as string;
if (!string.IsNullOrEmpty(value) && value.Length > maxLength)
{
string title = property.GetImporterHeader_Name();
errors.Add($"第{rowNum}行数据错误:字段 {(title.IsNullOrEmpty() ? property.Name : title)} 的长度超过限制 ({value.Length} > {maxLength})");
}
}
string format = property.GetImporterHeader_Format();
if (format.HasValue())
{
if (format == "yyyy-MM-dd" || format == "yyyy-MM-dd HH:mm:ss")
{
var value = property.PropertyInfo.GetValue(data) as string;
if (DateTime.TryParse(value, out DateTime result) == false)
{
string title = property.GetImporterHeader_Name();
errors.Add($"第{rowNum}行数据错误:字段 {(title.IsNullOrEmpty() ? property.Name : title)} 的格式错误 (格式:{format},字段值:{value})");
}
}
}
}
rowNum++;
}
return errors;
}
}
public static class PropertyExtension
{
public static string GetImporterHeader_Name(this IProperty value)
{
string ret = value?.PropertyInfo?.GetCustomAttribute<ImporterHeaderAttribute>()?.Name;
return ret;
}
public static string GetImporterHeader_Format(this IProperty value)
{
string ret = value?.PropertyInfo?.GetCustomAttribute<ImporterHeaderAttribute>()?.Format;
return ret;
}
}
public static class SearchControlExtension
{
/// <summary>
/// 忽略双字节的PadRight功能,汉字的length = 2
/// </summary>
/// <param name="str"></param>
/// <param name="totalWidth"></param>
/// <param name="paddingChar"></param>
/// <returns></returns>
public static string PadRightByte(this string str, int totalWidth, char paddingChar = ' ')
{
if (str == null)
{
str = "";
}
int strLen = System.Text.UTF8Encoding.Default.GetBytes(str).Length;
int actualWidth = (totalWidth > strLen) ? (totalWidth - strLen) : 0;
return str + "".PadLeft(actualWidth, paddingChar);
}
}
}