Skip to content

Commit

Permalink
Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
dgmjr committed Mar 31, 2024
1 parent c8ca620 commit dd59db6
Show file tree
Hide file tree
Showing 10 changed files with 208 additions and 28 deletions.
Binary file added DataProtection/Redis/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
36 changes: 33 additions & 3 deletions Logging/AutomaticLoggingConfigurator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ namespace Microsoft.Extensions.DependencyInjection;
using Dgmjr.Configuration.Extensions;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

using Serilog;

public class AutomaticLoggingConfigurator
: IConfigureIHostApplicationBuilder,
IConfigureIApplicationBuilder
public class AutomaticLoggingConfigurator : IHostingStartup, IStartupFilter
{
public ConfigurationOrder Order => ConfigurationOrder.First;

Expand All @@ -24,4 +23,35 @@ public void Configure(IApplicationBuilder app)
app.UseHttpLogging();
app.UseSerilogRequestLogging();
}

public void Configure(IWebHostBuilder builder)
{
builder.ConfigureLogging(
(context, logging) =>
{
Log.Logger = new LoggerConfiguration().ReadFrom
.Configuration(context.Configuration)
.CreateBootstrapLogger();
}
);
builder.ConfigureServices(
(context, services) =>
{
services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));
services.AddSingleton<Serilog.Extensions.Hosting.DiagnosticContext>();
services.AddLoggingAndApplicationInsightsTelemetry(context.Configuration);
services.AddSingleton<IStartupFilter>(this);
}
);
}

public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return app =>
{
app.UseHttpLogging();
app.UseSerilogRequestLogging();
next(app);
};
}
}
28 changes: 21 additions & 7 deletions Logging/LoggerWebApplicationBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
using global::Azure.Identity;
using global::Azure.Monitor.OpenTelemetry.Exporter;
using OpenTelemetry.Logs;
using Microsoft.AspNetCore.Hosting;

