Refactor to use target-typed new and inline object initializers for cleaner and more concise code. Remove redundant static readonly Utf8Encoding instances in favor of Encoding.UTF8.

This commit is contained in:
2025-07-29 04:45:13 +02:00
parent b7b7c472af
commit ef9c2b97a2
17 changed files with 46 additions and 53 deletions

View File

@@ -79,7 +79,7 @@ public class AspnetCoreWebContext : IWebContext
_requestForm = _context.Request.Form
.ToDictionary(p => p.Key, p => p.Value[0]);
}
else { _requestForm = new Dictionary<string, string?>(); }
else { _requestForm = new(); }
}
return _requestForm;
@@ -129,7 +129,7 @@ public class AspnetCoreWebContext : IWebContext
_context.Response.Cookies.Append(
key: cookieName,
value: value,
options: new CookieOptions { Expires = expiration, HttpOnly = httpOnly, Secure = secure, }
options: new() { Expires = expiration, HttpOnly = httpOnly, Secure = secure, }
);
}

View File

@@ -7,8 +7,8 @@ public static class DefaultMain
{
public static void WebFormCoreMain(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
app.UseGlobalRouterMiddleware(builder.Environment);

View File

@@ -28,7 +28,7 @@ public class Bundler
if (_assembly == null || string.IsNullOrEmpty(_assemblyNamespace))
{
_assemblyFiles = new List<string>();
_assemblyFiles = new();
return _assemblyFiles;
}
@@ -46,17 +46,17 @@ public class Bundler
if (_absolutePath == null || string.IsNullOrEmpty(_absolutePath))
{
_absoluteFiles = new List<string>();
_absoluteFiles = new();
return _absoluteFiles;
}
if (Directory.Exists(_absolutePath) == false)
{
_absoluteFiles = new List<string>();
_absoluteFiles = new();
return _absoluteFiles;
}
DirectoryInfo dir = new DirectoryInfo(_absolutePath);
DirectoryInfo dir = new(_absolutePath);
FileInfo[] files = dir.GetFiles();
_absoluteFiles = files.OrderBy(file => file.FullName).Select(file2 => file2.FullName).ToList();
return _absoluteFiles;
@@ -78,11 +78,9 @@ public class Bundler
#region Public methods
private static readonly Encoding Utf8Encoding = new UTF8Encoding();
public void WriteResponse(IWebContext context, string contentType)
{
StringWriter textWriter = new StringWriter();
StringWriter textWriter = new();
context.ResponseContentType = contentType;
foreach (string fileName in AssemblyFiles)
{
@@ -103,7 +101,7 @@ public class Bundler
textWriter.Write("\n\n");
}
byte[] byteObject = Utf8Encoding.GetBytes(textWriter.ToString());
byte[] byteObject = Encoding.UTF8.GetBytes(textWriter.ToString());
context.ResponseWriteBin(byteObject);
}

View File

@@ -26,13 +26,11 @@ public static class ExtensionMethods
return string.Empty;
}
private static readonly Encoding Utf8Encoding = new UTF8Encoding();
public static void ResponseObject(this IWebContext context, object obj, string contentType = "text/json")
{
context.ResponseContentType = contentType;
string strObject = JsonWriter.WriteObject(obj);
byte[] byteObject = Utf8Encoding.GetBytes(strObject);
byte[] byteObject = Encoding.UTF8.GetBytes(strObject);
context.ResponseWriteBin(byteObject);
}

View File

@@ -14,7 +14,7 @@ public static class GlobalErrorHandler
{
context.ResponseStatusCode = 500;
StringBuilder sbOutput = new StringBuilder();
StringBuilder sbOutput = new();
sbOutput.Append("<h2>Internal error</h2>");
Exception? exAux = ex;
while (exAux != null)

View File

@@ -26,7 +26,7 @@ public class GlobalRouter
else
{
// TODO: FrmNotFound
throw new Exception($"NotFound: {path}");
throw new($"NotFound: {path}");
}
}
@@ -34,7 +34,7 @@ public class GlobalRouter
if (handler == null)
{
// TODO: FrmNotFound
throw new Exception($"NotFound: {path}");
throw new($"NotFound: {path}");
}
// Use handler

View File

@@ -26,9 +26,9 @@ public static class MultiLang
private static void InitializeLiterals()
{
_literals = new Dictionary<string, Dictionary<string, object>?>();
_literals = new();
JsonParser jsonParser = new JsonParser();
JsonParser jsonParser = new();
foreach (string lang in new[] { "en", "es" })
{
string filePath = GetPrivatePath("Resources", $"Literals.{lang}.json");

View File

@@ -12,7 +12,7 @@ public static class ObjectActivator
{
lock (Creators)
{
if (Creators.TryGetValue(type, out var creator)) { return creator; }
if (Creators.TryGetValue(type, out Func<object>? creator)) { return creator; }
NewExpression newExp = Expression.New(type);
LambdaExpression lambda = Expression.Lambda(typeof(Func<object>), newExp);

View File

@@ -8,7 +8,7 @@ public class ScriptsBundler : IHttpHandler
public void ProcessRequest(IWebContext context)
{
Bundler bundler = new Bundler(
Bundler bundler = new(
assembly: Assembly.GetExecutingAssembly(),
assemblyNamespace: "Scripts",
absolutePath: ServerHelpers.MapContentPath("Scripts")

View File

@@ -21,7 +21,7 @@ public static class ServerHelpers
StringBuilder sbResult = new();
foreach (var ch in text)
foreach (char ch in text)
{
switch (ch)
{
@@ -64,7 +64,7 @@ public static class ServerHelpers
StringBuilder sbResult = new();
foreach (var ch in text)
foreach (char ch in text)
{
if (ch == ' ') { sbResult.Append('+'); }
else if (IsUrlSafe(ch) == false)

View File

@@ -8,7 +8,7 @@ public class StylesBundler : IHttpHandler
public void ProcessRequest(IWebContext context)
{
Bundler bundler = new Bundler(
Bundler bundler = new(
assembly: Assembly.GetExecutingAssembly(),
assemblyNamespace: "Styles",
absolutePath: ServerHelpers.MapContentPath("Styles")

View File

@@ -65,7 +65,7 @@ public class CTextBox : Control, INamingContainer, IValidableControl
{
if (KeepSize)
{
_hidSize = new HiddenField();
_hidSize = new();
Controls.Add(_hidSize);
}
@@ -75,12 +75,12 @@ public class CTextBox : Control, INamingContainer, IValidableControl
{ "txtContent", _txtContent.ClientID }, { "hidSize", _hidSize?.ClientID ?? string.Empty },
{ "keepSize", KeepSize },
};
StringBuilder sbCfg = new StringBuilder();
StringBuilder sbCfg = new();
sbCfg.AppendFormat("<script>\n");
sbCfg.Append($"var {strCfgName} = {JsonWriter.WriteObject(cfg)};\n");
sbCfg.Append($"CTextBox_Multiline_Init({strCfgName});\n");
sbCfg.AppendFormat("</script>\n");
LiteralControl liScript = new LiteralControl(sbCfg.ToString());
LiteralControl liScript = new(sbCfg.ToString());
Controls.Add(liScript);
}
}
@@ -120,7 +120,7 @@ public class CTextBox : Control, INamingContainer, IValidableControl
{
if (string.IsNullOrEmpty(_hidSize?.Value)) { return null; }
JsonParser jsonParser = new JsonParser();
JsonParser jsonParser = new();
Dictionary<string, object>? sizeObj = jsonParser.Parse(_hidSize?.Value) as Dictionary<string, object>;
if (sizeObj == null) { return null; }
@@ -141,11 +141,11 @@ public class CTextBox : Control, INamingContainer, IValidableControl
Dictionary<string, object?>? sizeObj = null;
if (string.IsNullOrEmpty(_hidSize?.Value) == false)
{
JsonParser jsonParser = new JsonParser();
JsonParser jsonParser = new();
sizeObj = jsonParser.Parse(_hidSize?.Value) as Dictionary<string, object?>;
}
sizeObj ??= new Dictionary<string, object?> { { "height", null }, { "width", null }, { "scrollTop", null }, };
sizeObj ??= new() { { "height", null }, { "width", null }, { "scrollTop", null }, };
sizeObj["height"] = height;
if (_hidSize != null) { _hidSize.Value = JsonWriter.WriteObject(sizeObj); }

View File

@@ -81,7 +81,7 @@ public class Control
public ControlCollection Controls
{
get { return _controls ??= new ControlCollection(this); }
get { return _controls ??= new(this); }
}
private Page? _page;
@@ -179,7 +179,7 @@ public class Control
protected List<Control> ChildsOfType<T>(List<Control>? controls = null)
{
controls ??= new List<Control>();
controls ??= new();
if (this is T) { controls.Add(this); }

View File

@@ -6,7 +6,7 @@ public static class FormUtils
{
public static Control CreatePanel(string cssClass, Control? ctrl = null)
{
Panel pnl = new Panel();
Panel pnl = new();
if (ctrl != null) { pnl.Controls.Add(ctrl); }
if (string.IsNullOrEmpty(cssClass) == false) { pnl.CssClass = cssClass; }
@@ -16,18 +16,18 @@ public static class FormUtils
public static Control CreateField(string label, Control fieldControl)
{
Panel pnlRow = new Panel { CssClass = "formRow" };
Panel pnlRow = new() { CssClass = "formRow" };
Panel pnlLabelContainer = new Panel { CssClass = "formLabel width25pc" };
Panel pnlLabelContainer = new() { CssClass = "formLabel width25pc" };
pnlRow.Controls.Add(pnlLabelContainer);
if (string.IsNullOrEmpty(label) == false)
{
Label lblField = new Label { Text = label };
Label lblField = new() { Text = label };
pnlLabelContainer.Controls.Add(lblField);
}
Panel pnlFieldContainer = new Panel { CssClass = "formField width75pc" };
Panel pnlFieldContainer = new() { CssClass = "formField width75pc" };
pnlRow.Controls.Add(pnlFieldContainer);
pnlFieldContainer.Controls.Add(fieldControl);

View File

@@ -31,25 +31,24 @@ public class FrmError : PageCommon
{
Title = "Application Error";
Label lblErrorTitle = new Label { Text = Title, Tag = "h2" };
Label lblErrorTitle = new() { Text = Title, Tag = "h2" };
Controls.Add(lblErrorTitle);
Exception? exAux = (Exception?)_ex;
//if (exAux is HttpUnhandledException && exAux.InnerException != null) { exAux = exAux.InnerException; }
while (exAux != null)
{
LiteralControl lblMessage =
new LiteralControl($"<p><b>Message:</b> {HttpUtility.HtmlEncode(exAux.Message)}</p>");
LiteralControl lblMessage = new($"<p><b>Message:</b> {HttpUtility.HtmlEncode(exAux.Message)}</p>");
Controls.Add(lblMessage);
LiteralControl lblStacktraceTitle = new LiteralControl("<p><b>Stacktrace:</b></p>");
LiteralControl lblStacktraceTitle = new("<p><b>Stacktrace:</b></p>");
Controls.Add(lblStacktraceTitle);
Panel pnlStacktrace = new Panel
Panel pnlStacktrace = new()
{
CssClass = "divCode"
};
Controls.Add(pnlStacktrace);
LiteralControl litStackTrace = new LiteralControl(
LiteralControl litStackTrace = new(
$"<pre><code>{HttpUtility.HtmlEncode(exAux.StackTrace)}</code></pre>");
pnlStacktrace.Controls.Add(litStackTrace);

View File

@@ -13,8 +13,6 @@ public class Page : Control, IHttpHandler
public IWebContext? Context { get; private set; }
private static readonly Encoding Utf8Encoding = new UTF8Encoding();
public void ProcessRequest(IWebContext context)
{
try
@@ -56,7 +54,7 @@ public class Page : Control, IHttpHandler
if (context.ResponseHasStarted) { return; }
context.ResponseContentType = "text/html";
byte[] byteObject = Utf8Encoding.GetBytes(stringWriter.ToString());
byte[] byteObject = Encoding.UTF8.GetBytes(stringWriter.ToString());
context.ResponseWriteBin(byteObject);
}
catch (Exception ex)

View File

@@ -78,10 +78,10 @@ public class PageCommon : Page
{
//Context.Response.Charset = Encoding.UTF8.WebName;
var doctype = new LiteralControl("<!DOCTYPE html>\n");
LiteralControl doctype = new("<!DOCTYPE html>\n");
base.Controls.Add(doctype);
var html = new HtmlGenericControl("html");
HtmlGenericControl html = new("html");
base.Controls.Add(html);
html.Controls.Add(_head);
@@ -109,13 +109,13 @@ public class PageCommon : Page
html.Controls.Add(_body);
_body.Controls.Add(_form);
var pnlHeader = new Panel { CssClass = "divHeader" };
Panel pnlHeader = new() { CssClass = "divHeader" };
_form.Controls.Add(pnlHeader);
HyperLink lnkTitle = new HyperLink { NavigateUrl = "." };
HyperLink lnkTitle = new() { NavigateUrl = "." };
pnlHeader.Controls.Add(lnkTitle);
var lblTitle = new Label { Text = GlobalConfig.Get().Title, Tag = "h1" };
Label lblTitle = new() { Text = GlobalConfig.Get().Title, Tag = "h1" };
lnkTitle.Controls.Add(lblTitle);
_btnPostback.ID = "btnPostback";
@@ -123,7 +123,7 @@ public class PageCommon : Page
pnlHeader.Controls.Add(_btnPostback);
_btnPostback.Style.Add("display", "none");
var pnlUserInfo = new Panel { CssClass = "divUserInfo" };
Panel pnlUserInfo = new() { CssClass = "divUserInfo" };
pnlHeader.Controls.Add(pnlUserInfo);
_btnLogout.ID = "btnLogout";