จัดระเบียบ Code ใหม่ และเพิ่ม Extension Method

implement GenericRepository Class ใหม่
This commit is contained in:
Suphonchai Phoonsawat 2023-06-26 10:15:50 +07:00
parent e49c6a4aca
commit 89de09d213
21 changed files with 1439 additions and 63 deletions

View file

@ -26,6 +26,8 @@ namespace BMA.EHR.Application.Common.Interfaces
#endregion
DbSet<T> Set<T>() where T : class;
Task<int> SaveChangesAsync();
}
}

View file

@ -1,10 +1,11 @@
using BMA.EHR.Domain.Common;
using Microsoft.AspNetCore.Http;
namespace BMA.EHR.Application.Common.Interfaces
{
public interface IGenericRepository<S,T> where T : class
{
Task<T?> GetByIdAsync(S id);
public interface IGenericRepository<S, T> where T : class
{
Task<T?> GetByIdAsync(S id);
Task<IReadOnlyList<T>> GetAllAsync();
}

View file

@ -1,26 +1,28 @@
using BMA.EHR.Application.Common.Interfaces;
using BMA.EHR.Domain.Entities.MetaData.BloodGroup;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
namespace BMA.EHR.Application.Repositories.BloodGroup
{
public class BloodGroupRepository : IGenericRepository<Guid, BloodGroupEntity>
public class BloodGroupRepository : GenericRepository<Guid, BloodGroupEntity>
{
private readonly IApplicationDBContext _dbContext;
#region " Fields "
public BloodGroupRepository(IApplicationDBContext dbContext)
private readonly IApplicationDBContext _dbContext;
private readonly IHttpContextAccessor _httpContextAccessor;
#endregion
#region " Constructor and Destructor "
public BloodGroupRepository(IApplicationDBContext dbContext,
IHttpContextAccessor httpContextAccessor) : base(dbContext, httpContextAccessor)
{
_dbContext = dbContext;
_httpContextAccessor = httpContextAccessor;
}
public async Task<IReadOnlyList<BloodGroupEntity>> GetAllAsync()
{
return await _dbContext.MD_BloodGroups.ToListAsync();
}
#endregion
public async Task<BloodGroupEntity?> GetByIdAsync(Guid id)
{
return await _dbContext.MD_BloodGroups.FirstOrDefaultAsync(x => x.Id == id);
}
}
}
}

View file

@ -0,0 +1,52 @@
using BMA.EHR.Application.Common.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
namespace BMA.EHR.Application.Repositories
{
public class GenericRepository<S, T> : IGenericRepository<S, T> where T : class
{
#region " Field "
private readonly IApplicationDBContext _dbContext;
private readonly DbSet<T> _dbSet;
private readonly IHttpContextAccessor _httpContextAccessor;
#endregion
#region " Constructor and Destructor "
public GenericRepository(IApplicationDBContext dbContext,
IHttpContextAccessor httpContextAccessor)
{
_dbContext = dbContext;
_dbSet = _dbContext.Set<T>();
_httpContextAccessor = httpContextAccessor;
}
#endregion
#region " Properties "
private string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
private string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value;
#endregion
#region " Methods "
public async Task<IReadOnlyList<T>> GetAllAsync()
{
return await _dbSet.ToListAsync();
}
public async Task<T?> GetByIdAsync(S id)
{
return await _dbSet.FindAsync(id);
}
#endregion
}
}

View file

@ -1,26 +1,28 @@
using BMA.EHR.Application.Common.Interfaces;
using BMA.EHR.Domain.Entities.MetaData.Prefix;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
namespace BMA.EHR.Application.Repositories.Prefix
{
public class PrefixRepository : IGenericRepository<Guid, PrefixEntity>
public class PrefixRepository : GenericRepository<Guid, PrefixEntity>
{
private readonly IApplicationDBContext _dbContext;
#region " Fields "
public PrefixRepository(IApplicationDBContext dbContext)
private readonly IApplicationDBContext _dbContext;
private readonly IHttpContextAccessor _httpContextAccessor;
#endregion
#region " Constructor and Destructor "
public PrefixRepository(IApplicationDBContext dbContext,
IHttpContextAccessor httpContextAccessor) : base(dbContext, httpContextAccessor)
{
_dbContext = dbContext;
_httpContextAccessor = httpContextAccessor;
}
public async Task<IReadOnlyList<PrefixEntity>> GetAllAsync()
{
return await _dbContext.MD_Prefixes.ToListAsync();
}
#endregion
public async Task<PrefixEntity?> GetByIdAsync(Guid id)
{
return await _dbContext.MD_Prefixes.FirstOrDefaultAsync(x => x.Id == id);
}
}
}

View file

@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="7.0.8" />
</ItemGroup>

View file

@ -0,0 +1,114 @@
using BMA.EHR.Domain.Shared;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace BMA.EHR.Domain.Common
{
public class BaseController : ControllerBase
{
#region " Fields "
private readonly IHttpContextAccessor _httpContextAccessor;
#endregion
#region " Constructor and Destructor "
public BaseController(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
#endregion
#region " Properties "
private string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
private string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value;
#endregion
#region " Methods "
#region " Protected "
#region " IActionResult "
protected virtual ActionResult<ResponseObject> Success(string message, object? result = null)
{
if (result != null)
{
return Ok(new ResponseObject
{
Status = StatusCodes.Status200OK,
Message = message,
Result = result
});
}
else
{
return Ok(new ResponseObject
{
Status = StatusCodes.Status200OK,
Message = message
});
}
}
protected virtual ActionResult<ResponseObject> Success(object? result = null)
{
return Success(GlobalMessages.Success, result);
}
protected virtual ActionResult<ResponseObject> Error(string message, string result, int statusCode = StatusCodes.Status500InternalServerError)
{
return StatusCode((int)statusCode, new ResponseObject
{
Status = statusCode,
Message = message,
Result = result
});
}
protected virtual ActionResult<ResponseObject> Error(string message, int statusCode = StatusCodes.Status500InternalServerError)
{
return Error(message, message, statusCode);
}
protected virtual ActionResult<ResponseObject> Error(Exception exception, string message, int statusCode = StatusCodes.Status500InternalServerError)
{
var msg = exception.Message;
var inner = exception.InnerException;
while (inner != null)
{
msg += $" {inner.Message}\r\n";
inner = inner.InnerException;
}
return Error(message, msg, statusCode);
}
protected virtual ActionResult<ResponseObject> Error(Exception exception, int statusCode = StatusCodes.Status500InternalServerError)
{
var msg = exception.Message;
var inner = exception.InnerException;
while (inner != null)
{
msg += $" {inner.Message}\r\n";
inner = inner.InnerException;
}
return Error(msg, msg, statusCode);
}
#endregion
#endregion
#endregion
}
}

View file

@ -0,0 +1,13 @@
using System.Data.Common;
namespace BMA.EHR.Domain.Extensions
{
public static class DataReaderExtension
{
public static bool IsDbNull(this DbDataReader dataReader, string columnName)
{
return dataReader[columnName] == DBNull.Value;
}
}
}

View file

@ -0,0 +1,338 @@
using System;
using System.Globalization;
using System.Text;
namespace BMA.EHR.Domain.Extensions
{
public static class DateTimeExtension
{
private static CultureInfo _culture = new CultureInfo("th-TH");
#region " Methods "
#region " Public "
public static double DiffYear(this DateTime currentDate)
{
return (DateTime.Today - currentDate).TotalDays / 365.2425;
}
public static int ToUnixTimeStamp(this DateTime value)
{
return (int)Math.Truncate((value.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}
public static string ToThaiFullDate(this DateTime value)
{
var yy = value.Year < 2400 ? value.Year + 543 : value.Year;
return $"วันที่ {value.Day} เดือน {value.ToString("MMMM", _culture.DateTimeFormat)} พ.ศ. {yy}";
}
public static string ToThaiFullDate2(this DateTime value)
{
var yy = value.Year < 2400 ? value.Year + 543 : value.Year;
return $"{value.Day} {value.ToString("MMMM", _culture.DateTimeFormat)} พ.ศ. {yy}";
}
public static string ToThaiFullDate3(this DateTime value)
{
var yy = value.Year < 2400 ? value.Year + 543 : value.Year;
return $"{value.Day} {value.ToString("MMMM", _culture.DateTimeFormat)} {yy}";
}
public static string ToThaiShortDateTime(this DateTime value)
{
var yy = value.Year < 2400 ? value.Year + 543 : value.Year;
return $"{value.Day} {value.ToString("MMM", _culture.DateTimeFormat)} {yy} {value.ToString("HH:mm:ss")}";
}
public static string ToThaiShortDate(this DateTime value)
{
var yy = value.Year < 2400 ? value.Year + 543 : value.Year;
return $"{value.Day} {value.ToString("MMM", _culture.DateTimeFormat)} {yy}";
}
public static string ToThaiShortDate2(this DateTime value)
{
var yy = value.Year < 2400 ? value.Year + 543 : value.Year;
return $"{value.Day} {value.ToString("MMM", _culture.DateTimeFormat)} {yy.ToString().Right(2)}";
}
public static string ToThaiDate(this DateTime value)
{
var yy = value.Year < 2400 ? value.Year + 543 : value.Year;
return $"{value.Day}/{value.Month}/{yy}";
}
public static string ToCeDate(this DateTime value)
{
var yy = value.Year >= 2400 ? value.Year - 543 : value.Year;
return $"{value.Day}/{value.Month}/{yy}";
}
public static string ToThaiDateFullDigit(this DateTime value)
{
var yy = value.Year < 2400 ? value.Year + 543 : value.Year;
return $"{value.Day.ToString("00")}/{value.Month.ToString("00")}/{yy.ToString("00")}";
}
public static string GetDay(this DateTime value)
{
return value.Day.ToString();
}
public static string GetMonth(this DateTime value)
{
return value.ToString("MMMM", _culture.DateTimeFormat);
}
public static string GetYear(this DateTime value)
{
return value.Year.ToThaiYear().ToString();
}
public static string CalculateAgeStrV2(this DateTime date, int plusYear = 0, int subtractYear = 0)
{
try
{
var currentDate = DateTime.Now;
var age = currentDate - date;
if (date > currentDate)
{
throw new ArgumentException("วันเกิดต้องไม่มากกว่าวันที่ปัจจุบัน");
}
int years = currentDate.Year - date.Year;
int months = 0;
int days = 0;
if (currentDate.Month < date.Month ||
(currentDate.Month == date.Month && currentDate.Day < date.Day))
{
years--;
months = 12 - date.Month + currentDate.Month;
if (currentDate.Day < date.Day)
{
months--;
int lastMonthDays = DateTime.DaysInMonth(currentDate.Year, currentDate.Month - 1);
days = lastMonthDays - date.Day + currentDate.Day;
}
else
{
days = currentDate.Day - date.Day;
}
}
else
{
months = currentDate.Month - date.Month;
if (currentDate.Day < date.Day)
{
months--;
int lastMonthDays = DateTime.DaysInMonth(currentDate.Year, currentDate.Month - 1);
days = lastMonthDays - date.Day + currentDate.Day;
}
else
{
days = currentDate.Day - date.Day;
}
}
//return new Age(years, months, days);
//// แปลงเป็นอายุในรูปแบบวันที่
//int years = (int)(age.Days / 365.25) + plusYear - subtractYear;
//int months = (int)((age.Days % 365.25) / 30.436875);
//int days = (int)((age.Days % 365.25) % 30.436875);
return $"{years} ปี {months} เดือน {days} วัน";
}
catch
{
throw;
}
}
public static int CalculateAge(this DateTime date, int plusYear = 0, int subtractYear = 0)
{
try
{
var currentDate = DateTime.Now;
var age = currentDate - date;
// แปลงเป็นอายุในรูปแบบวันที่
int years = (int)(age.Days / 365.25) + plusYear - subtractYear;
return years;
}
catch
{
throw;
}
}
public static int CalculateGovAge(this DateTime appointDate, int plusYear = 0, int subtractYear = 0)
{
if (DateTime.Now.Month - appointDate.Month >= 6)
return (DateTime.Now.Year - appointDate.Year) + 1 + plusYear - subtractYear;
else
return (DateTime.Now.Year - appointDate.Year) + plusYear - subtractYear;
}
public static string CalculateGovAgeStr(this DateTime appointDate, int plusYear = 0, int subtractYear = 0)
{
var d2 = DateTime.Now;
TimeSpan sp = d2.Subtract(appointDate);
var alldays = sp.Days + ((plusYear - subtractYear) * 365);
int yy = alldays / 365;
int mm = (alldays - (yy * 365)) / 30;
int dd = (alldays - (yy * 365) - (mm * 30));
var sb = new StringBuilder();
sb.Clear();
sb.Append(yy == 0 ? "" : $"{yy} ปี ");
sb.Append(mm == 0 ? "" : $"{mm} เดือน ");
sb.Append(dd == 0 ? "" : $"{dd} วัน ");
return sb.ToString();
}
public static string CalculateGovAgeInYear(this DateTime appointDate, int plusYear = 0, int subtractYear = 0)
{
var d2 = DateTime.Now;
TimeSpan sp = d2.Subtract(appointDate);
var alldays = sp.Days + ((plusYear - subtractYear) * 365);
int yy = alldays / 365;
return yy.ToString();
}
public static int GetDifferenceInYears(this DateTime startDate, DateTime endDate)
{
int finalResult = 0;
const int daysInYear = 365;
//DateTime endDate = DateTime.Now;
TimeSpan timeSpan = endDate - startDate;
if (timeSpan.TotalDays > 365)
{
finalResult = (int)Math.Round((timeSpan.TotalDays / daysInYear), MidpointRounding.ToEven);
}
return finalResult;
}
public static DateTime CalculateRetireDate(this DateTime birthDate)
{
var dd = birthDate.Day;
var mm = birthDate.Month;
var yy = birthDate.Year;
var g1 = true;
switch (mm)
{
case 10: if (dd >= 2) g1 = false; break;
case 11:
case 12: g1 = false; break;
}
if (g1)
return new DateTime(yy + 60, 9, 30);
else
return new DateTime(yy + 61, 9, 30);
}
public static bool IsBetween(this DateTime now, TimeSpan start, TimeSpan end)
{
var time = now.TimeOfDay;
// Scenario 1: If the start time and the end time are in the same day.
if (start <= end)
return time >= start && time <= end;
// Scenario 2: The start time and end time is on different days.
return time >= start || time <= end;
}
public static string CalculateBetweenDate(this DateTime startDate, DateTime endDate)
{
// var d2 = DateTime.Now;
TimeSpan sp = endDate.Subtract(startDate);
var alldays = sp.Days;
int yy = alldays / 365;
int mm = (alldays - (yy * 365)) / 30;
int dd = (alldays - (yy * 365) - (mm * 30));
var sb = new StringBuilder();
sb.Clear();
sb.Append(yy == 0 ? "" : $"{yy} ปี ");
sb.Append(mm == 0 ? "" : $"{mm} เดือน ");
sb.Append(dd == 0 ? "" : $"{dd} วัน ");
return sb.ToString();
}
public static string CalculateBetweenDateV2(this DateTime startDate, DateTime endDate)
{
if (startDate == null || endDate == null)
return "-";
DateTime today = endDate;
DateTime birthDate = Convert.ToDateTime(startDate).AddDays(-1);
int years = new DateTime(endDate.Subtract(birthDate).Ticks).Year - 1;
DateTime pastYearDate = birthDate.AddYears(years);
int months = 0;
for (int i = 1; i <= 12; i++)
{
if (pastYearDate.AddMonths(i) == today)
{
months = i;
break;
}
else if (pastYearDate.AddMonths(i) >= today)
{
months = i - 1;
break;
}
}
int days = today.Subtract(pastYearDate.AddMonths(months)).Days;
if (today.Day < pastYearDate.Day)
{
if (System.DateTime.DaysInMonth(pastYearDate.Year, pastYearDate.Month) > System.DateTime.DaysInMonth(pastYearDate.AddMonths(months).Year, pastYearDate.AddMonths(months).Month))
{
days += 1;
}
if (System.DateTime.DaysInMonth(pastYearDate.Year, pastYearDate.Month) < System.DateTime.DaysInMonth(pastYearDate.AddMonths(months).Year, pastYearDate.AddMonths(months).Month))
{
days -= 1;
}
}
// int Hours = Today.Subtract(PastYearDate).Hours;
// int Minutes = Today.Subtract(PastYearDate).Minutes;
// int Seconds = Today.Subtract(PastYearDate).Seconds;
Console.WriteLine(today);
Console.WriteLine(pastYearDate);
Console.WriteLine(months);
Console.WriteLine(pastYearDate.AddMonths(months));
var sb = new StringBuilder();
sb.Clear();
sb.Append(years == 0 ? "" : $"{years} ปี ");
sb.Append(months == 0 ? "" : $"{months} เดือน ");
sb.Append(days == 0 ? "" : $"{days} วัน ");
return sb.ToString();
}
#endregion
#endregion
}
}

View file

@ -0,0 +1,252 @@
using System;
using System.Text;
namespace BMA.EHR.Domain.Extensions
{
public static class DoubleExtension
{
#region " Fields "
private static string[] _ones =
{
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
};
private static string[] _teens =
{
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen"
};
private static string[] _tens =
{
"",
"ten",
"twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety"
};
// US Nnumbering:
private static string[] _thousands =
{
"",
"thousand",
"million",
"billion",
"trillion",
"quadrillion"
};
#endregion
#region " Methods "
#region " Conversion "
public static string ToNumericText(this double number)
{
return number.ToString("#,##0.00");
}
public static string ToReadText(this double value)
{
string digits, temp;
bool showThousands = false;
bool allZeros = true;
// Use StringBuilder to build result
StringBuilder builder = new StringBuilder();
// Convert integer portion of value to string
digits = ((long)value).ToString();
// Traverse characters in reverse order
for (int i = digits.Length - 1; i >= 0; i--)
{
int ndigit = (int)(digits[i] - '0');
int column = (digits.Length - (i + 1));
// Determine if ones, tens, or hundreds column
switch (column % 3)
{
case 0: // Ones position
showThousands = true;
if (i == 0)
{
// First digit in number (last in loop)
temp = String.Format("{0} ", _ones[ndigit]);
}
else if (digits[i - 1] == '1')
{
// This digit is part of "teen" value
temp = String.Format("{0} ", _teens[ndigit]);
// Skip tens position
i--;
}
else if (ndigit != 0)
{
// Any non-zero digit
temp = String.Format("{0} ", _ones[ndigit]);
}
else
{
// This digit is zero. If digit in tens and hundreds
// column are also zero, don't show "thousands"
temp = String.Empty;
// Test for non-zero digit in this grouping
if (digits[i - 1] != '0' || (i > 1 && digits[i - 2] != '0'))
showThousands = true;
else
showThousands = false;
}
// Show "thousands" if non-zero in grouping
if (showThousands)
{
if (column > 0)
{
temp = String.Format("{0}{1}{2}",
temp,
_thousands[column / 3],
allZeros ? " " : ", ");
}
// Indicate non-zero digit encountered
allZeros = false;
}
builder.Insert(0, temp);
break;
case 1: // Tens column
if (ndigit > 0)
{
temp = String.Format("{0}{1}",
_tens[ndigit],
(digits[i + 1] != '0') ? "-" : " ");
builder.Insert(0, temp);
}
break;
case 2: // Hundreds column
if (ndigit > 0)
{
temp = String.Format("{0} hundred ", _ones[ndigit]);
builder.Insert(0, temp);
}
break;
}
}
// Append fractional portion/cents
double val = (value - (long)value) * 100;
if (val > 0)
builder.AppendFormat("and {0:00}/100", (value - (long)value) * 100);
// Capitalize first letter
return String.Format("{0}{1}",
Char.ToUpper(builder[0]),
builder.ToString(1, builder.Length - 1));
}
#endregion
#region " Round "
public static double RoundUp(this double input)
{
return Math.Ceiling(input);
}
public static double RoundDown(this double input)
{
return Math.Floor(input);
}
public static double RoundUpStang(this double input)
{
string temp = "";
temp = input.ToNumericText();
string[] floating = temp.Split('.');
if (double.Parse(floating[1]) == 0)
{
return input;
}
if (double.Parse(floating[1]) >= 1 && double.Parse(floating[1]) <= 24)
{
return (double.Parse(floating[0])) + 0.25;
}
else if (double.Parse(floating[1]) >= 26 && double.Parse(floating[1]) <= 49)
{
return (double.Parse(floating[0])) + 0.5;
}
else if (double.Parse(floating[1]) >= 51 && double.Parse(floating[1]) <= 74)
{
return (double.Parse(floating[0])) + 0.75;
}
else if (double.Parse(floating[1]) >= 76 && double.Parse(floating[1]) <= 99)
{
return (double.Parse(floating[0])) + 1;
}
else
{
return input;
}
}
public static double RoundDownStang(this double input)
{
string temp = "";
temp = input.ToNumericText();
string[] floating = temp.Split('.');
if (double.Parse(floating[1]) == 0)
{
return input;
}
if (double.Parse(floating[1]) >= 1 && double.Parse(floating[1]) <= 24)
{
return Math.Floor(input);
}
else if (double.Parse(floating[1]) >= 26 && double.Parse(floating[1]) <= 49)
{
return (double.Parse(floating[0])) + 0.25;
}
else if (double.Parse(floating[1]) >= 51 && double.Parse(floating[1]) <= 74)
{
return (double.Parse(floating[0])) + 0.5;
}
else if (double.Parse(floating[1]) >= 76 && double.Parse(floating[1]) <= 99)
{
return (double.Parse(floating[0])) + 0.75;
}
else
{
return input;
}
}
#endregion
#endregion
}
}

View file

@ -0,0 +1,44 @@
namespace BMA.EHR.Domain.Extensions
{
public static class IntegerExtension
{
public static string ToThaiMonth(this int value)
{
switch (value)
{
case 1: return "มกราคม";
case 2: return "กุมภาพันธ์";
case 3: return "มีนาคม";
case 4: return "เมษายน";
case 5: return "พฤษภาคม";
case 6: return "มิถุนายน";
case 7: return "กรกฎาคม";
case 8: return "สิงหาคม";
case 9: return "กันยายน";
case 10: return "ตุลาคม";
case 11: return "พฤศจิกายน";
case 12: return "ธันวาคม";
default: return "";
}
}
public static int ToThaiYear(this int value)
{
if (value < 2400)
return value + 543;
else return value;
}
public static int ToCeYear(this int value)
{
if (value >= 2400)
return value - 543;
else return value;
}
public static string ToNumericText(this int number)
{
return number.ToString("#,##0");
}
}
}

View file

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
namespace BMA.EHR.Domain.Extensions
{
public static class ListExtension
{
#region " Methods "
#region " Convert "
public static DataTable ToDataTable<T>(this List<T> list)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in list)
{
for (int i = 0; i < values.Length; i++)
values[i] = props[i].GetValue(item) ?? DBNull.Value; table.Rows.Add(values);
}
return table;
}
#endregion
#endregion
}
}

View file

@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BMA.EHR.Domain.Extensions
{
public static class ObjectExtension
{
public static bool DeepCompare(this object obj, object another)
{
if (ReferenceEquals(obj, another)) return true;
if ((obj == null) || (another == null)) return false;
//Compare two object's class, return false if they are difference
if (obj.GetType() != another.GetType()) return false;
var result = true;
//Get all properties of obj
//And compare each other
foreach (var property in obj.GetType().GetProperties())
{
var objValue = property.GetValue(obj);
var anotherValue = property.GetValue(another);
if (!objValue.Equals(anotherValue)) result = false;
}
return result;
}
public static bool Compare(this object obj, object another)
{
if (ReferenceEquals(obj, another)) return true;
if ((obj == null) || (another == null)) return false;
if (obj.GetType() != another.GetType()) return false;
//properties: int, double, DateTime, etc, not class
if (!obj.GetType().IsClass) return obj.Equals(another);
var result = true;
foreach (var property in obj.GetType().GetProperties())
{
var objValue = property.GetValue(obj);
var anotherValue = property.GetValue(another);
//Recursion
if (!objValue.DeepCompare(anotherValue)) result = false;
}
return result;
}
}
}

View file

@ -0,0 +1,29 @@
using System;
using System.IO;
namespace BMA.EHR.Domain.Extensions
{
public static class StreamExtension
{
#region " Methods "
#region " Public "
public static string ToBase64(this MemoryStream stream)
{
stream.Seek(0, SeekOrigin.Begin);
byte[] bytes;
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
bytes = memoryStream.ToArray();
}
return Convert.ToBase64String(bytes);
}
#endregion
#endregion
}
}

View file

@ -0,0 +1,301 @@
using System;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
namespace BMA.EHR.Domain.Extensions
{
public enum DateTimeFormat
{
Dmy,
Mdy,
Ymd
}
public static partial class StringExtension
{
#region " Methods "
#region " Utilities "
public static string Format(this string input, int digit)
{
var fmt = $"D{ digit }";
return input.ToInteger().ToString(fmt);
}
public static string RemoveComma(this string value)
{
string ret;
if (value.Contains(","))
{
ret = value.Replace(",", "");
return ret;
}
else
{
if (value != "")
{
return value;
}
else
return "0.00";
}
}
public static string RemoveSpace(this string value)
{
string ret;
if (value.Contains(","))
{
ret = value.Replace(" ", "");
return ret;
}
else
{
if (value != "")
{
return value;
}
else
return "";
}
}
public static string Left(this string input, int length)
{
if (length > 0 && input.Length >= length)
{
return input.Substring(0, length);
}
else
{
return input;
}
}
public static string Right(this string input, int length)
{
if (length > 0 && input.Length >= length)
{
return input.Substring(input.Length - length, length);
}
else
{
return input;
}
}
#endregion
#region " Validation "
public static bool IsDateTime(this string input)
{
try
{
var d = Convert.ToDateTime(input);
return true;
}
catch
{
return false;
}
}
public static bool IsUrl(this string input)
{
if (input.Trim() != "")
{
if ((input.Left(7).ToLower() != "http://") || (input.Left(8).ToLower() != "https://"))
{
input = "http://" + input;
}
Regex reg = new Regex("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&amp;=]*)?");
return reg.Match(input).Success;
}
else
{
return false;
}
}
/// <summary>
/// Determines whether this instance is email.
/// </summary>
/// <param name="input">The input.</param>
/// <returns></returns>
public static bool IsEmail(this string input)
{
if (input.Trim() != "")
{
Regex reg = new Regex("\\w+([-+.\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
return reg.Match(input).Success;
}
else
{
return false;
}
}
/// <summary>
/// Determines whether this instance is numeric.
/// </summary>
/// <param name="input">The input.</param>
/// <returns></returns>
public static bool IsNumeric(this string input)
{
if (input.Length > 0)
{
double tempDouble = (double)(NumberStyles.Number);
return double.TryParse(input, out tempDouble);
}
else
{
return false;
}
}
public static string IsNull(this string input, string value)
{
if (input == null)
return value;
else
return input;
}
#endregion
#region " Conversion "
public static DateTime ToDateTime(this string input, DateTimeFormat format, string seperator = "/")
{
try
{
var dd = input.Split(seperator);
switch (format)
{
case DateTimeFormat.Dmy:
return new DateTime(dd[2].ToInteger().ToCeYear(), dd[1].ToInteger(), dd[0].ToInteger());
case DateTimeFormat.Mdy:
return new DateTime(dd[2].ToInteger().ToCeYear(), dd[0].ToInteger(), dd[1].ToInteger());
case DateTimeFormat.Ymd:
return new DateTime(dd[0].ToInteger().ToCeYear(), dd[1].ToInteger(), dd[2].ToInteger());
default:
return DateTime.MinValue;
}
}
catch
{
return DateTime.MinValue;
}
}
public static string ValueOrBlank(this string input)
{
if (input == null) return "";
if (input == "0")
return "";
else
return input;
}
public static MemoryStream ToMemoryStream(this string base64String)
{
if (base64String == null || base64String == String.Empty) return null;
var bytes = Convert.FromBase64String(base64String);
var stream = new MemoryStream(bytes);
return stream;
}
public static double ToDouble(this string input)
{
if (input == null) return 0.0;
if (input == "") return 0.0;
double ret = 0.0;
input = input.RemoveComma();
if (input.IsNumeric())
{
ret = double.Parse(input);
}
return ret;
}
public static float ToFloat(this string input)
{
if (input == null) return 0F;
if (input == "") return 0F;
float ret = 0F;
input = input.RemoveComma();
if (input.IsNumeric())
{
ret = float.Parse(input);
}
return ret;
}
public static int ToInteger(this string input)
{
if (input == null) return 0;
if (input == "") return 0;
int ret = 0;
input = input.RemoveComma();
int.TryParse(input, out ret);
return ret;
}
public static string ToBlank(this string value)
{
if (value == "0")
return "";
else
return value;
}
public static DateTime ToCeDateTime(this string date)
{
try
{
DateTime dddd;
if (!DateTime.TryParse(date, out dddd))
return DateTime.MinValue;
if (date == "01/01/0001")
return Convert.ToDateTime(date);
string[] dd = date.Split('/');
int yy = 0;
if (dd[2].Length == 2)
yy = dd[2].Left(2).ToInteger() + 2500;
else
yy = dd[2].Left(4).ToInteger();
if (yy >= 2400) yy -= 543;
DateTime birthdate = new DateTime(yy, dd[1].ToInteger(), dd[0].ToInteger());
return birthdate;
}
catch
{
return DateTime.MinValue;
}
}
#endregion
#endregion
}
}

View file

@ -0,0 +1,127 @@
using System;
namespace BMA.EHR.Domain.Extensions
{
public static class TimeSpanExtension
{
#region " To days "
public static double ConvertMillisecondsToDays(this double milliseconds)
{
return TimeSpan.FromMilliseconds(milliseconds).TotalDays;
}
public static double ConvertSecondsToDays(this double seconds)
{
return TimeSpan.FromSeconds(seconds).TotalDays;
}
public static double ConvertMinutesToDays(this double minutes)
{
return TimeSpan.FromMinutes(minutes).TotalDays;
}
public static double ConvertHoursToDays(this double hours)
{
return TimeSpan.FromHours(hours).TotalDays;
}
#endregion
#region " To hours "
public static double ConvertMillisecondsToHours(this double milliseconds)
{
return TimeSpan.FromMilliseconds(milliseconds).TotalHours;
}
public static double ConvertSecondsToHours(this double seconds)
{
return TimeSpan.FromSeconds(seconds).TotalHours;
}
public static double ConvertMinutesToHours(this double minutes)
{
return TimeSpan.FromMinutes(minutes).TotalHours;
}
public static double ConvertDaysToHours(this double days)
{
return TimeSpan.FromHours(days).TotalHours;
}
#endregion
#region " To minutes "
public static double ConvertMillisecondsToMinutes(this double milliseconds)
{
return TimeSpan.FromMilliseconds(milliseconds).TotalMinutes;
}
public static double ConvertSecondsToMinutes(this double seconds)
{
return TimeSpan.FromSeconds(seconds).TotalMinutes;
}
public static double ConvertHoursToMinutes(this double hours)
{
return TimeSpan.FromHours(hours).TotalMinutes;
}
public static double ConvertDaysToMinutes(this double days)
{
return TimeSpan.FromDays(days).TotalMinutes;
}
#endregion
#region " To seconds "
public static double ConvertMillisecondsToSeconds(this double milliseconds)
{
return TimeSpan.FromMilliseconds(milliseconds).TotalSeconds;
}
public static double ConvertMinutesToSeconds(this double minutes)
{
return TimeSpan.FromMinutes(minutes).TotalSeconds;
}
public static double ConvertHoursToSeconds(this double hours)
{
return TimeSpan.FromHours(hours).TotalSeconds;
}
public static double ConvertDaysToSeconds(this double days)
{
return TimeSpan.FromDays(days).TotalSeconds;
}
#endregion
#region " To milliseconds "
public static double ConvertSecondsToMilliseconds(this double seconds)
{
return TimeSpan.FromSeconds(seconds).TotalMilliseconds;
}
public static double ConvertMinutesToMilliseconds(this double minutes)
{
return TimeSpan.FromMinutes(minutes).TotalMilliseconds;
}
public static double ConvertHoursToMilliseconds(this double hours)
{
return TimeSpan.FromHours(hours).TotalMilliseconds;
}
public static double ConvertDaysToMilliseconds(this double days)
{
return TimeSpan.FromDays(days).TotalMilliseconds;
}
#endregion
}
}

View file

@ -8,9 +8,15 @@
public static readonly string DataNotFound = "ไม่พบข้อมูลในระบบ";
#region " Meta Data "
public static readonly string NotAuthorized = "กรุณาเข้าสู่ระบบก่อนใช้งาน!";
public static readonly string DataExist5 = "เนื่องจากมีการกำหนดวันหยุดในการทำงาน 5 วันอยู่";
public static readonly string ForbiddenAccess = "คุณไม่ได้รับอนุญาติให้เข้าใช้งาน!";
public static readonly string ExceptionOccured = "เกิดข้อผิดพลาดขึ้นในระบบ กรุณาติดต่อผู้ดูแลระบบ!";
#region " Meta Data "
public static readonly string DataExist5 = "เนื่องจากมีการกำหนดวันหยุดในการทำงาน 5 วันอยู่";
public static readonly string DataExist6 = "เนื่องจากมีการกำหนดวันหยุดในการทำงาน 6 วันอยู่";

View file

@ -6,11 +6,10 @@ using Microsoft.EntityFrameworkCore;
namespace BMA.EHR.Infrastructure.Persistence
{
public class ApplicationDBContext : DbContext, IApplicationDBContext
{
public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options)
: base(options)
{
}
{
public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
{
}
#region " Prefix "
@ -33,8 +32,8 @@ namespace BMA.EHR.Infrastructure.Persistence
#endregion
public Task<int> SaveChangesAsync()
{
return base.SaveChangesAsync();
}
}
{
return base.SaveChangesAsync();
}
}
}

View file

@ -12,8 +12,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BMA.EHR.Core" Version="1.0.0" />
<PackageReference Include="BMA.EHR.Extensions" Version="1.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.8" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.8" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.1.0" />

View file

@ -1,28 +1,33 @@
using BMA.EHR.Application.Repositories.Prefix;
using BMA.EHR.Domain.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace BMA.EHR.MetaData.Service.Controllers
{
[Route("api/prefix")]
[ApiController]
[Authorize]
public class PrefixController : ControllerBase
{
private readonly PrefixRepository _prefixRepository;
[ApiController]
[Authorize]
public class PrefixController : BaseController
{
private readonly PrefixRepository _prefixRepository;
private readonly IHttpContextAccessor _httpContextAccessor;
public PrefixController(PrefixRepository prefixRepository)
{
_prefixRepository = prefixRepository;
}
public PrefixController(PrefixRepository prefixRepository,
IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
{
_prefixRepository = prefixRepository;
_httpContextAccessor = httpContextAccessor;
}
[HttpGet]
public async Task<IActionResult> GetAllAsync()
{
var data = await _prefixRepository.GetAllAsync();
Console.WriteLine("Logic 1 Start");
[HttpGet]
public async Task<ActionResult<ResponseObject>> GetAllAsync()
{
var data = await _prefixRepository.GetAllAsync();
return Success(data);
}
return Ok(data);
}
}
//[HttpGet("user")]
//public
}
}

View file

@ -1,4 +1,5 @@
using BMA.EHR.Domain.Common;
using BMA.EHR.Domain.Shared;
using System.Net;
namespace BMA.EHR.MetaData.Service
@ -36,12 +37,12 @@ namespace BMA.EHR.MetaData.Service
if (responseModel.Status == (int)HttpStatusCode.Unauthorized)
{
responseModel.Message = "กรุณาเข้าสู่ระบบก่อนใช้งาน!";
responseModel.Message = GlobalMessages.NotAuthorized;
await response.WriteAsJsonAsync(responseModel);
}
if (responseModel.Status == (int)HttpStatusCode.Forbidden)
{
responseModel.Message = "คุณไม่ได้รับอนุญาติให้เข้าใช้งาน!";
responseModel.Message = GlobalMessages.ForbiddenAccess;
await response.WriteAsJsonAsync(responseModel);
}
}
@ -64,14 +65,14 @@ namespace BMA.EHR.MetaData.Service
switch (response.StatusCode)
{
case (int)HttpStatusCode.Unauthorized:
responseModel.Message = "กรุณาเข้าสู่ระบบก่อนใช้งาน!";
responseModel.Message = GlobalMessages.NotAuthorized;
break;
case (int)HttpStatusCode.Forbidden:
responseModel.Message = "คุณไม่ได้รับอนุญาติให้เข้าใช้งาน!";
responseModel.Message = GlobalMessages.ForbiddenAccess;
break;
default:
responseModel.Status = (int)HttpStatusCode.InternalServerError;
responseModel.Message = "เกิดข้อผิดพลาดขึ้นในระบบ กรุณาติดต่อผู้ดูแลระบบ!";
responseModel.Message = GlobalMessages.ExceptionOccured;
break;
}
await response.WriteAsJsonAsync(responseModel);