public static partial class LoggingWebApplicationBuilderExtensions
{
Expand All @@ -36,18 +37,31 @@ public static partial class LoggingWebApplicationBuilderExtensions
public static WebApplicationBuilder AddLoggingAndApplicationInsightsTelemetry(
this WebApplicationBuilder builder
)
{
builder.Services.AddLoggingAndApplicationInsightsTelemetry(
builder.Host, builder.Logging, builder.Configuration
);
return builder;
}

public static IServiceCollection AddLoggingAndApplicationInsightsTelemetry(
this IServiceCollection services,
IHostBuilder host,
ILoggingBuilder logging,
IConfiguration configuration
)
{
Log.Logger = new LoggerConfiguration().ReadFrom
.Configuration(builder.Configuration)
.Configuration(configuration)
.CreateBootstrapLogger();

builder.Host.UseSerilog(Log.Logger, true);
host.UseSerilog(Log.Logger, true);

builder.Services.AddLoggingAndApplicationInsightsTelemetry(builder.Configuration);
builder.Logging
services.AddLoggingAndApplicationInsightsTelemetry(configuration);
logging
.AddApplicationInsights(
configureTelemetryConfiguration: config =>
config.ConnectionString = builder.Configuration.GetConnectionString(
config.ConnectionString = configuration.GetConnectionString(
ApplicationInsights
),
configureApplicationInsightsLoggerOptions: _ => { }
Expand All @@ -62,13 +76,13 @@ this WebApplicationBuilder builder
// .AddEventLog()
.AddEventSourceLogger();

builder.Services.AddTransient<ILogger>(sp =>
services.AddTransient<ILogger>(sp =>
{
var logger = sp.GetRequiredService<ILogger<object>>();
return logger;
});

return builder;
return services;
}

public static IServiceCollection AddLoggingAndApplicationInsightsTelemetry(
Expand Down
1 change: 0 additions & 1 deletion Redis/Dgmjr.Redis.Extensions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" />
<PackageReference Include="Microsoft.AspNetCore.OutputCaching.StackExchangeRedis" />
<PackageReference Include="StackExchange.Redis" />
<PackageReference Include="System.Net.Sockets" VersionOverride="[4.3.0,)" />
Expand Down
38 changes: 22 additions & 16 deletions Redis/RedisAutoConfigurator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,39 @@ namespace Microsoft.Extensions.DependencyInjection;

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Hosting;

public class RedisAutoConfigurator
: IConfigureIHostApplicationBuilder,
IConfigureIApplicationBuilder
public class RedisAutoConfigurator : IHostingStartup, IStartupFilter
{
private const string Redis = nameof(Redis);
private const string ResponseCaching = nameof(ResponseCaching);
public ConfigurationOrder Order => ConfigurationOrder.AnyTime;

public void Configure(WebApplicationBuilder builder)
public void Configure(IWebHostBuilder builder)
{
var redisOptions = builder.Configuration.GetSection(Redis).Get<RedisCacheOptions>();
if (redisOptions?.UseRedis == true)
builder.ConfigureServices((context, services) =>
{
builder.AddRedisCaching();
}
var redisOptions = context.Configuration.GetSection(Redis).Get<RedisCacheOptions>();
if (redisOptions?.UseRedis == true)
{
services.AddRedisCaching(context.Configuration);
}
});
}

public void Configure(IApplicationBuilder builder)
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
var redisOptions = builder.ApplicationServices
.GetRequiredService<IConfiguration>()
.GetSection(Redis)
.Get<RedisCacheOptions>();
if (redisOptions?.UseRedis == true)
return builder =>
{
builder.UseRedisCaching();
}
var redisOptions = builder.ApplicationServices
.GetRequiredService<IConfiguration>()
.GetSection(Redis)
.Get<RedisCacheOptions>();
if (redisOptions?.UseRedis == true)
{
builder.UseRedisCaching();
}
next(builder);
};
}
}
1 change: 1 addition & 0 deletions System/Dgmjr.System.Extensions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
<PackageReference Include="System.Text.Usings" IncludeAssets="Build" ExcludeAssets="Compile;Runtime;Native;Analyzers"/>
<PackageReference Include="system.Xml.ReaderWriter" Condition="$(TargetFramework.StartsWith('net6')) Or $(TargetFramework.StartsWith('net7'))"/>
<PackageReference Include="system.ComponentModel.Annotations" Condition="$(TargetFramework.StartsWith('netstandard'))"/>
<PackageReference Include="Dgmjr.ComponentModel" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.Memory" />
Expand Down
37 changes: 36 additions & 1 deletion System/System.Linq/System.Linq.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ namespace System.Linq;
// #if DEFINE_INTERNAL
public static class DmjrsLinqExtensions
// #else
// public static class JustinsLinqExtensions
// #endif
{
/// <summary>
Expand Down Expand Up @@ -218,4 +217,40 @@ public static int GreatestPowerOfTwo<T>(this IEnumerable<T> values, Func<T, int>
}
return k;
}

public static async Task<IEnumerable<T>> ToEnumerableAsync<T>(this IAsyncEnumerable<T> asyncEnumerable)
{
var list = new List<T>();
await foreach (var item in asyncEnumerable)
{
list.Add(item);
}
return list;
}

public static IEnumerable<T> TakeRandom<T>(this IEnumerable<T> enumerable, int count = 1, bool allowDuplicates = false)
{
#if !NET5_0_OR_GREATER
var random = new Random();
#endif
var list = enumerable.ToList();
for (var i = 0; i < count; i++)
{
#if NET5_0_OR_GREATER
var index = Random.Shared.Next(0, list.Count);
#else
var index = random.Next(0, list.Count);
#endif
yield return list[index];
if(!allowDuplicates)
{
list.RemoveAt(index);
}
}
}

public static T TakeRandom<T>(this IEnumerable<T> enumerable)
{
return enumerable.TakeRandom(1).First();
}
}
31 changes: 31 additions & 0 deletions System/System.Reflection/System.Reflection.Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,35 @@ public static Task<string> ReadAssemblyResourceAllTextAsync(
this Assembly assembly,
string resourceName
) => assembly.GetManifestResourceStream(resourceName).ReadToEndAsync();


public static Expression<Func<T, U>> ToExpression<T, U>(this PropertyInfo propertyInfo)
{
// Validate the input
if (propertyInfo == null)
{
throw new ArgumentNullException(nameof(propertyInfo));
}

if (typeof(T) != propertyInfo.DeclaringType && !typeof(T).IsSubclassOf(propertyInfo.DeclaringType))
{
throw new ArgumentException($"The property '{propertyInfo.Name}' does not belong to type {typeof(T).FullName}.", nameof(propertyInfo));
}

if (typeof(U) != propertyInfo.PropertyType)
{
throw new ArgumentException($"The property '{propertyInfo.Name}' is not of type {typeof(U).FullName}.", nameof(propertyInfo));
}

// Create the parameter expression (t => ...)
var parameterExpression = Expression.Parameter(typeof(T), "t");

// Create the property access expression (t => t.Property)
var propertyAccessExpression = Expression.Property(parameterExpression, propertyInfo);

// Create the lambda expression (t => t.Property)
var lambdaExpression = Expression.Lambda<Func<T, U>>(propertyAccessExpression, parameterExpression);

return lambdaExpression;
}
}
42 changes: 42 additions & 0 deletions System/System/EnumExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,46 @@ public static int GetOrder<T>(this T e)
var attribute = e.GetCustomAttribute< DisplayAttribute>();
return attribute?.GetOrder() ?? 0;
}

