Apply Rider recommendations

This commit is contained in:
2022-05-14 21:03:00 +02:00
parent d3a0bd4ad1
commit bf629a5ebe
34 changed files with 434 additions and 548 deletions

33
VAR.Focus.sln.DotSettings Normal file
View File

@@ -0,0 +1,33 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_EXISTING_EMBEDDED_ARRANGEMENT/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_EXISTING_EXPR_MEMBER_ARRANGEMENT/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_EXISTING_INITIALIZER_ARRANGEMENT/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_EXISTING_INVOCATION_PARENS_ARRANGEMENT/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_EXISTING_PROPERTY_PATTERNS_ARRANGEMENT/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_EXISTING_SWITCH_EXPRESSION_ARRANGEMENT/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_SIMPLE_EMBEDDED_BLOCK_ON_SAME_LINE/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_SIMPLE_METHOD_ON_SINGLE_LINE/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_SIMPLE_SWITCH_EXPRESSION_ON_SINGLE_LINE/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_TYPE_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">IF_OWNER_IS_SINGLE_LINE</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_AFTER_DECLARATION_LPAR/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_AFTER_INVOCATION_LPAR/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_ARGUMENTS_STYLE/@EntryValue">CHOP_IF_LONG</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_BEFORE_BINARY_PATTERN_OP/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_BEFORE_DECLARATION_RPAR/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_BEFORE_INVOCATION_RPAR/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_BEFORE_LINQ_EXPRESSION/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_CHAINED_BINARY_EXPRESSIONS/@EntryValue">CHOP_IF_LONG</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_CHAINED_METHOD_CALLS/@EntryValue">CHOP_IF_LONG</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_ENUM_DECLARATION/@EntryValue">CHOP_IF_LONG</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_SWITCH_EXPRESSION/@EntryValue">CHOP_IF_LONG</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=ID/@EntryIndexedValue">ID</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=OK/@EntryIndexedValue">OK</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SHA/@EntryIndexedValue">SHA</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=TypeParameters/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"&gt;&lt;ExtraRule Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Childs/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=nosniff/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=priv/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Textbox/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Unauthenticate/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Uncacheable/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Validable/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

View File

@@ -11,11 +11,11 @@ namespace VAR.WebFormsCore.Code
{
#region Declarations
private Assembly _assembly = null;
private string _assemblyNamespace = null;
private List<string> _assemblyFiles = null;
private string _absolutePath = null;
private List<string> _absoluteFiles = null;
private readonly Assembly _assembly;
private readonly string _assemblyNamespace;
private List<string> _assemblyFiles;
private readonly string _absolutePath;
private List<string> _absoluteFiles;
#endregion Declarations
@@ -26,11 +26,13 @@ namespace VAR.WebFormsCore.Code
get
{
if (_assemblyFiles != null) { return _assemblyFiles; }
if (_assembly == null || string.IsNullOrEmpty(_assemblyNamespace))
{
_assemblyFiles = new List<string>();
return _assemblyFiles;
}
string assemblyPath = string.Concat(_assembly.GetName().Name, ".", _assemblyNamespace, ".");
_assemblyFiles = _assembly.GetManifestResourceNames().Where(r => r.StartsWith(assemblyPath)).ToList();
return _assemblyFiles;
@@ -48,6 +50,7 @@ namespace VAR.WebFormsCore.Code
_absoluteFiles = new List<string>();
return _absoluteFiles;
}
DirectoryInfo dir = new DirectoryInfo(_absolutePath);
FileInfo[] files = dir.GetFiles();
_absoluteFiles = files.OrderBy(file => file.FullName).Select(file2 => file2.FullName).ToList();
@@ -70,7 +73,7 @@ namespace VAR.WebFormsCore.Code
#region Public methods
private static Encoding _utf8Econding = new UTF8Encoding();
private static readonly Encoding Utf8Encoding = new UTF8Encoding();
public async void WriteResponse(HttpResponse response, string contentType)
{
@@ -79,17 +82,23 @@ namespace VAR.WebFormsCore.Code
foreach (string fileName in AssemblyFiles)
{
Stream resourceStream = _assembly.GetManifestResourceStream(fileName);
string fileContent = new StreamReader(resourceStream).ReadToEnd();
textWriter.Write(fileContent);
if (resourceStream != null)
{
string fileContent = new StreamReader(resourceStream).ReadToEnd();
textWriter.Write(fileContent);
}
textWriter.Write("\n\n");
}
foreach (string fileName in AbsoluteFiles)
{
string fileContent = File.ReadAllText(fileName);
textWriter.Write(fileContent);
textWriter.Write("\n\n");
}
byte[] byteObject = _utf8Econding.GetBytes(textWriter.ToString());
byte[] byteObject = Utf8Encoding.GetBytes(textWriter.ToString());
await response.Body.WriteAsync(byteObject);
}

View File

@@ -15,65 +15,54 @@ namespace VAR.WebFormsCore.Code
{
foreach (string key in context.Request.Form.Keys)
{
if (string.IsNullOrEmpty(key) == false && key == parm)
{
return context.Request.Form[key];
}
if (string.IsNullOrEmpty(key) == false && key == parm) { return context.Request.Form[key]; }
}
}
foreach (string key in context.Request.Query.Keys)
{
if (string.IsNullOrEmpty(key) == false && key == parm)
{
return context.Request.Query[key];
}
if (string.IsNullOrEmpty(key) == false && key == parm) { return context.Request.Query[key]; }
}
return string.Empty;
}
private static Encoding _utf8Econding = new UTF8Encoding();
private static readonly Encoding Utf8Encoding = new UTF8Encoding();
public static void ResponseObject(this HttpContext context, object obj)
{
context.Response.ContentType = "text/json";
string strObject = JsonWriter.WriteObject(obj);
byte[] byteObject = _utf8Econding.GetBytes(strObject);
byte[] byteObject = Utf8Encoding.GetBytes(strObject);
context.Response.Body.WriteAsync(byteObject);
}
public static void SafeSet(this IHeaderDictionary header, string key, string value)
{
if (header.ContainsKey(key))
{
header[key] = value;
}
else
{
header.Add(key, value);
}
if (header.ContainsKey(key)) { header[key] = value; }
else { header.Add(key, value); }
}
public static void SafeDel(this IHeaderDictionary header, string key)
{
if (header.ContainsKey(key))
{
header.Remove(key);
}
if (header.ContainsKey(key)) { header.Remove(key); }
}
public static void PrepareCacheableResponse(this HttpResponse response)
{
const int secondsInDay = 86400;
response.Headers.SafeSet("Cache-Control", string.Format("public, max-age={0}", secondsInDay));
string ExpireDate = DateTime.UtcNow.AddSeconds(secondsInDay).ToString("ddd, dd MMM yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
response.Headers.SafeSet("Expires", ExpireDate + " GMT");
response.Headers.SafeSet("Cache-Control", $"public, max-age={secondsInDay}");
string expireDate = DateTime.UtcNow.AddSeconds(secondsInDay)
.ToString("ddd, dd MMM yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
response.Headers.SafeSet("Expires", expireDate + " GMT");
}
public static void PrepareUncacheableResponse(this HttpResponse response)
{
response.Headers.SafeSet("Cache-Control", "max-age=0, no-cache, no-store");
string ExpireDate = DateTime.UtcNow.AddSeconds(-1500).ToString("ddd, dd MMM yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
response.Headers.SafeSet("Expires", ExpireDate + " GMT");
string expireDate = DateTime.UtcNow.AddSeconds(-1500)
.ToString("ddd, dd MMM yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
response.Headers.SafeSet("Expires", expireDate + " GMT");
}
#endregion HttpContext

View File

@@ -5,24 +5,28 @@ namespace VAR.WebFormsCore.Code
{
public static class GlobalConfig
{
private static IGlobalConfig _globalConfig = null;
private static IGlobalConfig _globalConfig;
public static IGlobalConfig Get()
{
if (_globalConfig == null)
{
Type iGlobalConfig = typeof(IGlobalConfig);
Type foundGlobalConfig = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x =>
if (_globalConfig != null) { return _globalConfig; }
Type iGlobalConfig = typeof(IGlobalConfig);
Type foundGlobalConfig = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(
x =>
x.GetTypes()
)
.FirstOrDefault(
x =>
x.IsAbstract == false &&
x.IsInterface == false &&
iGlobalConfig.IsAssignableFrom(x) &&
true)
.FirstOrDefault();
_globalConfig = ObjectActivator.CreateInstance(foundGlobalConfig) as IGlobalConfig;
}
true
);
_globalConfig = ObjectActivator.CreateInstance(foundGlobalConfig) as IGlobalConfig;
return _globalConfig;
}
}

View File

@@ -31,17 +31,18 @@ namespace VAR.WebFormsCore.Code
if (fillResponse > 0)
{
sbOutput.Append("<!--");
for (int i = 0; i < fillResponse; i++)
{
sbOutput.Append("A");
}
for (int i = 0; i < fillResponse; i++) { sbOutput.Append("A"); }
sbOutput.Append("-->");
}
await context.Response.WriteAsync(sbOutput.ToString());
await context.Response.Body.FlushAsync();
}
catch { /* Nom nom nom */ }
catch
{
/* Nom nom nom */
}
}
#endregion Private methods
@@ -58,10 +59,7 @@ namespace VAR.WebFormsCore.Code
frmError.ProcessRequest(context);
await context.Response.Body.FlushAsync();
}
catch
{
await ShowInternalErrorAsync(context, ex);
}
catch { await ShowInternalErrorAsync(context, ex); }
}
#endregion Public methods

