From 23d539109004b5469d08679712a8ea002feeee15 Mon Sep 17 00:00:00 2001 From: nugroho Date: Sat, 17 May 2025 03:54:36 +0700 Subject: [PATCH] rethrow sql errors, rewrites context-related helpers into extensions --- Commons.cs | 162 ++++++++++++++++++----------------------------------- 1 file changed, 55 insertions(+), 107 deletions(-) diff --git a/Commons.cs b/Commons.cs index e77649d..c36a550 100644 --- a/Commons.cs +++ b/Commons.cs @@ -53,32 +53,7 @@ internal static class Commons 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 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 RunNonQueryAsync(string ConnectionString, string SQL, Action? Configure = null, CancellationToken Token = default) { await using SqlConnection Conn = new(ConnectionString); @@ -117,6 +92,7 @@ internal static class Commons { await Tran.RollbackAsync(Token); + throw; // if (ex.State != 255) throw; //state = 255 is custom sql error, designed just for this purpose of not rethrowing. } catch @@ -143,23 +119,6 @@ internal static class Commons uuidBytes[8] = (byte)((uuidBytes[8] & 0x3F) | 0x80); // Set variant to 10xx return Convert.ToHexString(uuidBytes).ToLower().Insert(8, "-").Insert(13, "-").Insert(18, "-").Insert(23, "-"); } - internal static async Task?> TryGetBodyJsonAsync(HttpContext Context, string[] Keys, CancellationToken Token) - { - using JsonDocument BodyDoc = await JsonDocument.ParseAsync(Context.Request.Body,cancellationToken: Token); - JsonElement Element = BodyDoc.RootElement; - Dictionary? 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? JsonElementToDict(JsonElement Element, string[] Keys) { Dictionary? Result = new(StringComparer.OrdinalIgnoreCase); @@ -174,7 +133,7 @@ internal static class Commons return Result; } - internal static async Task UpdateCache() + internal static async Task UpdateCache() { Console.WriteLine("Updating app cache."); 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"])); } } + Console.WriteLine("Done."); + Console.Write(" Caching Unit Kerja... "); FComm.CommandText = "SELECT * FROM deployment"; await using (SqlDataReader SRead = await FComm.ExecuteReaderAsync(CTS.Token).ConfigureAwait(false)) { @@ -196,6 +157,8 @@ internal static class Commons (string)r["unitkerja"] ),CTS.Token); } + Console.WriteLine("Done."); + Console.Write(" Caching Agents Info... "); FComm.CommandText = "SELECT * FROM agents"; 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"] ),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(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("App cache updated."); - return 0; - // 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(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(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(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(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"); + return; } @@ -334,7 +236,7 @@ internal static class DataReaderExtensions Func map, CancellationToken cancellationToken = default) { - var list = new List(); + List list = []; while (await reader.ReadAsync(cancellationToken)) { list.Add(map(reader)); @@ -342,6 +244,52 @@ internal static class DataReaderExtensions return list; } } +internal static class HttpContextExtensions +{ + internal static async Task 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?> TryGetBodyJsonAsync(this HttpContext Context, string[] Keys, CancellationToken Token) + { + using JsonDocument BodyDoc = await JsonDocument.ParseAsync(Context.Request.Body,cancellationToken: Token); + JsonElement Element = BodyDoc.RootElement; + Dictionary? 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 { static readonly uint[] Table;