public static string GetDescription<T>(this T e)
where T : Enum
{
var attribute = e.GetCustomAttribute<DisplayAttribute>();
return attribute?.Description?.IsPresent() == true ? attribute.GetDescription() : e.ToString();
}

public static string GetCategory<T>(this T e)
where T : Enum
{
var attribute = e.GetCustomAttribute<DisplayAttribute>();
return attribute?.GetGroupName()?.IsPresent() == true ? attribute.GetGroupName() : e.ToString();
}

public static string[] GetSynonyms<T>(this T e)
where T : Enum
{
var attribute = e.GetCustomAttribute<SynonymsAttribute>();
return attribute?.Value ?? Empty<string>();
}

public static string GetName<T>(this T e)
where T : Enum
{
var attribute = e.GetCustomAttribute<DisplayAttribute>();
return attribute?.GetName() ?? e.ToString();
}

public static guid? GetGuid<T>(this T e)
where T : Enum
{
var attribute = e.GetCustomAttribute<GuidAttribute>();
return attribute?.Value;
}

public static Uri? GetUri<T>(this T e)
where T : Enum
{
var attribute = e.GetCustomAttribute<UriAttribute>();
return attribute?.Value;
}
}
22 changes: 22 additions & 0 deletions System/System/FlagsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -247,4 +247,26 @@ private static bool IsEnum<T>()
{
return typeof(T).IsEnum;
}

public static T[] GetFlags<T>(this T flags)
where T : Enum
{
var individualFlags = new List<T>();
foreach (var value in Enum.GetValues(typeof(T)))
{
var flag = Convert.ToInt64(value);
if (flag != 0 && (Convert.ToInt64(flags) & flag) == flag)
{
individualFlags.Add((T)value);
}
}

// Case to handle the 'None' scenario, typically represented by a value of 0.
if (individualFlags.Count == 0 && Enum.IsDefined(typeof(T), 0))
{
individualFlags.Add((T)Enum.ToObject(typeof(T), 0));
}

return [.. individualFlags];
}
}

0 comments on commit dd59db6

Please sign in to comment.