rethrow sql errors, rewrites context-related helpers into extensions
This commit is contained in:
parent
1a809acbfb
commit
23d5391090
162
Commons.cs
162
Commons.cs
@ -53,32 +53,7 @@ internal static class Commons
|
|||||||
CTS.Cancel();
|
CTS.Cancel();
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
internal static async Task WriteJsonResponse(HttpContext Context, int Status, string Message, object Data)
|
|
||||||
{
|
|
||||||
Context.Response.StatusCode = Status;
|
|
||||||
await Context.Response.WriteAsJsonAsync(new ApiResponse(Status, Message, Data), SGContext.Default.ApiResponse,cancellationToken: CTS.Token);
|
|
||||||
}
|
|
||||||
internal static async Task WriteJsonResponse(HttpContext Context, int Status, string Message)
|
|
||||||
{
|
|
||||||
Context.Response.StatusCode = Status;
|
|
||||||
await Context.Response.WriteAsJsonAsync(new SimpleApiResponse(Status, Message), SGContext.Default.SimpleApiResponse,cancellationToken: CTS.Token);
|
|
||||||
}
|
|
||||||
internal static async Task<bool> RequestValidated(HttpContext Context, int RequiredLevel = 0, string ValidMethod = "GET", bool CheckJson = false)
|
|
||||||
{
|
|
||||||
if (!ValidMethod.Equals(Context.Request.Method,StringComparison.OrdinalIgnoreCase) ||
|
|
||||||
(CheckJson && !Context.Request.HasJsonContentType()))
|
|
||||||
{
|
|
||||||
await WriteJsonResponse(Context, StatusCodes.Status405MethodNotAllowed, "Method Not Allowed.");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!Auth.IsAuthorized(Context, RequiredLevel))
|
|
||||||
{
|
|
||||||
await WriteJsonResponse(Context, StatusCodes.Status401Unauthorized, "Unauthorized.");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
internal static async Task<int> RunNonQueryAsync(string ConnectionString, string SQL, Action<SqlCommand>? Configure = null, CancellationToken Token = default)
|
internal static async Task<int> RunNonQueryAsync(string ConnectionString, string SQL, Action<SqlCommand>? Configure = null, CancellationToken Token = default)
|
||||||
{
|
{
|
||||||
await using SqlConnection Conn = new(ConnectionString);
|
await using SqlConnection Conn = new(ConnectionString);
|
||||||
@ -117,6 +92,7 @@ internal static class Commons
|
|||||||
{
|
{
|
||||||
|
|
||||||
await Tran.RollbackAsync(Token);
|
await Tran.RollbackAsync(Token);
|
||||||
|
throw;
|
||||||
// if (ex.State != 255) throw; //state = 255 is custom sql error, designed just for this purpose of not rethrowing.
|
// if (ex.State != 255) throw; //state = 255 is custom sql error, designed just for this purpose of not rethrowing.
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
@ -143,23 +119,6 @@ internal static class Commons
|
|||||||
uuidBytes[8] = (byte)((uuidBytes[8] & 0x3F) | 0x80); // Set variant to 10xx
|
uuidBytes[8] = (byte)((uuidBytes[8] & 0x3F) | 0x80); // Set variant to 10xx
|
||||||
return Convert.ToHexString(uuidBytes).ToLower().Insert(8, "-").Insert(13, "-").Insert(18, "-").Insert(23, "-");
|
return Convert.ToHexString(uuidBytes).ToLower().Insert(8, "-").Insert(13, "-").Insert(18, "-").Insert(23, "-");
|
||||||
}
|
}
|
||||||
internal static async Task<Dictionary<string, JsonElement>?> TryGetBodyJsonAsync(HttpContext Context, string[] Keys, CancellationToken Token)
|
|
||||||
{
|
|
||||||
using JsonDocument BodyDoc = await JsonDocument.ParseAsync(Context.Request.Body,cancellationToken: Token);
|
|
||||||
JsonElement Element = BodyDoc.RootElement;
|
|
||||||
Dictionary<string, JsonElement>? Result = new(StringComparer.OrdinalIgnoreCase);
|
|
||||||
foreach (string Key in Keys)
|
|
||||||
{
|
|
||||||
if (!Element.TryGetProperty(Key, out JsonElement Value))
|
|
||||||
{
|
|
||||||
await WriteJsonResponse(Context, StatusCodes.Status400BadRequest,
|
|
||||||
"Bad Request. One or more required properties were not received.");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
Result[Key] = Value.Clone();
|
|
||||||
}
|
|
||||||
return Result;
|
|
||||||
}
|
|
||||||
internal static Dictionary<string, JsonElement>? JsonElementToDict(JsonElement Element, string[] Keys)
|
internal static Dictionary<string, JsonElement>? JsonElementToDict(JsonElement Element, string[] Keys)
|
||||||
{
|
{
|
||||||
Dictionary<string, JsonElement>? Result = new(StringComparer.OrdinalIgnoreCase);
|
Dictionary<string, JsonElement>? Result = new(StringComparer.OrdinalIgnoreCase);
|
||||||
@ -174,7 +133,7 @@ internal static class Commons
|
|||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static async Task<int> UpdateCache()
|
internal static async Task UpdateCache()
|
||||||
{
|
{
|
||||||
Console.WriteLine("Updating app cache.");
|
Console.WriteLine("Updating app cache.");
|
||||||
Console.Write(" Caching User Accounts... ");
|
Console.Write(" Caching User Accounts... ");
|
||||||
@ -188,6 +147,8 @@ internal static class Commons
|
|||||||
_ = UserAccounts.TryAdd((string)URead["uname"], new User((string)URead["uname"],(string)URead["name"],(string)URead["pass"],(byte)URead["level"],(bool)URead["active"]));
|
_ = UserAccounts.TryAdd((string)URead["uname"], new User((string)URead["uname"],(string)URead["name"],(string)URead["pass"],(byte)URead["level"],(bool)URead["active"]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Console.WriteLine("Done.");
|
||||||
|
Console.Write(" Caching Unit Kerja... ");
|
||||||
FComm.CommandText = "SELECT * FROM deployment";
|
FComm.CommandText = "SELECT * FROM deployment";
|
||||||
await using (SqlDataReader SRead = await FComm.ExecuteReaderAsync(CTS.Token).ConfigureAwait(false))
|
await using (SqlDataReader SRead = await FComm.ExecuteReaderAsync(CTS.Token).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
@ -196,6 +157,8 @@ internal static class Commons
|
|||||||
(string)r["unitkerja"]
|
(string)r["unitkerja"]
|
||||||
),CTS.Token);
|
),CTS.Token);
|
||||||
}
|
}
|
||||||
|
Console.WriteLine("Done.");
|
||||||
|
Console.Write(" Caching Agents Info... ");
|
||||||
FComm.CommandText = "SELECT * FROM agents";
|
FComm.CommandText = "SELECT * FROM agents";
|
||||||
await using (SqlDataReader SRead = await FComm.ExecuteReaderAsync(CTS.Token).ConfigureAwait(false))
|
await using (SqlDataReader SRead = await FComm.ExecuteReaderAsync(CTS.Token).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
@ -213,70 +176,9 @@ internal static class Commons
|
|||||||
r["photourl"] == DBNull.Value ? null : (string)r["photourl"]
|
r["photourl"] == DBNull.Value ? null : (string)r["photourl"]
|
||||||
),CTS.Token);
|
),CTS.Token);
|
||||||
}
|
}
|
||||||
// FComm.CommandText = "SELECT shift_sched.*, shifts.name FROM shifts LEFT JOIN shift_sched ON shifts.shiftid = shift_sched.shiftid ORDER BY shifts.shiftid, [day]";
|
|
||||||
// await using (SqlDataReader SRead = await FComm.ExecuteReaderAsync(CTS.Token).ConfigureAwait(false))
|
|
||||||
// {
|
|
||||||
// ShiftSched = await SRead.ToListAsync<ShiftSchedEntry>(r=>new(
|
|
||||||
// (byte)r["shiftid"],
|
|
||||||
// (string)r["name"],
|
|
||||||
// (byte)r["schedid"],
|
|
||||||
// (byte)r["day"],
|
|
||||||
// TimeOnly.FromTimeSpan((TimeSpan)r["start"]),
|
|
||||||
// TimeOnly.FromTimeSpan((TimeSpan)r["end"])
|
|
||||||
// ),CTS.Token);
|
|
||||||
// }
|
|
||||||
Console.WriteLine("Done.");
|
Console.WriteLine("Done.");
|
||||||
Console.WriteLine("App cache updated.");
|
Console.WriteLine("App cache updated.");
|
||||||
return 0;
|
return;
|
||||||
// FComm.CommandText = "SELECT shift_sched.*, shifts.name FROM shifts LEFT JOIN shift_sched ON shifts.shiftid = shift_sched.shiftid ORDER BY shifts.shiftid, [day]";
|
|
||||||
// await using (SqlDataReader SRead = await FComm.ExecuteReaderAsync(CTS.Token).ConfigureAwait(false))
|
|
||||||
// {
|
|
||||||
// ShiftSched = await SRead.ToListAsync<ShiftSchedEntry>(r=>new(
|
|
||||||
// (byte)r["shiftid"],
|
|
||||||
// (string)r["name"],
|
|
||||||
// (byte)r["schedid"],
|
|
||||||
// (byte)r["day"],
|
|
||||||
// TimeOnly.FromTimeSpan((TimeSpan)r["start"]),
|
|
||||||
// TimeOnly.FromTimeSpan((TimeSpan)r["end"])
|
|
||||||
// ),CTS.Token);
|
|
||||||
// }
|
|
||||||
// FComm.CommandText = "SELECT tariffs.*, tariff_sched.schedid, tariff_sched.amount FROM tariffs LEFT JOIN tariff_sched ON tariffs.tariffid = tariff_sched.tariffid ORDER BY tariffs.tariffid";
|
|
||||||
// await using (SqlDataReader TRead = await FComm.ExecuteReaderAsync(CTS.Token).ConfigureAwait(false))
|
|
||||||
// {
|
|
||||||
// TariffSched = await TRead.ToListAsync<TariffSchedEntry>(r=>new(
|
|
||||||
// (byte)r["tariffid"],
|
|
||||||
// (string)r["name"],
|
|
||||||
// (bool)r["active"],
|
|
||||||
// r["schedid"] == DBNull.Value ? null : (byte)r["schedid"],
|
|
||||||
// r["amount"] == DBNull.Value ? null : (int)r["amount"]
|
|
||||||
// ),CTS.Token);
|
|
||||||
// }
|
|
||||||
// FComm.CommandText = "SELECT * FROM charges";
|
|
||||||
// await using (SqlDataReader CRead = await FComm.ExecuteReaderAsync(CTS.Token).ConfigureAwait(false))
|
|
||||||
// {
|
|
||||||
// Charges = await CRead.ToListAsync<Charge>(r=>new(
|
|
||||||
// (byte)r["chargid"],
|
|
||||||
// (string)r["name"],
|
|
||||||
// r["percentage"] == DBNull.Value ? null : (byte)r["percentage"],
|
|
||||||
// r["amount"] == DBNull.Value ? null : (int)r["amount"]
|
|
||||||
// ),CTS.Token);
|
|
||||||
// }
|
|
||||||
// FComm.CommandText = "SELECT * FROM packview";
|
|
||||||
// await using (SqlDataReader PRead = await FComm.ExecuteReaderAsync(CTS.Token).ConfigureAwait(false))
|
|
||||||
// {
|
|
||||||
// Packages = await PRead.ToListAsync<PackItem>(r=>new(
|
|
||||||
// (byte)r["packid"],
|
|
||||||
// (string)r["name"],
|
|
||||||
// (short)r["durinmin"],
|
|
||||||
// (int)r["price"],
|
|
||||||
// (byte)r["shiftid"],
|
|
||||||
// (string)r["shift"],
|
|
||||||
// (byte)r["schedid"],
|
|
||||||
// (byte)r["day"],
|
|
||||||
// (bool)r["active"]
|
|
||||||
// ), CTS.Token);
|
|
||||||
// }
|
|
||||||
// EventsMarker.CacheUpdates = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString("X");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -334,7 +236,7 @@ internal static class DataReaderExtensions
|
|||||||
Func<SqlDataReader, T> map,
|
Func<SqlDataReader, T> map,
|
||||||
CancellationToken cancellationToken = default)
|
CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var list = new List<T>();
|
List<T> list = [];
|
||||||
while (await reader.ReadAsync(cancellationToken))
|
while (await reader.ReadAsync(cancellationToken))
|
||||||
{
|
{
|
||||||
list.Add(map(reader));
|
list.Add(map(reader));
|
||||||
@ -342,6 +244,52 @@ internal static class DataReaderExtensions
|
|||||||
return list;
|
return list;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
internal static class HttpContextExtensions
|
||||||
|
{
|
||||||
|
internal static async Task<bool> RequestValidated(this HttpContext Context, int RequiredLevel = 0, string ValidMethod = "GET", bool CheckJson = false)
|
||||||
|
{
|
||||||
|
if (!ValidMethod.Equals(Context.Request.Method, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
(CheckJson && !Context.Request.HasJsonContentType()))
|
||||||
|
{
|
||||||
|
await Context.WriteJsonResponse(StatusCodes.Status405MethodNotAllowed, "Method Not Allowed.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Auth.IsAuthorized(Context, RequiredLevel))
|
||||||
|
{
|
||||||
|
await Context.WriteJsonResponse(StatusCodes.Status401Unauthorized, "Unauthorized.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
internal static async Task WriteJsonResponse(this HttpContext Context, int Status, string Message, object Data)
|
||||||
|
{
|
||||||
|
Context.Response.StatusCode = Status;
|
||||||
|
await Context.Response.WriteAsJsonAsync(new ApiResponse(Status, Message, Data), SGContext.Default.ApiResponse, cancellationToken: CTS.Token);
|
||||||
|
}
|
||||||
|
internal static async Task WriteJsonResponse(this HttpContext Context, int Status, string Message = "")
|
||||||
|
{
|
||||||
|
Context.Response.StatusCode = Status;
|
||||||
|
await Context.Response.WriteAsJsonAsync(new SimpleApiResponse(Status, Message), SGContext.Default.SimpleApiResponse, cancellationToken: CTS.Token);
|
||||||
|
}
|
||||||
|
internal static async Task<Dictionary<string, JsonElement>?> TryGetBodyJsonAsync(this HttpContext Context, string[] Keys, CancellationToken Token)
|
||||||
|
{
|
||||||
|
using JsonDocument BodyDoc = await JsonDocument.ParseAsync(Context.Request.Body,cancellationToken: Token);
|
||||||
|
JsonElement Element = BodyDoc.RootElement;
|
||||||
|
Dictionary<string, JsonElement>? Result = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
foreach (string Key in Keys)
|
||||||
|
{
|
||||||
|
if (!Element.TryGetProperty(Key, out JsonElement Value))
|
||||||
|
{
|
||||||
|
await Context.WriteJsonResponse(StatusCodes.Status400BadRequest,
|
||||||
|
"Bad Request. One or more required properties were not received.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Result[Key] = Value.Clone();
|
||||||
|
}
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
}
|
||||||
public static class Crc32
|
public static class Crc32
|
||||||
{
|
{
|
||||||
static readonly uint[] Table;
|
static readonly uint[] Table;
|
||||||
|
Loading…
x
Reference in New Issue
Block a user