View File

@@ -12,13 +12,8 @@ namespace VAR.WebFormsCore.Code
{
public class GlobalRouterMiddleware
{
private readonly RequestDelegate _next;
private readonly IWebHostEnvironment _env;
public GlobalRouterMiddleware(RequestDelegate next, IWebHostEnvironment env)
{
_next = next;
_env = env;
ServerHelpers.SetContentRoot(env.ContentRootPath);
}
@@ -46,26 +41,15 @@ namespace VAR.WebFormsCore.Code
await GlobalErrorHandler.HandleErrorAsync(httpContext, ex);
}
}
}
private static bool IsIgnoreException(Exception ex)
{
if (ex is ThreadAbortException)
{
return true;
}
return false;
}
private static bool IsIgnoreException(Exception ex) { return ex is ThreadAbortException; }
private void RouteRequest(HttpContext context)
{
string path = context.Request.Path;
string file = Path.GetFileName(path);
if (string.IsNullOrEmpty(file))
{
file = GlobalConfig.Get().DefaultHandler;
}
if (string.IsNullOrEmpty(file)) { file = GlobalConfig.Get().DefaultHandler; }
// Pass allowed extensions requests
string extension = Path.GetExtension(path).ToLower();
@@ -80,7 +64,7 @@ namespace VAR.WebFormsCore.Code
else
{
// TODO: FrmNotFound
throw new Exception("NotFound");
throw new Exception($"NotFound: {path}");
}
}
@@ -88,33 +72,36 @@ namespace VAR.WebFormsCore.Code
if (handler == null)
{
// TODO: FrmNotFound
throw new Exception("NotFound");
throw new Exception($"NotFound: {path}");
}
// Use handler
handler.ProcessRequest(context);
}
private static Dictionary<string, Type> _handlers = new Dictionary<string, Type>();
private static readonly Dictionary<string, Type> Handlers = new Dictionary<string, Type>();
private static IHttpHandler GetHandler(string typeName)
{
if (string.IsNullOrEmpty(typeName)) { return null; }
Type type = null;
if (_handlers.ContainsKey(typeName))
lock (Handlers)
{
type = _handlers[typeName];
IHttpHandler handler = ObjectActivator.CreateInstance(type) as IHttpHandler;
return handler;
if (Handlers.ContainsKey(typeName))
{
type = Handlers[typeName];
IHttpHandler handler = ObjectActivator.CreateInstance(type) as IHttpHandler;
return handler;
}
}
// Search type on executing assembly
Type[] types;
Assembly asm = Assembly.GetExecutingAssembly();
types = asm.GetTypes();
Type[] types = asm.GetTypes();
foreach (Type typeAux in types)
{
if (typeAux.FullName.EndsWith(typeName))
if (typeAux.FullName?.EndsWith(typeName) == true)
{
type = typeAux;
break;
@@ -124,18 +111,18 @@ namespace VAR.WebFormsCore.Code
// Search type on all loaded assemblies
if (type == null)
{
Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly asmAux in asms)
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly asmAux in assemblies)
{
types = asmAux.GetTypes();
foreach (Type typeAux in types)
{
if (typeAux.FullName.EndsWith(typeName))
{
type = typeAux;
break;
}
if (typeAux.FullName?.EndsWith(typeName) != true) { continue; }
type = typeAux;
break;
}
if (type != null) { break; }
}
}
@@ -146,25 +133,25 @@ namespace VAR.WebFormsCore.Code
IHttpHandler handler = ObjectActivator.CreateInstance(type) as IHttpHandler;
if (handler != null)
{
lock (_handlers)
lock (Handlers)
{
if (_handlers.ContainsKey(typeName) == false)
{
_handlers.Add(typeName, type);
}
if (Handlers.ContainsKey(typeName) == false) { Handlers.Add(typeName, type); }
}
}
return handler;
}
return null;
}
}
public static class GlobalRouterMiddlewareExtensions
{
public static IApplicationBuilder UseGlobalRouterMiddleware(this IApplicationBuilder builder, IWebHostEnvironment env)
public static IApplicationBuilder UseGlobalRouterMiddleware(
this IApplicationBuilder builder,
IWebHostEnvironment env
)
{
return builder.UseMiddleware<GlobalRouterMiddleware>(env);
}

View File

@@ -1,11 +1,10 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.IO;
using VAR.Json;
namespace VAR.WebFormsCore.Code
{
public class MultiLang
public static class MultiLang
{
private static string GetPrivatePath(string baseDir, string fileName)
{
@@ -15,22 +14,24 @@ namespace VAR.WebFormsCore.Code
{
DirectoryInfo dirInfo = Directory.GetParent(currentDir);
if (dirInfo == null) { break; }
currentDir = dirInfo.FullName;
privatePath = Path.Combine(currentDir, baseDir);
}
return Path.Combine(privatePath, fileName);
}
private static Dictionary<string, Dictionary<string, object>> _literals = null;
private static Dictionary<string, Dictionary<string, object>> _literals;
private static void InitializeLiterals()
{
_literals = new Dictionary<string, Dictionary<string, object>>();
JsonParser jsonParser = new JsonParser();
foreach (string lang in new string[] { "en", "es" })
foreach (string lang in new[] {"en", "es"})
{
string filePath = GetPrivatePath("Resources", string.Format("Literals.{0}.json", lang));
string filePath = GetPrivatePath("Resources", $"Literals.{lang}.json");
if (File.Exists(filePath) == false) { continue; }
string strJsonLiteralsLanguage = File.ReadAllText(filePath);
@@ -39,7 +40,7 @@ namespace VAR.WebFormsCore.Code
}
}
private const string _defaultLanguage = "en";
private const string DefaultLanguage = "en";
private static string GetUserLanguage()
{
@@ -71,19 +72,25 @@ namespace VAR.WebFormsCore.Code
// ctx.Items["UserLang"] = userLang;
// return userLang;
//}
return _defaultLanguage;
return DefaultLanguage;
}
public static string GetLiteral(string resource, string culture = null)
{
if (_literals == null) { InitializeLiterals(); }
if (culture == null) { culture = GetUserLanguage(); }
culture ??= GetUserLanguage();
if (_literals == null || _literals.ContainsKey(culture) == false) { return resource; }
Dictionary<string, object> _literalCurrentCulture = _literals[culture];
if (_literalCurrentCulture == null || _literalCurrentCulture.ContainsKey(resource) == false) { return resource; }
return (_literalCurrentCulture[resource] as string) ?? resource;
Dictionary<string, object> literalCurrentCulture = _literals[culture];
if (literalCurrentCulture == null || literalCurrentCulture.ContainsKey(resource) == false)
{
return resource;
}
return (literalCurrentCulture[resource] as string) ?? resource;
}
}
}

View File

@@ -4,26 +4,24 @@ using System.Linq.Expressions;
namespace VAR.WebFormsCore.Code
{
public class ObjectActivator
public static class ObjectActivator
{
private static Dictionary<Type, Func<object>> _creators = new Dictionary<Type, Func<object>>();
private static readonly Dictionary<Type, Func<object>> Creators = new Dictionary<Type, Func<object>>();
public static Func<object> GetLambdaNew(Type type)
private static Func<object> GetLambdaNew(Type type)
{
if (_creators.ContainsKey(type))
lock (Creators)
{
return _creators[type];
}
if (Creators.ContainsKey(type)) { return Creators[type]; }
lock (_creators)
{
NewExpression newExp = Expression.New(type);
LambdaExpression lambda = Expression.Lambda(typeof(Func<object>), newExp);
Func<object> compiledLambdaNew = (Func<object>)lambda.Compile();
Func<object> compiledLambdaNew = (Func<object>) lambda.Compile();
_creators.Add(type, compiledLambdaNew);
Creators.Add(type, compiledLambdaNew);
return Creators[type];
}
return _creators[type];
}
public static object CreateInstance(Type type)

View File

@@ -2,8 +2,6 @@
{
public class Program
{
public static void Main()
{
}
public static void Main() { }
}
}

View File

@@ -12,7 +12,8 @@ namespace VAR.WebFormsCore.Code
Bundler bundler = new Bundler(
assembly: Assembly.GetExecutingAssembly(),
assemblyNamespace: "Scripts",
absolutePath: ServerHelpers.MapContentPath("Scripts"));
absolutePath: ServerHelpers.MapContentPath("Scripts")
);
context.Response.PrepareCacheableResponse();
bundler.WriteResponse(context.Response, "text/javascript");
}

View File

@@ -3,13 +3,10 @@ using System.Text;
namespace VAR.WebFormsCore.Code
{
public class ServerHelpers
public static class ServerHelpers
{
private static string _contentRoot = null;
public static void SetContentRoot(string contentRoot)
{
_contentRoot = contentRoot;
}
private static string _contentRoot;
public static void SetContentRoot(string contentRoot) { _contentRoot = contentRoot; }
public static string MapContentPath(string path)
{
@@ -27,36 +24,18 @@ namespace VAR.WebFormsCore.Code
{
char ch = text[i];
if (ch == '<')
{
sbResult.Append("&lt;");
}
else if (ch == '>')
{
sbResult.Append("&gt;");
}
else if (ch == '"')
{
sbResult.Append("&quot;");
}
else if (ch == '\'')
{
sbResult.Append("&#39;");
}
else if (ch == '&')
{
sbResult.Append("&amp;");
}
if (ch == '<') { sbResult.Append("&lt;"); }
else if (ch == '>') { sbResult.Append("&gt;"); }
else if (ch == '"') { sbResult.Append("&quot;"); }
else if (ch == '\'') { sbResult.Append("&#39;"); }
else if (ch == '&') { sbResult.Append("&amp;"); }
else if (ch > 127)
{
sbResult.Append("&#");
sbResult.Append(((int)ch).ToString(NumberFormatInfo.InvariantInfo));
sbResult.Append(((int) ch).ToString(NumberFormatInfo.InvariantInfo));
sbResult.Append(';');
}
else
{
sbResult.Append(ch);
}
else { sbResult.Append(ch); }
}
return sbResult.ToString();
@@ -72,18 +51,9 @@ namespace VAR.WebFormsCore.Code
{
char ch = text[i];
if (ch == ' ')
{
sbResult.Append('+');
}
else if (IsUrlSafe(ch) == false)
{
sbResult.AppendFormat("%{0:X02}", ch);
}
else
{
sbResult.Append(ch);
}
if (ch == ' ') { sbResult.Append('+'); }
else if (IsUrlSafe(ch) == false) { sbResult.AppendFormat("%{0:X02}", ch); }
else { sbResult.Append(ch); }
}
return sbResult.ToString();
@@ -102,10 +72,7 @@ namespace VAR.WebFormsCore.Code
ch == '*' ||
ch == '(' ||
ch == ')' ||
false)
{
return true;
}
false) { return true; }
return false;
}

View File

@@ -4,9 +4,11 @@ using Microsoft.AspNetCore.Http;
namespace VAR.WebFormsCore.Code
{
public class StaticFileHelper
public static class StaticFileHelper
{
private static Dictionary<string, string> _mimeTypeByExtension = new Dictionary<string, string> { {".aac", "audio/aac"},
private static readonly Dictionary<string, string> MimeTypeByExtension = new Dictionary<string, string>
{
{".aac", "audio/aac"},
{".abw", "application/x-abiword"},
{".arc", "application/octet-stream"},
{".avi", "video/x-msvideo"},
@@ -70,20 +72,14 @@ namespace VAR.WebFormsCore.Code
{
string extension = Path.GetExtension(filePath).ToLower();
string contentType = null;
if (_mimeTypeByExtension.ContainsKey(extension))
{
contentType = _mimeTypeByExtension[extension];
}
if (MimeTypeByExtension.ContainsKey(extension)) { contentType = MimeTypeByExtension[extension]; }
if (string.IsNullOrEmpty(contentType) == false) { context.Response.ContentType = contentType; }
if (string.IsNullOrEmpty(contentType) == false)
{
context.Response.ContentType = contentType;
}
context.Response.PrepareCacheableResponse();
byte[] fileData = File.ReadAllBytes(filePath);
await context.Response.Body.WriteAsync(fileData);
}
}
}

View File

@@ -12,7 +12,8 @@ namespace VAR.WebFormsCore.Code
Bundler bundler = new Bundler(
assembly: Assembly.GetExecutingAssembly(),
assemblyNamespace: "Styles",
absolutePath: ServerHelpers.MapContentPath("Styles"));
absolutePath: ServerHelpers.MapContentPath("Styles")
);
context.Response.PrepareCacheableResponse();
bundler.WriteResponse(context.Response, "text/css");
}

View File

@@ -2,8 +2,8 @@
{
public class Unit
{
private int _value;
private UnitType _unitType;
private readonly int _value;
private readonly UnitType _unitType;
public Unit(int value, UnitType type)
{
@@ -13,15 +13,9 @@
public override string ToString()
{
if (_unitType == UnitType.Pixel)
{
return string.Format("{0}px", _value);
}
if (_unitType == UnitType.Pixel) { return $"{_value}px"; }
if (_unitType == UnitType.Percentaje)
{
return string.Format("{0}%", _value);
}
if (_unitType == UnitType.Percentage) { return $"{_value}%"; }
return string.Empty;
}
@@ -29,7 +23,6 @@
public enum UnitType
{
Pixel,
Percentaje,
Pixel, Percentage,
}
}

View File

@@ -5,18 +5,17 @@ namespace VAR.WebFormsCore.Controls
{
public class Button : Control, IReceivePostbackEvent
{
public Button()
{
CssClass = "button";
}
public Button() { CssClass = "button"; }
private string _text = string.Empty;
public string Text { get { return _text; } set { _text = value; } }
public string Text
{
get => _text;
set => _text = value;
}
private string _commandArgument = string.Empty;
public string CommandArgument { get { return _commandArgument; } set { _commandArgument = value; } }
public string CommandArgument { get; set; } = string.Empty;
public event EventHandler Click;
@@ -32,9 +31,6 @@ namespace VAR.WebFormsCore.Controls
textWriter.Write("</input>");
}
public void ReceivePostBack()
{
Click?.Invoke(this, null);
}
public void ReceivePostBack() { Click?.Invoke(this, EventArgs.Empty); }
}
}

View File

@@ -9,9 +9,9 @@ namespace VAR.WebFormsCore.Controls
{
#region Declarations
private TextBox _txtContent = new TextBox();
private readonly TextBox _txtContent = new TextBox();
private HiddenField _hidSize = null;
private HiddenField _hidSize;
private const string CssClassBase = "textbox";
private string _cssClassExtra = "";
@@ -20,11 +20,11 @@ namespace VAR.WebFormsCore.Controls
private string _placeHolder = string.Empty;
private bool _markedInvalid = false;
private bool _markedInvalid;
private Control _nextFocusOnEnter = null;
private Control _nextFocusOnEnter;
private bool _keepSize = false;
private bool _keepSize;
#endregion Declarations
@@ -32,50 +32,50 @@ namespace VAR.WebFormsCore.Controls
public string CssClassExtra
{
get { return _cssClassExtra; }
set { _cssClassExtra = value; }
get => _cssClassExtra;
set => _cssClassExtra = value;
}
public bool AllowEmpty
{
get { return _allowEmpty; }
set { _allowEmpty = value; }
get => _allowEmpty;
set => _allowEmpty = value;
}
public string PlaceHolder
{
get { return _placeHolder; }
set { _placeHolder = value; }
get => _placeHolder;
set => _placeHolder = value;
}
public bool MarkedInvalid
{
get { return _markedInvalid; }
set { _markedInvalid = value; }
get => _markedInvalid;
set => _markedInvalid = value;
}
public Control NextFocusOnEnter
{
get { return _nextFocusOnEnter; }
set { _nextFocusOnEnter = value; }
get => _nextFocusOnEnter;
set => _nextFocusOnEnter = value;
}
public bool KeepSize
{
get { return _keepSize; }
set { _keepSize = value; }
get => _keepSize;
set => _keepSize = value;
}
public string Text
{
get { return _txtContent.Text; }
set { _txtContent.Text = value; }
get => _txtContent.Text;
set => _txtContent.Text = value;
}
public TextBoxMode TextMode
{
get { return _txtContent.TextMode; }
set { _txtContent.TextMode = value; }
get => _txtContent.TextMode;
init => _txtContent.TextMode = value;
}
#endregion Properties
@@ -100,12 +100,10 @@ namespace VAR.WebFormsCore.Controls
Controls.Add(_hidSize);
}
string strCfgName = string.Format("{0}_cfg", this.ClientID);
string strCfgName = $"{this.ClientID}_cfg";
Dictionary<string, object> cfg = new Dictionary<string, object>
{
{"txtContent", _txtContent.ClientID},
{"hidSize", _hidSize.ClientID},
{"keepSize", _keepSize },
{"txtContent", _txtContent.ClientID}, {"hidSize", _hidSize.ClientID}, {"keepSize", _keepSize},
};
StringBuilder sbCfg = new StringBuilder();
sbCfg.AppendFormat("<script>\n");
@@ -122,12 +120,14 @@ namespace VAR.WebFormsCore.Controls
_txtContent.CssClass = CssClassBase;
if (string.IsNullOrEmpty(_cssClassExtra) == false)
{
_txtContent.CssClass = string.Format("{0} {1}", CssClassBase, _cssClassExtra);
_txtContent.CssClass = $"{CssClassBase} {_cssClassExtra}";
}
if (Page.IsPostBack && (_allowEmpty == false && IsEmpty()) || _markedInvalid)
{
_txtContent.CssClass += " textboxInvalid";
}
_txtContent.Attributes.Add("onchange", "ElementRemoveClass(this, 'textboxInvalid');");
if (string.IsNullOrEmpty(_placeHolder) == false)
@@ -137,9 +137,10 @@ namespace VAR.WebFormsCore.Controls
if (_nextFocusOnEnter != null)
{
_txtContent.Attributes.Add("onkeydown", string.Format(
"if(event.keyCode==13){{document.getElementById('{0}').focus(); return false;}}",
_nextFocusOnEnter.ClientID));
_txtContent.Attributes.Add(
"onkeydown",
$"if(event.keyCode==13){{document.getElementById('{_nextFocusOnEnter.ClientID}').focus(); return false;}}"
);
}
}
@@ -147,28 +148,21 @@ namespace VAR.WebFormsCore.Controls
#region Public methods
public bool IsEmpty()
{
return string.IsNullOrEmpty(_txtContent.Text);
}
private bool IsEmpty() { return string.IsNullOrEmpty(_txtContent.Text); }
public bool IsValid()
{
return _allowEmpty || (string.IsNullOrEmpty(_txtContent.Text) == false);
}
public bool IsValid() { return _allowEmpty || (string.IsNullOrEmpty(_txtContent.Text) == false); }
public int? GetClientsideHeight()
{
if (string.IsNullOrEmpty(_hidSize.Value))
{
return null;
}
if (string.IsNullOrEmpty(_hidSize.Value)) { return null; }
JsonParser jsonParser = new JsonParser();
Dictionary<string, object> sizeObj = jsonParser.Parse(_hidSize.Value) as Dictionary<string, object>;
if (sizeObj == null) { return null; }
if (sizeObj.ContainsKey("height") == false) { return null; }
return (int)sizeObj["height"];
return (int) sizeObj["height"];
}
public void SetClientsideHeight(int? height)
@@ -178,7 +172,8 @@ namespace VAR.WebFormsCore.Controls
_hidSize.Value = string.Empty;
return;
}
Dictionary<string, object> sizeObj = null;
Dictionary<string, object> sizeObj;
if (string.IsNullOrEmpty(_hidSize.Value) == false)
{
JsonParser jsonParser = new JsonParser();
@@ -186,12 +181,9 @@ namespace VAR.WebFormsCore.Controls
}
else
{
sizeObj = new Dictionary<string, object> {
{ "height", height },
{ "width", null },
{ "scrollTop", null },
};
sizeObj = new Dictionary<string, object> {{"height", height}, {"width", null}, {"scrollTop", null},};
}
_hidSize.Value = JsonWriter.WriteObject(sizeObj);
}

