Skip to content

Commit

Permalink
Fix code style (#24)
Browse files Browse the repository at this point in the history
* Fix ApiResponse constraint

* Fix AlertMessage naming

* Fix code style
  • Loading branch information
7702244 authored Jun 21, 2024
1 parent c865861 commit 5883b02
Show file tree
Hide file tree
Showing 24 changed files with 70 additions and 101 deletions.
9 changes: 3 additions & 6 deletions src/MAOToolkit.Web/Extensions/EnumerableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,10 @@ public static class EnumerableExtensions
public static RouteValueDictionary ToRouteValues(this IEnumerable<KeyValuePair<string, StringValues>> col, object? obj = null)
{
var values = new RouteValueDictionary(obj);
if (col is not null)
foreach (var kvp in col)
{
foreach (var kvp in col)
{
if (!String.IsNullOrEmpty(kvp.Key))
values.TryAdd(kvp.Key, kvp.Value);
}
if (!String.IsNullOrEmpty(kvp.Key))
values.TryAdd(kvp.Key, kvp.Value);
}
return values;
}
Expand Down
14 changes: 4 additions & 10 deletions src/MAOToolkit.Web/Extensions/HtmlHelperExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ public static IHtmlContent MetaKeywords(this IHtmlHelper htmlHelper, string? key
{
if (String.IsNullOrEmpty(keywords))
return HtmlString.Empty;
return new HtmlString(
String.Format("<meta name=\"keywords\" content=\"{0}\" />",
htmlHelper.Encode(keywords)));
return new HtmlString($"<meta name=\"keywords\" content=\"{htmlHelper.Encode(keywords)}\" />");
}

/// <summary>
Expand All @@ -35,9 +33,7 @@ public static IHtmlContent MetaDescription(this IHtmlHelper htmlHelper, string?
{
if (String.IsNullOrEmpty(description))
return HtmlString.Empty;
return new HtmlString(
String.Format("<meta name=\"description\" content=\"{0}\" />",
htmlHelper.Encode(description)));
return new HtmlString($"<meta name=\"description\" content=\"{htmlHelper.Encode(description)}\" />");
}

/// <summary>
Expand All @@ -50,9 +46,7 @@ public static IHtmlContent LinkCanonical(this IHtmlHelper htmlHelper, string? ca
{
if (String.IsNullOrEmpty(canonical))
return HtmlString.Empty;
return new HtmlString(
String.Format("<link rel=\"canonical\" href=\"{0}\" />",
htmlHelper.Encode(canonical)));
return new HtmlString($"<link rel=\"canonical\" href=\"{htmlHelper.Encode(canonical)}\" />");
}

/// <summary>
Expand All @@ -76,7 +70,7 @@ public static IHtmlContent HintFor<TModel, TValue>(this IHtmlHelper<TModel> html

if (!String.IsNullOrEmpty(description))
{
return new HtmlString(String.Format("<span class=\"bi bi-question-circle-fill text-muted\" style=\"cursor:pointer\" data-bs-toggle=\"tooltip\" title=\"{0}\" tabindex=\"0\"></span>", description));
return new HtmlString($"<span class=\"bi bi-question-circle-fill text-muted\" style=\"cursor:pointer\" data-bs-toggle=\"tooltip\" title=\"{description}\" tabindex=\"0\"></span>");
}

return HtmlString.Empty;
Expand Down
13 changes: 6 additions & 7 deletions src/MAOToolkit.Web/Extensions/HttpRequestExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public static bool IsModifiedSince(this HttpRequest request, DateTime updatedAt)
// Example:
// If-Modified-Since: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT
// If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT
var headerValue = request.Headers.IfModifiedSince.FirstOrDefault();
string? headerValue = request.Headers.IfModifiedSince.FirstOrDefault();
if (DateTime.TryParse(headerValue, out DateTime isModifiedSince))
{
isModifiedSince = DateTime.SpecifyKind(isModifiedSince, DateTimeKind.Utc);
Expand Down Expand Up @@ -161,12 +161,11 @@ public static async ValueTask<byte[]> GetRawBodyBytesAsync(this HttpRequest requ
throw new ArgumentNullException(nameof(request));

request.Body.Seek(0, SeekOrigin.Begin);
using (var ms = new MemoryStream(1024))
{
await request.Body.CopyToAsync(ms, request.HttpContext.RequestAborted);
request.Body.Seek(0, SeekOrigin.Begin);
return ms.ToArray();
}

using var ms = new MemoryStream(1024);
await request.Body.CopyToAsync(ms, request.HttpContext.RequestAborted);
request.Body.Seek(0, SeekOrigin.Begin);
return ms.ToArray();
}
}
}
4 changes: 2 additions & 2 deletions src/MAOToolkit.Web/Extensions/TempDataExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ public static class TempDataExtensions
{
if (!tempData.TryGetValue(key, out object? obj) || obj is null)
{
return new();
return new T();
}

return JsonSerializer.Deserialize<T>((string)obj, JsonSettings) ?? new();
return JsonSerializer.Deserialize<T>((string)obj, JsonSettings) ?? new T();
}

public static T Peek<T>(this ITempDataDictionary tempData, string key) where T : new()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ public Task<HealthCheckResult> CheckHealthAsync(
CancellationToken cancellationToken = default)
{
// Include drive information in the reported diagnostics.
var freeMb = drive.AvailableFreeSpace / 1024 / 1024;
var data = new Dictionary<string, object>()
long freeMb = drive.AvailableFreeSpace / 1024 / 1024;
var data = new Dictionary<string, object>
{
{ nameof(drive.Name), drive.Name },
{ nameof(drive.DriveFormat), drive.DriveFormat },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ public Task<HealthCheckResult> CheckHealthAsync(
CancellationToken cancellationToken = default)
{
// Include GC information in the reported diagnostics.
var allocatedMb = GC.GetTotalMemory(forceFullCollection: false) / 1024 / 1024;
var data = new Dictionary<string, object>()
long allocatedMb = GC.GetTotalMemory(forceFullCollection: false) / 1024 / 1024;
var data = new Dictionary<string, object>
{
{ "AllocatedMegabytes", allocatedMb },
{ "Gen0Collections", GC.CollectionCount(0) },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public override RouteValueDictionary Read(ref Utf8JsonReader reader, Type typeTo

// Get the value.
reader.Read();
StringValues value = stringValuesConverter.Read(ref reader, typeof(StringValues), options);
var value = stringValuesConverter.Read(ref reader, typeof(StringValues), options);

// Add to dictionary.
routeValues.Add(propertyName, value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public Task BindModelAsync(ModelBindingContext bindingContext)
return Task.CompletedTask;
}

var value = valueProviderResult.FirstValue;
string? value = valueProviderResult.FirstValue;

if (String.IsNullOrWhiteSpace(value))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public Task BindModelAsync(ModelBindingContext bindingContext)
return Task.CompletedTask;
}

var value = valueProviderResult.FirstValue;
string? value = valueProviderResult.FirstValue;

if (String.IsNullOrWhiteSpace(value))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public Task BindModelAsync(ModelBindingContext bindingContext)
return Task.CompletedTask;
}

var value = valueProviderResult.FirstValue;
string? value = valueProviderResult.FirstValue;

if (String.IsNullOrEmpty(value))
{
Expand Down
29 changes: 14 additions & 15 deletions src/MAOToolkit.Web/Utilities/ViewUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,28 +37,27 @@ public async Task<string> RenderToStringAsync(string viewName, object model)
var viewResult = razorViewEngine.GetView(null, viewName, false);
if (!viewResult.Success)
{
throw new InvalidOperationException(String.Format("Couldn't find view '{0}'. Searched: {1}", viewName, String.Join(',', viewResult.SearchedLocations)));
throw new InvalidOperationException($"Couldn't find view '{viewName}'. Searched: {String.Join(',', viewResult.SearchedLocations)}");
}

var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
Model = model
};

using (var writer = new StringWriter())
{
var viewContext = new ViewContext(
actionContext,
viewResult.View,
viewDictionary,
new TempDataDictionary(actionContext.HttpContext, tempDataProvider),
writer,
new HtmlHelperOptions()
);

await viewResult.View.RenderAsync(viewContext);
return writer.ToString();
}
await using var writer = new StringWriter();

var viewContext = new ViewContext(
actionContext,
viewResult.View,
viewDictionary,
new TempDataDictionary(actionContext.HttpContext, tempDataProvider),
writer,
new HtmlHelperOptions()
);

await viewResult.View.RenderAsync(viewContext);
return writer.ToString();
}
}
}
8 changes: 4 additions & 4 deletions src/MAOToolkit/Entities/AlertMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ public readonly record struct AlertMessage
{
public enum Kind
{
success,
info,
warning,
danger
Success,
Info,
Warning,
Danger
}

public Kind Type { get; init; }
Expand Down
35 changes: 10 additions & 25 deletions src/MAOToolkit/Entities/ApiResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace MAOToolkit.Entities
{
// https://github.com/omniti-labs/jsend
public class ApiResponse : ApiResponse<object> { }
public class ApiResponse<T> where T : class
public class ApiResponse<T>
{
/// <summary>
/// The result of the operation.
Expand All @@ -26,30 +26,15 @@ public class ApiResponse<T> where T : class
[JsonPropertyName("data")]
public T? Data { get; init; }

public static ApiResponse<T> Success(string message)
{
return new ApiResponse<T> { Status = ApiResponseResult.Success, Message = message };
}

public static ApiResponse<T> Success(T data)
{
return new ApiResponse<T> { Status = ApiResponseResult.Success, Data = data };
}

public static ApiResponse<T> Success(string message, T data)
{
return new ApiResponse<T> { Status = ApiResponseResult.Success, Message = message, Data = data };
}

public static ApiResponse<T> Error(string message)
{
return new ApiResponse<T> { Status = ApiResponseResult.Error, Message = message };
}

public static ApiResponse<T> Error(string message, T data)
{
return new ApiResponse<T> { Status = ApiResponseResult.Error, Message = message, Data = data };
}
public static ApiResponse<T> Success(string message) => new() { Status = ApiResponseResult.Success, Message = message };

public static ApiResponse<T> Success(T data) => new() { Status = ApiResponseResult.Success, Data = data };

public static ApiResponse<T> Success(string message, T data) => new() { Status = ApiResponseResult.Success, Message = message, Data = data };

public static ApiResponse<T> Error(string message) => new() { Status = ApiResponseResult.Error, Message = message };

public static ApiResponse<T> Error(string message, T data) => new() { Status = ApiResponseResult.Error, Message = message, Data = data };
}

/// <summary>
Expand Down
6 changes: 3 additions & 3 deletions src/MAOToolkit/Extensions/ColorExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ public static Color ChangeBrightness(this Color color, float correctionFactor)
}
else
{
red = (255 - red) * correctionFactor + red;
green = (255 - green) * correctionFactor + green;
blue = (255 - blue) * correctionFactor + blue;
red = ((255 - red) * correctionFactor) + red;
green = ((255 - green) * correctionFactor) + green;
blue = ((255 - blue) * correctionFactor) + blue;
}

return Color.FromArgb(color.A, (int)red, (int)green, (int)blue);
Expand Down
2 changes: 1 addition & 1 deletion src/MAOToolkit/Extensions/DateTimeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public static DateTime ToDateTime(this double timestamp)

public static double ToUnixTimestamp(this DateTime value)
{
TimeSpan diff = value.ToUniversalTime() - DateTime.UnixEpoch;
var diff = value.ToUniversalTime() - DateTime.UnixEpoch;
return Math.Floor(diff.TotalSeconds);
}

Expand Down
2 changes: 1 addition & 1 deletion src/MAOToolkit/Extensions/DictionaryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dicti

public static async Task<TValue> GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<Task<TValue>> getter) where TKey : notnull
{
if (!dictionary.TryGetValue(key, out TValue? value))
if (!dictionary.TryGetValue(key, out var value))
{
value = await getter();
dictionary.Add(key, value);
Expand Down
2 changes: 1 addition & 1 deletion src/MAOToolkit/Extensions/EnumerableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public static IEnumerable<T> ForEach<T>(
this IEnumerable<T> source,
Action<T> act)
{
foreach (T element in source)
foreach (var element in source)
{
act(element);
}
Expand Down
8 changes: 3 additions & 5 deletions src/MAOToolkit/Extensions/HttpContentExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,13 @@ public static async Task<string> ReadAsStringAsync(this HttpContent httpContent,
}

// The `leaveOpen` should be `true` if there's another function going to be invoked AFTER this.
using (var reader = new StreamReader(
using var reader = new StreamReader(
stream,
Encoding.UTF8,
detectEncodingFromByteOrderMarks: false,
bufferSize: 1024,
leaveOpen: false))
{
return await reader.ReadWithLimitAsync(charsLimit);
}
leaveOpen: false);
return await reader.ReadWithLimitAsync(charsLimit);
}
}
}
8 changes: 4 additions & 4 deletions src/MAOToolkit/Extensions/IPAddressExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,19 @@ public static bool IsPrivateNetwork(this IPAddress ipAddress)

byte[] octets = ipAddress.GetAddressBytes();

var is24BitBlock = octets[0] == 10;
bool is24BitBlock = octets[0] == 10;
if (is24BitBlock)
return true; // Return to prevent further processing

var is20BitBlock = octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31;
bool is20BitBlock = octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31;
if (is20BitBlock)
return true; // Return to prevent further processing

var is16BitBlock = octets[0] == 192 && octets[1] == 168;
bool is16BitBlock = octets[0] == 192 && octets[1] == 168;
if (is16BitBlock)
return true; // Return to prevent further processing

var isLinkLocalAddress = octets[0] == 169 && octets[1] == 254;
bool isLinkLocalAddress = octets[0] == 169 && octets[1] == 254;
return isLinkLocalAddress;
}

Expand Down
6 changes: 2 additions & 4 deletions src/MAOToolkit/Extensions/StreamReaderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,8 @@ public static async ValueTask<string> ReadWithLimitAsync(this StreamReader reade
int read = await reader.ReadAsync(chars, 0, chars.Length);
return new string(chars.AsSpan(0, read));
}
else
{
return await reader.ReadToEndAsync();
}

return await reader.ReadToEndAsync();
}
}
}
2 changes: 1 addition & 1 deletion src/MAOToolkit/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public static string TrimEnd(this string str, string? trimString)
{
if (!String.IsNullOrEmpty(s) && s.Trim().Length > 0)
{
TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
var conv = TypeDescriptor.GetConverter(typeof(T));
result = (T?)conv.ConvertFrom(s);
}
}
Expand Down
3 changes: 1 addition & 2 deletions src/MAOToolkit/Extensions/TypeExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Runtime.CompilerServices;

Expand Down Expand Up @@ -31,7 +30,7 @@ public static bool IsSimpleType(this Type type)

return type.IsPrimitive
|| type.IsValueType
|| type.Equals(typeof(string));
|| type == typeof(string);
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion src/MAOToolkit/Extensions/Utf8JsonReaderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public static class Utf8JsonReaderExtensions
return null;
}

ReadOnlySpan<byte> utf8Bytes = jsonReader.HasValueSequence ? jsonReader.ValueSequence.ToArray() : jsonReader.ValueSpan;
var utf8Bytes = jsonReader.HasValueSequence ? jsonReader.ValueSequence.ToArray() : jsonReader.ValueSpan;

return System.Text.RegularExpressions.Regex.Unescape(Encoding.UTF8.GetString(utf8Bytes));
}
Expand Down
Loading

0 comments on commit 5883b02

Please sign in to comment.