View File

@@ -11,25 +11,19 @@ namespace VAR.WebFormsCore.Controls
{
public event EventHandler PreInit;
protected void OnPreInit()
protected void OnPreInit(EventArgs e)
{
PreInit?.Invoke(this, null);
foreach (Control control in Controls)
{
control.OnPreInit();
}
PreInit?.Invoke(this, e);
foreach (Control control in Controls) { control.OnPreInit(e); }
}
public event EventHandler Init;
protected void OnInit()
protected void OnInit(EventArgs e)
{
Init?.Invoke(this, null);
foreach (Control control in Controls)
{
control.OnInit();
}
Init?.Invoke(this, e);
foreach (Control control in Controls) { control.OnInit(e); }
}
@@ -37,97 +31,83 @@ namespace VAR.WebFormsCore.Controls
protected virtual void Process() { }
protected void OnLoad()
protected void OnLoad(EventArgs e)
{
Process();
Load?.Invoke(this, null);
foreach (Control control in Controls)
{
control.OnLoad();
}
Load?.Invoke(this, e);
foreach (Control control in Controls) { control.OnLoad(e); }
}
public event EventHandler PreRender;
protected void OnPreRender()
protected void OnPreRender(EventArgs e)
{
PreRender?.Invoke(this, null);
foreach (Control control in Controls)
PreRender?.Invoke(this, e);
foreach (Control control in Controls) { control.OnPreRender(e); }
}
private string _id;
public string ID
{
get => _id;
set
{
control.OnPreRender();
_id = value;
_clientID = null;
}
}
private string _id = null;
public string ID { get { return _id; } set { _id = value; _clientID = null; } }
private string _clientID = null;
private string _clientID;
public string ClientID
{
get
get { return _clientID ??= GenerateClientID(); }
}
private Control _parent;
public Control Parent
{
get => _parent;
set
{
if (_clientID == null)
{
_clientID = GenerateClientID();
}
return _clientID;
_parent = value;
_clientID = null;
}
}
private Control _parent = null;
private ControlCollection _controls;
public Control Parent { get { return _parent; } set { _parent = value; _clientID = null; } }
private ControlCollection _controls = null;
private string _cssClass = null;
public string CssClass { get { return _cssClass; } set { _cssClass = value; } }
public string CssClass { get; set; }
public ControlCollection Controls
{
get
{
if (_controls == null)
{
_controls = new ControlCollection(this);
}
return _controls;
}
get { return _controls ??= new ControlCollection(this); }
}
private Page _page = null;
private Page _page;
public Page Page
{
get { return _page; }
get => _page;
set
{
_page = value;
foreach (Control control in Controls)
{
control.Page = value;
}
foreach (Control control in Controls) { control.Page = value; }
}
}
private bool _visible = true;
public bool Visible { get { return _visible; } set { _visible = value; } }
public bool Visible { get; set; } = true;
private string GenerateClientID()
{
StringBuilder sbClientID = new();
if (string.IsNullOrEmpty(_id) == false)
{
sbClientID.Insert(0, _id);
}
if (string.IsNullOrEmpty(_id) == false) { sbClientID.Insert(0, _id); }
else
{
string currentID = string.Format("ctl{0:00}", Index);
string currentID = $"ctl{Index:00}";
sbClientID.Insert(0, currentID);
}
@@ -137,13 +117,10 @@ namespace VAR.WebFormsCore.Controls
if (parent is INamingContainer)
{
sbClientID.Insert(0, "_");
if (string.IsNullOrEmpty(parent.ID) == false)
{
sbClientID.Insert(0, parent.ID);
}
if (string.IsNullOrEmpty(parent.ID) == false) { sbClientID.Insert(0, parent.ID); }
else
{
string parentID = string.Format("ctl{0:00}", parent.Index);
string parentID = $"ctl{parent.Index:00}";
sbClientID.Insert(0, parentID);
}
}
@@ -158,20 +135,19 @@ namespace VAR.WebFormsCore.Controls
public Dictionary<string, string> Attributes { get; } = new Dictionary<string, string>();
private int _index = 0;
public int Index { get { return _index; } set { _index = value; } }
public int Index { get; set; }
public virtual void Render(TextWriter textWriter)
{
foreach (Control control in Controls)
{
if (control.Visible == false) { continue; }
control.Render(textWriter);
}
}
public void RenderAttribute(TextWriter textWriter, string key, string value)
public static void RenderAttribute(TextWriter textWriter, string key, string value)
{
textWriter.Write(" {0}=\"{1}\"", key, ServerHelpers.HtmlEncode(value));
}
@@ -183,40 +159,35 @@ namespace VAR.WebFormsCore.Controls
RenderAttribute(textWriter, "id", ClientID);
RenderAttribute(textWriter, "name", ClientID);
}
if (string.IsNullOrEmpty(_cssClass) == false)
{
RenderAttribute(textWriter, "class", _cssClass);
}
if (string.IsNullOrEmpty(CssClass) == false) { RenderAttribute(textWriter, "class", CssClass); }
foreach (KeyValuePair<string, string> attributePair in Attributes)
{
RenderAttribute(textWriter, attributePair.Key, attributePair.Value);
}
if (Style.Count > 0)
{
StringBuilder sbStyle = new();
foreach (KeyValuePair<string, string> stylePair in Style)
{
sbStyle.AppendFormat("{0}: {1};", stylePair.Key, stylePair.Value);
sbStyle.Append($"{stylePair.Key}: {stylePair.Value};");
}
RenderAttribute(textWriter, "style", sbStyle.ToString());
}
}
public List<Control> ChildsOfType<T>(List<Control> controls = null)
{
if (controls == null)
{
controls = new List<Control>();
}
controls ??= new List<Control>();
if (this is T) { controls.Add(this); }
foreach (Control child in _controls)
{
child.ChildsOfType<T>(controls);
}
foreach (Control child in _controls) { child.ChildsOfType<T>(controls); }
return controls;
}
}
}

View File

@@ -4,13 +4,10 @@ namespace VAR.WebFormsCore.Controls
{
public class ControlCollection : List<Control>
{
private Control _parent = null;
private int _index = 0;
private readonly Control _parent;
private int _index;
public ControlCollection(Control parent)
{
_parent = parent;
}
public ControlCollection(Control parent) { _parent = parent; }
public new void Add(Control control)
{

View File

@@ -6,7 +6,11 @@ namespace VAR.WebFormsCore.Controls
{
private string _value = string.Empty;
public string Value { get { return _value; } set { _value = value; } }
public string Value
{
get => _value;
set => _value = value;
}
protected override void Process()
{
@@ -20,10 +24,8 @@ namespace VAR.WebFormsCore.Controls
{
textWriter.Write("<input type=\"hidden\" ");
RenderAttributes(textWriter, forceId: true);
if (string.IsNullOrEmpty(Value) == false)
{
RenderAttribute(textWriter, "value", _value);
}
if (string.IsNullOrEmpty(Value) == false) { RenderAttribute(textWriter, "value", _value); }
textWriter.Write(">");
textWriter.Write("</input>");
}

View File

@@ -10,8 +10,6 @@ namespace VAR.WebFormsCore.Controls
{
private string _method = "post";
public HtmlForm() { }
public override void Render(TextWriter textWriter)
{
textWriter.Write("<form ");
@@ -24,19 +22,20 @@ namespace VAR.WebFormsCore.Controls
textWriter.Write("</form>");
}
private string GetAction()
{
StringBuilder sbAction = new();
sbAction.Append(Page.GetType().Name);
if (Page.Context.Request.Query.Count > 0)
{
sbAction.Append('?');
if (Page.Context.Request.Query.Count <= 0) { return sbAction.ToString(); }
foreach (KeyValuePair<string, StringValues> queryParam in Page.Context.Request.Query)
{
sbAction.AppendFormat("&{0}={1}", ServerHelpers.UrlEncode(queryParam.Key), ServerHelpers.UrlEncode(queryParam.Value[0]));
}
sbAction.Append('?');
foreach (KeyValuePair<string, StringValues> queryParam in Page.Context.Request.Query)
{
string key = ServerHelpers.UrlEncode(queryParam.Key);
string value = ServerHelpers.UrlEncode(queryParam.Value[0]);
sbAction.Append($"&{key}={value}");
}
return sbAction.ToString();

View File

@@ -4,12 +4,9 @@ namespace VAR.WebFormsCore.Controls
{
public class HtmlGenericControl : Control
{
private string _tagName;
private readonly string _tagName;
public HtmlGenericControl(string tag)
{
_tagName = tag;
}
public HtmlGenericControl(string tag) { _tagName = tag; }
public override void Render(TextWriter textWriter)
{

View File

@@ -12,10 +12,7 @@ namespace VAR.WebFormsCore.Controls
RenderAttributes(textWriter);
textWriter.Write(">");
if (string.IsNullOrEmpty(Title) == false)
{
textWriter.Write("<title>{0}</title>", Title);
}
if (string.IsNullOrEmpty(Title) == false) { textWriter.Write("<title>{0}</title>", Title); }
base.Render(textWriter);

View File

@@ -4,25 +4,20 @@ namespace VAR.WebFormsCore.Controls
{
public class HtmlMeta : Control
{
public string Name { get; set; }
public string Content { get; set; }
public string HttpEquiv { get; internal set; }
public string Name { get; init; }
public string Content { get; init; }
public string HttpEquiv { get; internal init; }
public override void Render(TextWriter textWriter)
{
textWriter.Write("<meta ");
RenderAttributes(textWriter);
if (string.IsNullOrEmpty(Name) == false)
{
textWriter.Write(" name=\"{0}\"", Name);
}
if (string.IsNullOrEmpty(Content) == false)
{
textWriter.Write(" content=\"{0}\"", Content);
}
if (string.IsNullOrEmpty(HttpEquiv) == false)
{
textWriter.Write(" http-equiv=\"{0}\"", HttpEquiv);
}
if (string.IsNullOrEmpty(Name) == false) { textWriter.Write(" name=\"{0}\"", Name); }
if (string.IsNullOrEmpty(Content) == false) { textWriter.Write(" content=\"{0}\"", Content); }
if (string.IsNullOrEmpty(HttpEquiv) == false) { textWriter.Write(" http-equiv=\"{0}\"", HttpEquiv); }
textWriter.Write(" />");
}
}

View File

@@ -4,29 +4,22 @@ namespace VAR.WebFormsCore.Controls
{
public class HyperLink : Control
{
public string NavigateUrl { get; set; }
public string Text { get; set; }
public string Text { get; init; }
public override void Render(TextWriter textWriter)
{
textWriter.Write("<a ");
RenderAttributes(textWriter);
if (string.IsNullOrEmpty(NavigateUrl) == false)
{
textWriter.Write(" href=\"{0}\"", NavigateUrl);
}
if (string.IsNullOrEmpty(NavigateUrl) == false) { textWriter.Write(" href=\"{0}\"", NavigateUrl); }
textWriter.Write(">");
if (string.IsNullOrEmpty(Text) == false)
{
textWriter.Write(Text);
}
if (string.IsNullOrEmpty(Text) == false) { textWriter.Write(Text); }
base.Render(textWriter);
textWriter.Write("</a>");
}
}
}

View File

@@ -11,13 +11,17 @@ namespace VAR.WebFormsCore.Controls
public string Tag
{
get { return _tagName; }
set { _tagName = value; }
get => _tagName;
set => _tagName = value;
}
private string _text = string.Empty;
public string Text { get { return _text; } set { _text = value; } }
public string Text
{
get => _text;
set => _text = value;
}
#endregion Properties

View File

@@ -4,15 +4,11 @@ namespace VAR.WebFormsCore.Controls
{
public class LiteralControl : Control
{
public string Content { get; set; }
private string Content { get; set; }
public LiteralControl() { }
public LiteralControl(string content) { Content = content; }
public override void Render(TextWriter textWriter)
{
textWriter.Write(Content);
}
public override void Render(TextWriter textWriter) { textWriter.Write(Content); }
}
}

View File

@@ -5,9 +5,7 @@ namespace VAR.WebFormsCore.Controls
{
public class TextBox : Control
{
private string _text = string.Empty;
public string Text { get { return _text; } set { _text = value; } }
public string Text { get; set; } = string.Empty;
public TextBoxMode TextMode { get; set; } = TextBoxMode.Normal;
@@ -15,7 +13,7 @@ namespace VAR.WebFormsCore.Controls
{
if (Page.IsPostBack && Page.Context.Request.Form.ContainsKey(ClientID))
{
_text = Page.Context.Request.Form[ClientID];
Text = Page.Context.Request.Form[ClientID];
}
}
@@ -26,17 +24,15 @@ namespace VAR.WebFormsCore.Controls
textWriter.Write("<textarea ");
RenderAttributes(textWriter, forceId: true);
textWriter.Write(">");
textWriter.Write(ServerHelpers.HtmlEncode(_text));
textWriter.Write(ServerHelpers.HtmlEncode(Text));
textWriter.Write("</textarea>");
}
else if (TextMode == TextBoxMode.Normal)
{
textWriter.Write("<input type=\"text\" ");
RenderAttributes(textWriter, forceId: true);
if (string.IsNullOrEmpty(Text) == false)
{
RenderAttribute(textWriter, "value", _text);
}
if (string.IsNullOrEmpty(Text) == false) { RenderAttribute(textWriter, "value", Text); }
textWriter.Write(">");
textWriter.Write("</input>");
}
@@ -44,10 +40,8 @@ namespace VAR.WebFormsCore.Controls
{
textWriter.Write("<input type=\"password\" ");
RenderAttributes(textWriter, forceId: true);
if (string.IsNullOrEmpty(Text) == false)
{
RenderAttribute(textWriter, "value", _text);
}
if (string.IsNullOrEmpty(Text) == false) { RenderAttribute(textWriter, "value", Text); }
textWriter.Write(">");
textWriter.Write("</input>");
}
@@ -56,8 +50,6 @@ namespace VAR.WebFormsCore.Controls
public enum TextBoxMode
{
Normal,
Password,
MultiLine,
Normal, Password, MultiLine,
}
}

View File

@@ -2,45 +2,32 @@
namespace VAR.WebFormsCore.Pages
{
public class FormUtils
public static class FormUtils
{
public static Control CreatePanel(string cssClass, Control ctrl)
public static Control CreatePanel(string cssClass, Control ctrl = null)
{
Panel pnl = new Panel();
if (ctrl != null)
{
pnl.Controls.Add(ctrl);
}
if (string.IsNullOrEmpty(cssClass) == false)
{
pnl.CssClass = cssClass;
}
return pnl;
}
if (ctrl != null) { pnl.Controls.Add(ctrl); }
public static Control CreatePanel(string cssClass)
{
return CreatePanel(cssClass, null);
if (string.IsNullOrEmpty(cssClass) == false) { pnl.CssClass = cssClass; }
return pnl;
}
public static Control CreateField(string label, Control fieldControl)
{
Panel pnlRow = new Panel();
pnlRow.CssClass = "formRow";
Panel pnlRow = new Panel {CssClass = "formRow"};
Panel pnlLabelContainer = new Panel();
pnlLabelContainer.CssClass = "formLabel width25pc";
Panel pnlLabelContainer = new Panel {CssClass = "formLabel width25pc"};
pnlRow.Controls.Add(pnlLabelContainer);
if (string.IsNullOrEmpty(label) == false)
{
Label lblField = new Label();
lblField.Text = label;
Label lblField = new Label {Text = label};
pnlLabelContainer.Controls.Add(lblField);
}
Panel pnlFieldContainer = new Panel();
pnlFieldContainer.CssClass = "formField width75pc";
Panel pnlFieldContainer = new Panel {CssClass = "formField width75pc"};
pnlRow.Controls.Add(pnlFieldContainer);
pnlFieldContainer.Controls.Add(fieldControl);
@@ -50,14 +37,7 @@ namespace VAR.WebFormsCore.Pages
public static bool Control_IsValid(Control control)
{
if (control is IValidableControl)
{
if (((IValidableControl)control).IsValid() == false)
{
return false;
}
}
return true;
return (control as IValidableControl)?.IsValid() != false;
}
public static bool Controls_AreValid(ControlCollection controls)
@@ -79,6 +59,7 @@ namespace VAR.WebFormsCore.Pages
break;
}
}
return valid;
}
}

View File

@@ -8,7 +8,7 @@ namespace VAR.WebFormsCore.Pages
{
#region Declarations
private Exception _ex = null;
private readonly Exception _ex;
#endregion Declarations
@@ -16,15 +16,12 @@ namespace VAR.WebFormsCore.Pages
public FrmError(Exception ex)
{
MustBeAutenticated = false;
MustBeAuthenticated = false;
_ex = ex;
Init += FrmError_Init;
}
private void FrmError_Init(object sender, EventArgs e)
{
InitializeControls();
}
private void FrmError_Init(object sender, EventArgs e) { InitializeControls(); }
#endregion Page life cycle
@@ -34,25 +31,25 @@ namespace VAR.WebFormsCore.Pages
{
Title = "Application Error";
Label lblErrorTitle = new Label { Text = Title, Tag = "h2" };
Label lblErrorTitle = new Label {Text = Title, Tag = "h2"};
Controls.Add(lblErrorTitle);
Exception exAux = _ex;
//if (exAux is HttpUnhandledException && exAux.InnerException != null) { exAux = exAux.InnerException; }
while (exAux != null)
{
Label lblMessage = new Label { Tag = "P" };
lblMessage.Text = string.Format("<b>{0}:</b> {1}", "Message", HttpUtility.HtmlEncode(exAux.Message));
Label lblMessage = new Label {Tag = "P", Text =
$"<b>Message:</b> {HttpUtility.HtmlEncode(exAux.Message)}"
};
Controls.Add(lblMessage);
Label lblStacktraceTitle = new Label { Tag = "p" };
lblStacktraceTitle.Text = string.Format("<b>{0}:</b>", "Stacktrace");
Label lblStacktraceTitle = new Label {Tag = "p", Text = "<b>Stacktrace:</b>"};
Controls.Add(lblStacktraceTitle);
Panel pnlStacktrace = new Panel();
pnlStacktrace.CssClass = "divCode";
Panel pnlStacktrace = new Panel {CssClass = "divCode"};
Controls.Add(pnlStacktrace);
LiteralControl litStackTrace = new LiteralControl(
string.Format("<pre><code>{0}</code></pre>", HttpUtility.HtmlEncode(exAux.StackTrace)));
$"<pre><code>{HttpUtility.HtmlEncode(exAux.StackTrace)}</code></pre>"
);
pnlStacktrace.Controls.Add(litStackTrace);
exAux = exAux.InnerException;

View File

@@ -10,11 +10,11 @@ namespace VAR.WebFormsCore.Pages
{
public class Page : Control, IHttpHandler
{
public string Title { get; set; }
protected string Title { get; set; }
public HttpContext Context { get; set; }
public HttpContext Context { get; private set; }
private static Encoding _utf8Econding = new UTF8Encoding();
private static readonly Encoding Utf8Encoding = new UTF8Encoding();
public async void ProcessRequest(HttpContext context)
{
@@ -25,18 +25,15 @@ namespace VAR.WebFormsCore.Pages
Context = context;
Page = this;
if (context.Request.Method == "POST")
{
_isPostBack = true;
}
if (context.Request.Method == "POST") { _isPostBack = true; }
OnPreInit();
OnPreInit(EventArgs.Empty);
if (context.Response.HasStarted) { return; }
OnInit();
OnInit(EventArgs.Empty);
if (context.Response.HasStarted) { return; }
OnLoad();
OnLoad(EventArgs.Empty);
if (context.Response.HasStarted) { return; }
if (_isPostBack)
@@ -47,20 +44,20 @@ namespace VAR.WebFormsCore.Pages
string clientID = control.ClientID;
if (context.Request.Form.ContainsKey(clientID))
{
(control as IReceivePostbackEvent).ReceivePostBack();
(control as IReceivePostbackEvent)?.ReceivePostBack();
if (context.Response.HasStarted) { return; }
}
}
}
OnPreRender();
OnPreRender(EventArgs.Empty);
if (context.Response.HasStarted) { return; }
Render(stringWriter);
if (context.Response.HasStarted) { return; }
context.Response.Headers.SafeSet("Content-Type", "text/html");
byte[] byteObject = _utf8Econding.GetBytes(stringWriter.ToString());
byte[] byteObject = Utf8Encoding.GetBytes(stringWriter.ToString());
await context.Response.Body.WriteAsync(byteObject);
}
catch (Exception ex)
@@ -73,8 +70,8 @@ namespace VAR.WebFormsCore.Pages
}
}
private bool _isPostBack = false;
private bool _isPostBack;
public bool IsPostBack { get { return _isPostBack; } }
public bool IsPostBack => _isPostBack;
}
}

View File

@@ -12,27 +12,19 @@ namespace VAR.WebFormsCore.Pages
private HtmlHead _head;
private HtmlBody _body;
private HtmlForm _form;
private Panel _pnlContainer = new Panel();
private Button _btnPostback = new Button();
private Button _btnLogout = new Button();
private readonly Panel _pnlContainer = new Panel();
private readonly Button _btnPostback = new Button();
private readonly Button _btnLogout = new Button();
private bool _mustBeAutenticated = true;
private bool _isAuthenticated = false;
private bool _isAuthenticated;
#endregion Declarations
#region Properties
public new ControlCollection Controls
{
get { return _pnlContainer.Controls; }
}
public new ControlCollection Controls => _pnlContainer.Controls;
public bool MustBeAutenticated
{
get { return _mustBeAutenticated; }
set { _mustBeAutenticated = value; }
}
public bool MustBeAuthenticated { get; init; } = true;
#endregion Properties
@@ -50,20 +42,19 @@ namespace VAR.WebFormsCore.Pages
Context.Response.PrepareUncacheableResponse();
_isAuthenticated = GlobalConfig.Get().IsUserAuthenticated(Context);
if (_mustBeAutenticated && _isAuthenticated == false)
if (MustBeAuthenticated && _isAuthenticated == false)
{
Context.Response.Redirect(GlobalConfig.Get().LoginHandler);
}
}
private void PageCommon_Init(object sender, EventArgs e)
{
CreateControls();
}
private void PageCommon_Init(object sender, EventArgs e) { CreateControls(); }
private void PageCommon_PreRender(object sender, EventArgs e)
{
_head.Title = string.IsNullOrEmpty(Title) ? GlobalConfig.Get().Title : string.Concat(Title, GlobalConfig.Get().TitleSeparator, GlobalConfig.Get().Title);
_head.Title = string.IsNullOrEmpty(Title)
? GlobalConfig.Get().Title
: string.Concat(Title, GlobalConfig.Get().TitleSeparator, GlobalConfig.Get().Title);
_btnLogout.Visible = _isAuthenticated;
}
@@ -74,10 +65,7 @@ namespace VAR.WebFormsCore.Pages
private void btnLogout_Click(object sender, EventArgs e)
{
GlobalConfig.Get().UserUnauthenticate(Context);
if (_mustBeAutenticated)
{
Context.Response.Redirect(GlobalConfig.Get().LoginHandler);
}
if (MustBeAuthenticated) { Context.Response.Redirect(GlobalConfig.Get().LoginHandler); }
}
#endregion UI Events
@@ -97,29 +85,38 @@ namespace VAR.WebFormsCore.Pages
_head = new HtmlHead();
html.Controls.Add(_head);
_head.Controls.Add(new HtmlMeta { HttpEquiv = "X-UA-Compatible", Content = "IE=Edge" });
_head.Controls.Add(new HtmlMeta { HttpEquiv = "content-type", Content = "text/html; charset=utf-8" });
_head.Controls.Add(new HtmlMeta { Name = "author", Content = GlobalConfig.Get().Author });
_head.Controls.Add(new HtmlMeta { Name = "Copyright", Content = GlobalConfig.Get().Copyright });
_head.Controls.Add(new HtmlMeta { Name = "viewport", Content = "width=device-width, initial-scale=1, maximum-scale=4, user-scalable=1" });
_head.Controls.Add(new HtmlMeta {HttpEquiv = "X-UA-Compatible", Content = "IE=Edge"});
_head.Controls.Add(new HtmlMeta {HttpEquiv = "content-type", Content = "text/html; charset=utf-8"});
_head.Controls.Add(new HtmlMeta {Name = "author", Content = GlobalConfig.Get().Author});
_head.Controls.Add(new HtmlMeta {Name = "Copyright", Content = GlobalConfig.Get().Copyright});
_head.Controls.Add(
new HtmlMeta
{
Name = "viewport",
Content = "width=device-width, initial-scale=1, maximum-scale=4, user-scalable=1"
}
);
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
_head.Controls.Add(new LiteralControl(string.Format("<script type=\"text/javascript\" src=\"ScriptsBundler?v={0}\"></script>\n", version)));
_head.Controls.Add(new LiteralControl(string.Format("<link href=\"StylesBundler?v={0}\" type=\"text/css\" rel=\"stylesheet\"/>\n", version)));
string version = Assembly.GetExecutingAssembly().GetName().Version?.ToString();
_head.Controls.Add(
new LiteralControl($"<script type=\"text/javascript\" src=\"ScriptsBundler?v={version}\"></script>\n")
);
_head.Controls.Add(
new LiteralControl($"<link href=\"StylesBundler?v={version}\" type=\"text/css\" rel=\"stylesheet\"/>\n")
);
_body = new HtmlBody();
html.Controls.Add(_body);
_form = new HtmlForm { ID = "formMain" };
_form = new HtmlForm {ID = "formMain"};
_body.Controls.Add(_form);
var pnlHeader = new Panel { CssClass = "divHeader" };
var pnlHeader = new Panel {CssClass = "divHeader"};
_form.Controls.Add(pnlHeader);
HyperLink lnkTitle = new HyperLink();
lnkTitle.NavigateUrl = ".";
HyperLink lnkTitle = new HyperLink {NavigateUrl = "."};
pnlHeader.Controls.Add(lnkTitle);
var lblTitle = new Label { Text = GlobalConfig.Get().Title, Tag = "h1" };
var lblTitle = new Label {Text = GlobalConfig.Get().Title, Tag = "h1"};
lnkTitle.Controls.Add(lblTitle);
_btnPostback.ID = "btnPostback";
@@ -127,13 +124,16 @@ namespace VAR.WebFormsCore.Pages
pnlHeader.Controls.Add(_btnPostback);
_btnPostback.Style.Add("display", "none");
var pnlUserInfo = new Panel { CssClass = "divUserInfo" };
var pnlUserInfo = new Panel {CssClass = "divUserInfo"};
pnlHeader.Controls.Add(pnlUserInfo);
_btnLogout.ID = "btnLogout";
_btnLogout.Text = MultiLang.GetLiteral("Logout");
_btnLogout.Click += btnLogout_Click;
_btnLogout.Attributes.Add("onclick", string.Format("return confirm('{0}');", MultiLang.GetLiteral("ConfirmExit")));
_btnLogout.Attributes.Add(
"onclick",
$"return confirm('{MultiLang.GetLiteral("ConfirmExit")}');"
);
pnlUserInfo.Controls.Add(_btnLogout);
_pnlContainer.CssClass = "divContent";

View File

@@ -1,6 +1,5 @@
////////////////////////
// CTextBox_Multilin_SetText
////////////////////////
// CTextBox_SetText
//
var CTextBox_SetText = function (id, text) {
var element = document.getElementById(id);

View File

@@ -16,7 +16,7 @@ form {
p {
margin-bottom: 0.5em;
text-shadow: 0 1px 1px rgba(255,255,255,0.5);
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.5);
}
h1 {
@@ -24,7 +24,7 @@ h1 {
text-align: center;
margin-top: 1.0em;
margin-bottom: 0.5em;
text-shadow: 0 1px 1px rgba(255,255,255,0.5);
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.5);
}
h2 {
@@ -32,7 +32,7 @@ h2 {
text-align: center;
margin-top: 1.0em;
margin-bottom: 0.5em;
text-shadow: 0 1px 1px rgba(255,255,255,0.5);
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.5);
}
h3 {
@@ -40,7 +40,7 @@ h3 {
text-align: left;
margin-top: 1.0em;
margin-bottom: 0.5em;
text-shadow: 0 1px 1px rgba(255,255,255,0.5);
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.5);
}
.divHeader {
@@ -80,7 +80,7 @@ h3 {
overflow: auto;
margin: 5px;
padding: 2px;
box-shadow: 0 0 10px rgb(0,0,0);
box-shadow: 0 0 10px rgb(0, 0, 0);
}
.formColumn {
@@ -98,7 +98,7 @@ h3 {
display: inline-block;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-size: 12px;
text-shadow: 0 1px 1px rgba(255,255,255,0.5);
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.5);
text-align: right;
padding-right: 20px;
vertical-align: top;
@@ -122,12 +122,12 @@ h3 {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-size: 11px;
padding: 3px;
box-shadow: inset 0 -2px 5px rgba(255,255,255,1), inset 0 2px 5px rgba(128,128,128,1);
box-shadow: inset 0 -2px 5px rgba(255, 255, 255, 1), inset 0 2px 5px rgba(128, 128, 128, 1);
}
.textbox:focus {
border: solid 1px black;
box-shadow: 0 0 10px rgba(255,255,255,0.5), inset 0 -2px 5px rgba(255,255,255,1), inset 0 2px 5px rgba(0,0,0,0.5);
box-shadow: 0 0 10px rgba(255, 255, 255, 0.5), inset 0 -2px 5px rgba(255, 255, 255, 1), inset 0 2px 5px rgba(0, 0, 0, 0.5);
}
textarea.textbox {
@@ -137,26 +137,26 @@ textarea.textbox {
}
.textboxInvalid {
box-shadow: 0 0 10px rgba(255,0,0,1), inset 0 -2px 5px rgba(255,255,255,1), inset 0 2px 5px rgba(0,0,0,0.5);
border: solid 1px rgb(255,0,0);
box-shadow: 0 0 10px rgba(255, 0, 0, 1), inset 0 -2px 5px rgba(255, 255, 255, 1), inset 0 2px 5px rgba(0, 0, 0, 0.5);
border: solid 1px rgb(255, 0, 0);
}
.textboxInvalid:focus {
box-shadow: 0 0 10px rgba(255,0,0,1), inset 0 -2px 5px rgba(255,255,255,1), inset 0 2px 5px rgba(0,0,0,0.5);
box-shadow: 0 0 10px rgba(255, 0, 0, 1), inset 0 -2px 5px rgba(255, 255, 255, 1), inset 0 2px 5px rgba(0, 0, 0, 0.5);
border: solid 1px black;
}
.button {
box-shadow: 0 2px 10px rgba(0,0,0,0.5), inset 0 2px 5px rgba(255,255,255,1), inset 0 -2px 5px rgba(128,128,128,1);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5), inset 0 2px 5px rgba(255, 255, 255, 1), inset 0 -2px 5px rgba(128, 128, 128, 1);
vertical-align: top;
border-radius: 5px;
border: solid 1px rgba(0, 0, 0, 0.5);
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
font-size: 11px;
text-shadow: 0 1px 1px rgba(255,255,255,0.5);
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.5);
text-align: center;
cursor: pointer;
background-color: rgb(192,192,192);
background-color: rgb(192, 192, 192);
margin-left: 5px;
padding-bottom: 2px;
padding-top: 2px;
@@ -169,15 +169,15 @@ textarea.textbox {
}
.button:hover {
background-color: rgb(220,220,220);
background-color: rgb(220, 220, 220);
}
.button:focus {
border: solid 1px black;
}
.button:active {
background-color: rgb(220,220,220);
box-shadow: inset 0 2px 5px rgba(255,255,255,1), inset 0 -2px 5px rgba(128,128,128,1);
background-color: rgb(220, 220, 220);
box-shadow: inset 0 2px 5px rgba(255, 255, 255, 1), inset 0 -2px 5px rgba(128, 128, 128, 1);
}
.width25pc {