Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

Grand.Infrastructure - Code refactoring (#347)

Krzysztof Pajak7a6c187718e7
diff --git a/src/API/Grand.Api/Infrastructure/ODataStartup.cs b/src/API/Grand.Api/Infrastructure/ODataStartup.cs
index d778dafcb..5e3acbd1d 100644
--- a/src/API/Grand.Api/Infrastructure/ODataStartup.cs
+++ b/src/API/Grand.Api/Infrastructure/ODataStartup.cs
@@ -8,7 +8,7 @@ using Grand.Api.Queries.Handlers.Common;
using Grand.Api.Queries.Models.Common;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
-using Grand.Infrastructure.TypeSearchers;
+using Grand.Infrastructure.TypeSearch;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
@@ -73,7 +73,7 @@ namespace Grand.Api.Infrastructure
private void RegisterDependencies(ODataConventionModelBuilder builder, BackendAPIConfig apiConfig)
{
- var typeFinder = new AppTypeSearcher();
+ var typeFinder = new TypeSearcher();
//find dependency provided by other assemblies
var dependencyInject = typeFinder.ClassesOfType<IDependencyEdmModel>();
diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs b/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs
index ca0ffb278..6e8333bf4 100644
--- a/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs
+++ b/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs
@@ -31,7 +31,7 @@ using Grand.Domain.Tasks;
using Grand.Domain.Tax;
using Grand.Domain.Vendors;
using Grand.Infrastructure;
-using Grand.Infrastructure.TypeSearchers;
+using Grand.Infrastructure.TypeSearch;
using Grand.SharedKernel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
diff --git a/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.cs
index 4b969edf2..fb418c6d9 100644
--- a/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.cs
+++ b/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.cs
@@ -26,7 +26,7 @@
/// Key for caching
/// </summary>
/// <remarks>
- /// {0} : discont ID
+ /// {0} : discount ID
/// </remarks>
public static string DISCOUNTS_BY_ID_KEY => "Grand.discount.id-{0}";
@@ -218,7 +218,7 @@
/// Key for caching
/// </summary>
/// <remarks>
- /// {0} : page systemname
+ /// {0} : page system name
/// {1} : store id
/// </remarks>
public static string PAGES_BY_SYSTEMNAME => "Grand.pages.systemname-{0}-{1}";
diff --git a/src/Core/Grand.Infrastructure/Caching/Constants/CustomerCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/CustomerCacheKey.cs
index ddb33de47..53ed2c603 100644
--- a/src/Core/Grand.Infrastructure/Caching/Constants/CustomerCacheKey.cs
+++ b/src/Core/Grand.Infrastructure/Caching/Constants/CustomerCacheKey.cs
@@ -91,7 +91,7 @@
/// Key for caching
/// </summary>
/// <remarks>
- /// {0} : salesemployee ID
+ /// {0} : sales-employee ID
/// </remarks>
public static string SALESEMPLOYEE_BY_ID_KEY => "Grand.salesemployee.id-{0}";
diff --git a/src/Core/Grand.Infrastructure/Caching/Constants/DirectoryCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/DirectoryCacheKey.cs
index bd3aff236..900839f6d 100644
--- a/src/Core/Grand.Infrastructure/Caching/Constants/DirectoryCacheKey.cs
+++ b/src/Core/Grand.Infrastructure/Caching/Constants/DirectoryCacheKey.cs
@@ -134,7 +134,7 @@
/// key for caching by country id
/// </summary>
/// <remarks>
- /// {0} : twoletter
+ /// {0} : two-letter
/// </remarks>
public static string COUNTRIES_BY_TWOLETTER => "Grand.country.twoletter-{0}";
@@ -142,7 +142,7 @@
/// key for caching by country id
/// </summary>
/// <remarks>
- /// {0} : threeletter
+ /// {0} : three-letter
/// </remarks>
public static string COUNTRIES_BY_THREELETTER => "Grand.country.threeletter-{0}";
diff --git a/src/Core/Grand.Infrastructure/Caching/Constants/MerchandiseReturnCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/MerchandiseReturnCacheKey.cs
index a89bde527..27a92bb31 100644
--- a/src/Core/Grand.Infrastructure/Caching/Constants/MerchandiseReturnCacheKey.cs
+++ b/src/Core/Grand.Infrastructure/Caching/Constants/MerchandiseReturnCacheKey.cs
@@ -3,7 +3,7 @@
public static partial class CacheKey
{
/// <summary>
- /// Key for all merchandise return reaason
+ /// Key for all merchandise return reason
/// </summary>
public static string MERCHANDISE_RETURN_REASONS_ALL_KEY => "Grand.merchandisereturn.reasons.all";
/// <summary>
diff --git a/src/Core/Grand.Infrastructure/Caching/Constants/OrdersCacheKeys.cs b/src/Core/Grand.Infrastructure/Caching/Constants/OrdersCacheKeys.cs
index 83e2c66b0..0258f3b61 100644
--- a/src/Core/Grand.Infrastructure/Caching/Constants/OrdersCacheKeys.cs
+++ b/src/Core/Grand.Infrastructure/Caching/Constants/OrdersCacheKeys.cs
@@ -19,7 +19,7 @@
/// </summary>
/// <remarks>
/// {0} : store ID
- /// {1} : >A value indicating whether we should exlude shippable attributes
+ /// {1} : >A value indicating whether we should exclude shippable attributes
/// {2} : ignore ACL?
/// </remarks>
public static string CHECKOUTATTRIBUTES_ALL_KEY => "Grand.checkoutattribute.all-{0}-{1}-{2}";
diff --git a/src/Core/Grand.Infrastructure/Caching/Constants/ProductCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/ProductCacheKey.cs
index 69bf390d0..81e323d98 100644
--- a/src/Core/Grand.Infrastructure/Caching/Constants/ProductCacheKey.cs
+++ b/src/Core/Grand.Infrastructure/Caching/Constants/ProductCacheKey.cs
@@ -64,7 +64,6 @@
/// <summary>
/// Key for caching
/// </summary>
- /// <remarks>
public static string PRODUCTS_CUSTOMER_PERSONAL_PATTERN => "Grand.product.personal";
/// <summary>
diff --git a/src/Core/Grand.Infrastructure/Caching/Constants/ShippingCacheKeys.cs b/src/Core/Grand.Infrastructure/Caching/Constants/ShippingCacheKeys.cs
index 2668e165f..5ef7b9719 100644
--- a/src/Core/Grand.Infrastructure/Caching/Constants/ShippingCacheKeys.cs
+++ b/src/Core/Grand.Infrastructure/Caching/Constants/ShippingCacheKeys.cs
@@ -34,7 +34,7 @@
/// Key for caching
/// </summary>
/// <remarks>
- /// {0} : picpup point ID
+ /// {0} : pickup point point ID
/// </remarks>
public static string PICKUPPOINTS_BY_ID_KEY => "Grand.pickuppoint.id-{0}";
diff --git a/src/Core/Grand.Infrastructure/Caching/MemoryCacheBase.cs b/src/Core/Grand.Infrastructure/Caching/MemoryCacheBase.cs
index 6f4bdfb76..5300477d6 100644
--- a/src/Core/Grand.Infrastructure/Caching/MemoryCacheBase.cs
+++ b/src/Core/Grand.Infrastructure/Caching/MemoryCacheBase.cs
@@ -10,7 +10,7 @@ namespace Grand.Infrastructure.Caching
/// <summary>
/// Represents a manager for memory caching
/// </summary>
- public partial class MemoryCacheBase : ICacheBase
+ public class MemoryCacheBase : ICacheBase
{
#region Fields
@@ -20,7 +20,7 @@ namespace Grand.Infrastructure.Caching
private bool _disposed;
private static CancellationTokenSource _resetCacheToken = new();
- protected readonly ConcurrentDictionary<string, SemaphoreSlim> _cacheEntries = new();
+ protected readonly ConcurrentDictionary<string, SemaphoreSlim> CacheEntries = new();
#endregion
@@ -43,52 +43,46 @@ namespace Grand.Infrastructure.Caching
public virtual async Task<T> GetAsync<T>(string key, Func<Task<T>> acquire, int cacheTime)
{
- T cacheEntry;
- if (!_cache.TryGetValue(key, out cacheEntry))
+ if (_cache.TryGetValue(key, out T cacheEntry)) return cacheEntry;
+ SemaphoreSlim semaphore = CacheEntries.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
+ await semaphore.WaitAsync();
+ try
{
- SemaphoreSlim slock = _cacheEntries.GetOrAdd(key, k => new SemaphoreSlim(1, 1));
- await slock.WaitAsync();
- try
+ if (!_cache.TryGetValue(key, out cacheEntry))
{
- if (!_cache.TryGetValue(key, out cacheEntry))
- {
- cacheEntry = await acquire();
- _cache.Set(key, cacheEntry, GetMemoryCacheEntryOptions(cacheTime));
- }
- }
- finally
- {
- slock.Release();
+ cacheEntry = await acquire();
+ _cache.Set(key, cacheEntry, GetMemoryCacheEntryOptions(cacheTime));
}
}
+ finally
+ {
+ semaphore.Release();
+ }
return cacheEntry;
}
public virtual T Get<T>(string key, Func<T> acquire)
{
- return Get<T>(key, acquire, CommonHelper.CacheTimeMinutes);
+ return Get(key, acquire, CommonHelper.CacheTimeMinutes);
}
public virtual T Get<T>(string key, Func<T> acquire, int cacheTime)
{
- T cacheEntry;
- if (!_cache.TryGetValue(key, out cacheEntry))
+ if (_cache.TryGetValue(key, out T cacheEntry)) return cacheEntry;
+ SemaphoreSlim semaphore = CacheEntries.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
+ semaphore.Wait();
+ try
{
- SemaphoreSlim slock = _cacheEntries.GetOrAdd(key, k => new SemaphoreSlim(1, 1));
- slock.Wait();
- try
- {
- if (!_cache.TryGetValue(key, out cacheEntry))
- {
- cacheEntry = acquire();
- _cache.Set(key, cacheEntry, GetMemoryCacheEntryOptions(cacheTime));
- }
- }
- finally
+ if (!_cache.TryGetValue(key, out cacheEntry))
{
- slock.Release();
+ cacheEntry = acquire();
+ _cache.Set(key, cacheEntry, GetMemoryCacheEntryOptions(cacheTime));
}
}
+ finally
+ {
+ semaphore.Release();
+ }
return cacheEntry;
}
@@ -104,10 +98,10 @@ namespace Grand.Infrastructure.Caching
public virtual Task RemoveByPrefix(string prefix, bool publisher = true)
{
- var entriesToRemove = _cacheEntries.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
- foreach (var cacheEntrie in entriesToRemove)
+ var entriesToRemove = CacheEntries.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
+ foreach (var cacheEntries in entriesToRemove)
{
- _cache.Remove(cacheEntrie.Key);
+ _cache.Remove(cacheEntries.Key);
}
if (publisher)
@@ -119,7 +113,7 @@ namespace Grand.Infrastructure.Caching
public virtual Task Clear(bool publisher = true)
{
//clear keys
- foreach (var cacheEntry in _cacheEntries.Keys.ToList())
+ foreach (var cacheEntry in CacheEntries.Keys.ToList())
_cache.Remove(cacheEntry);
//cancel
@@ -145,23 +139,21 @@ namespace Grand.Infrastructure.Caching
protected virtual void Dispose(bool disposing)
{
- if (!_disposed)
+ if (_disposed) return;
+ if (disposing)
{
- if (disposing)
- {
- _cache.Dispose();
- }
- _disposed = true;
+ _cache.Dispose();
}
+ _disposed = true;
}
#endregion
#region Utilities
- protected MemoryCacheEntryOptions GetMemoryCacheEntryOptions(int cacheTime)
+ private MemoryCacheEntryOptions GetMemoryCacheEntryOptions(int cacheTime)
{
- var options = new MemoryCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(cacheTime) }
+ var options = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(cacheTime) }
.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token))
.RegisterPostEvictionCallback(PostEvictionCallback);
@@ -171,7 +163,7 @@ namespace Grand.Infrastructure.Caching
private void PostEvictionCallback(object key, object value, EvictionReason reason, object state)
{
if (reason != EvictionReason.Replaced)
- _cacheEntries.TryRemove(key.ToString(), out var _);
+ CacheEntries.TryRemove(key.ToString(), out var _);
}
diff --git a/src/Core/Grand.Infrastructure/Caching/Message/IMessageBus.cs b/src/Core/Grand.Infrastructure/Caching/Message/IMessageBus.cs
index d1a3867e6..f2b34c2de 100644
--- a/src/Core/Grand.Infrastructure/Caching/Message/IMessageBus.cs
+++ b/src/Core/Grand.Infrastructure/Caching/Message/IMessageBus.cs
@@ -2,6 +2,6 @@
{
public interface IMessageBus : IMessagePublisher, IMessageSubscriber
{
- Task OnSubscriptionChanged(IMessageEvent message);
+ void OnSubscriptionChanged(IMessageEvent message);
}
}
diff --git a/src/Core/Grand.Infrastructure/Caching/RabbitMq/CacheMessageEventConsumer.cs b/src/Core/Grand.Infrastructure/Caching/RabbitMq/CacheMessageEventConsumer.cs
index 83c7a3931..da6dd634f 100644
--- a/src/Core/Grand.Infrastructure/Caching/RabbitMq/CacheMessageEventConsumer.cs
+++ b/src/Core/Grand.Infrastructure/Caching/RabbitMq/CacheMessageEventConsumer.cs
@@ -15,7 +15,7 @@ namespace Grand.Infrastructure.Caching.RabbitMq
public async Task Consume(ConsumeContext<CacheMessageEvent> context)
{
var message = context.Message;
- if (RabbitMqMessageCacheManager.ClientId.Equals(message.ClientId)) return;
+ if (RabbitMqMessageCacheManager.ManageClientId.Equals(message.ClientId)) return;
switch (message.MessageType)
{
case (int)MessageEventType.RemoveKey:
diff --git a/src/Core/Grand.Infrastructure/Caching/RabbitMq/RabbitMqMessageCacheManager.cs b/src/Core/Grand.Infrastructure/Caching/RabbitMq/RabbitMqMessageCacheManager.cs
index 347bc7bfa..e24801bed 100644
--- a/src/Core/Grand.Infrastructure/Caching/RabbitMq/RabbitMqMessageCacheManager.cs
+++ b/src/Core/Grand.Infrastructure/Caching/RabbitMq/RabbitMqMessageCacheManager.cs
@@ -7,7 +7,7 @@ namespace Grand.Infrastructure.Caching.RabbitMq
{
public class RabbitMqMessageCacheManager : MemoryCacheBase, ICacheBase
{
- public static readonly string ClientId = Guid.NewGuid().ToString("N");
+ public static readonly string ManageClientId = Guid.NewGuid().ToString("N");
private readonly IMemoryCache _cache;
private readonly IBus _bus;
@@ -22,12 +22,13 @@ namespace Grand.Infrastructure.Caching.RabbitMq
/// Removes the value with the specified key from the cache
/// </summary>
/// <param name="key">Key of cached item</param>
+ /// <param name="publisher">Publisher</param>
public override async Task RemoveAsync(string key, bool publisher = true)
{
_cache.Remove(key);
if (publisher)
- await _bus.Publish(new CacheMessageEvent() { ClientId = ClientId, Key = key, MessageType = (int)MessageEventType.RemoveKey });
+ await _bus.Publish(new CacheMessageEvent { ClientId = ManageClientId, Key = key, MessageType = (int)MessageEventType.RemoveKey });
}
/// <summary>
@@ -37,14 +38,14 @@ namespace Grand.Infrastructure.Caching.RabbitMq
/// <param name="publisher">publisher</param>
public override async Task RemoveByPrefix(string prefix, bool publisher = true)
{
- var entriesToRemove = _cacheEntries.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
- foreach (var cacheEntrie in entriesToRemove)
+ var entriesToRemove = CacheEntries.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
+ foreach (var cacheEntries in entriesToRemove)
{
- _cache.Remove(cacheEntrie.Key);
+ _cache.Remove(cacheEntries.Key);
}
if (publisher)
- await _bus.Publish(new CacheMessageEvent() { ClientId = ClientId, Key = prefix, MessageType = (int)MessageEventType.RemoveByPrefix });
+ await _bus.Publish(new CacheMessageEvent { ClientId = ManageClientId, Key = prefix, MessageType = (int)MessageEventType.RemoveByPrefix });
}
///<summary>
@@ -55,7 +56,7 @@ namespace Grand.Infrastructure.Caching.RabbitMq
{
await base.Clear();
if (publisher)
- await _bus.Publish(new CacheMessageEvent() { ClientId = ClientId, Key = "", MessageType = (int)MessageEventType.ClearCache });
+ await _bus.Publish(new CacheMessageEvent { ClientId = ManageClientId, Key = "", MessageType = (int)MessageEventType.ClearCache });
}
}
}
diff --git a/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageBus.cs b/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageBus.cs
index 4fa35af4e..fe06009c7 100644
--- a/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageBus.cs
+++ b/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageBus.cs
@@ -7,13 +7,13 @@ using System.Diagnostics;
namespace Grand.Infrastructure.Caching.Redis
{
- public class RedisMessageBus : IMessageBus
+ public sealed class RedisMessageBus : IMessageBus
{
private readonly ISubscriber _subscriber;
private readonly IServiceProvider _serviceProvider;
private readonly RedisConfig _redisConfig;
- private static readonly string _clientId = Guid.NewGuid().ToString("N");
+ private static readonly string ClientId = Guid.NewGuid().ToString("N");
public RedisMessageBus(ISubscriber subscriber, IServiceProvider serviceProvider, RedisConfig redisConfig)
{
@@ -27,14 +27,13 @@ namespace Grand.Infrastructure.Caching.Redis
{
try
{
- var pub = _subscriber.Multiplexer.GetSubscriber();
- var clientmsg = new MessageEventClient {
- ClientId = _clientId,
+ var client = new MessageEventClient {
+ ClientId = ClientId,
Key = msg.Key,
MessageType = msg.MessageType
};
- var message = JsonConvert.SerializeObject(clientmsg);
- await pub.PublishAsync(_redisConfig.RedisPubSubChannel, message);
+ var message = JsonConvert.SerializeObject(client);
+ await _subscriber.PublishAsync(_redisConfig.RedisPubSubChannel, message);
}
catch(Exception ex)
{
@@ -42,17 +41,15 @@ namespace Grand.Infrastructure.Caching.Redis
}
}
- public virtual Task SubscribeAsync()
+ public Task SubscribeAsync()
{
- var sub = _subscriber.Multiplexer.GetSubscriber();
-
- sub.SubscribeAsync(_redisConfig.RedisPubSubChannel, async (_, redisValue) =>
+ _subscriber.SubscribeAsync(_redisConfig.RedisPubSubChannel, (_, redisValue) =>
{
try
{
var message = JsonConvert.DeserializeObject<MessageEventClient>(redisValue);
- if (message != null && message.ClientId != _clientId)
- await OnSubscriptionChanged(message);
+ if (message != null && message.ClientId != ClientId)
+ OnSubscriptionChanged(message);
}
catch (Exception ex)
{
@@ -62,26 +59,21 @@ namespace Grand.Infrastructure.Caching.Redis
return Task.CompletedTask;
}
- public async Task OnSubscriptionChanged(IMessageEvent message)
+ public void OnSubscriptionChanged(IMessageEvent message)
{
- using (var scope = _serviceProvider.CreateScope())
+ using var scope = _serviceProvider.CreateScope();
+ var cache = scope.ServiceProvider.GetRequiredService<ICacheBase>();
+ switch (message.MessageType)
{
- var cache = scope.ServiceProvider.GetRequiredService<ICacheBase>();
- switch (message.MessageType)
- {
- case (int)MessageEventType.RemoveKey:
- await cache.RemoveAsync(message.Key, false);
- break;
- case (int)MessageEventType.RemoveByPrefix:
- await cache.RemoveByPrefix(message.Key, false);
- break;
- case (int)MessageEventType.ClearCache:
- await cache.Clear(false);
- break;
- default:
- break;
- }
-
+ case (int)MessageEventType.RemoveKey:
+ _ = cache.RemoveAsync(message.Key, false);
+ break;
+ case (int)MessageEventType.RemoveByPrefix:
+ _ = cache.RemoveByPrefix(message.Key, false);
+ break;
+ case (int)MessageEventType.ClearCache:
+ _ = cache.Clear(false);
+ break;
}
}
}
diff --git a/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageCacheManager.cs b/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageCacheManager.cs
index 502f271a9..a45914902 100644
--- a/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageCacheManager.cs
+++ b/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageCacheManager.cs
@@ -20,12 +20,13 @@ namespace Grand.Infrastructure.Caching.Redis
/// Removes the value with the specified key from the cache
/// </summary>
/// <param name="key">Key of cached item</param>
+ /// <param name="publisher">Publisher</param>
public override Task RemoveAsync(string key, bool publisher = true)
{
_cache.Remove(key);
if (publisher)
- _messageBus.PublishAsync(new MessageEvent() { Key = key, MessageType = (int)MessageEventType.RemoveKey });
+ _messageBus.PublishAsync(new MessageEvent { Key = key, MessageType = (int)MessageEventType.RemoveKey });
return Task.CompletedTask;
}
@@ -37,14 +38,14 @@ namespace Grand.Infrastructure.Caching.Redis
/// <param name="publisher">publisher</param>
public override Task RemoveByPrefix(string prefix, bool publisher = true)
{
- var entriesToRemove = _cacheEntries.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
- foreach (var cacheEntrie in entriesToRemove)
+ var entriesToRemove = CacheEntries.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
+ foreach (var cacheEntries in entriesToRemove)
{
- _cache.Remove(cacheEntrie.Key);
+ _cache.Remove(cacheEntries.Key);
}
if (publisher)
- _messageBus.PublishAsync(new MessageEvent() { Key = prefix, MessageType = (int)MessageEventType.RemoveByPrefix });
+ _messageBus.PublishAsync(new MessageEvent { Key = prefix, MessageType = (int)MessageEventType.RemoveByPrefix });
return Task.CompletedTask;
}
@@ -57,7 +58,7 @@ namespace Grand.Infrastructure.Caching.Redis
{
base.Clear();
if (publisher)
- _messageBus.PublishAsync(new MessageEvent() { Key = "", MessageType = (int)MessageEventType.ClearCache });
+ _messageBus.PublishAsync(new MessageEvent { Key = "", MessageType = (int)MessageEventType.ClearCache });
return Task.CompletedTask;
}
diff --git a/src/Core/Grand.Infrastructure/Configuration/AdvancedConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AdvancedConfig.cs
index 0c32f8d51..c41f3abee 100644
--- a/src/Core/Grand.Infrastructure/Configuration/AdvancedConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/AdvancedConfig.cs
@@ -1,6 +1,6 @@
namespace Grand.Infrastructure.Configuration
{
- public partial class AdvancedConfig
+ public class AdvancedConfig
{
public string DbConnectionString { get; set; }
public int DbProvider { get; set; }
diff --git a/src/Core/Grand.Infrastructure/Configuration/AmazonConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AmazonConfig.cs
index 482e98d7d..e78f0671c 100644
--- a/src/Core/Grand.Infrastructure/Configuration/AmazonConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/AmazonConfig.cs
@@ -1,6 +1,6 @@
namespace Grand.Infrastructure.Configuration
{
- public partial class AmazonConfig
+ public class AmazonConfig
{
/// <summary>
/// Amazon Access Key
diff --git a/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs
index 1ed27d99e..fe4248337 100644
--- a/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs
@@ -3,7 +3,7 @@ namespace Grand.Infrastructure.Configuration
/// <summary>
/// Represents a Application Config
/// </summary>
- public partial class AppConfig
+ public class AppConfig
{
public AppConfig()
{
diff --git a/src/Core/Grand.Infrastructure/Configuration/ApplicationInsightsConfig.cs b/src/Core/Grand.Infrastructure/Configuration/ApplicationInsightsConfig.cs
index b09683ef4..0c0abea16 100644
--- a/src/Core/Grand.Infrastructure/Configuration/ApplicationInsightsConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/ApplicationInsightsConfig.cs
@@ -1,6 +1,6 @@
namespace Grand.Infrastructure.Configuration
{
- public partial class ApplicationInsightsConfig
+ public class ApplicationInsightsConfig
{
public bool Enabled { get; set; }
}
diff --git a/src/Core/Grand.Infrastructure/Configuration/AzureConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AzureConfig.cs
index aed43fbe5..19b7a23a9 100644
--- a/src/Core/Grand.Infrastructure/Configuration/AzureConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/AzureConfig.cs
@@ -1,6 +1,6 @@
namespace Grand.Infrastructure.Configuration
{
- public partial class AzureConfig
+ public class AzureConfig
{
/// <summary>
/// A value indicating whether the site is run on Windows Azure Web Apps
diff --git a/src/Core/Grand.Infrastructure/Configuration/BackendAPIConfig.cs b/src/Core/Grand.Infrastructure/Configuration/BackendAPIConfig.cs
index 460c1b97f..ee241c97e 100644
--- a/src/Core/Grand.Infrastructure/Configuration/BackendAPIConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/BackendAPIConfig.cs
@@ -1,6 +1,6 @@
namespace Grand.Infrastructure.Configuration
{
- public partial class BackendAPIConfig
+ public class BackendAPIConfig
{
public bool Enabled { get; set; }
public bool UseSwagger { get; set; }
diff --git a/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs b/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs
index 0563a0e8a..5f0e848de 100644
--- a/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs
@@ -1,6 +1,6 @@
namespace Grand.Infrastructure.Configuration
{
- public partial class DatabaseConfig
+ public class DatabaseConfig
{
/// <summary>
/// Gets or sets a value indicating whether use LiteDB database for your application
diff --git a/src/Core/Grand.Infrastructure/Configuration/ExtensionsConfig.cs b/src/Core/Grand.Infrastructure/Configuration/ExtensionsConfig.cs
index a1ad6bc7f..2d4bb7536 100644
--- a/src/Core/Grand.Infrastructure/Configuration/ExtensionsConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/ExtensionsConfig.cs
@@ -3,7 +3,7 @@ namespace Grand.Infrastructure.Configuration
/// <summary>
/// Represents a Extensions Config
/// </summary>
- public partial class ExtensionsConfig
+ public class ExtensionsConfig
{
/// <summary>
/// Indicates whether we disabled upload plugins/themes
diff --git a/src/Core/Grand.Infrastructure/Configuration/RabbitConfig.cs b/src/Core/Grand.Infrastructure/Configuration/RabbitConfig.cs
index e8b97e96e..5c5425c6b 100644
--- a/src/Core/Grand.Infrastructure/Configuration/RabbitConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/RabbitConfig.cs
@@ -1,6 +1,6 @@
namespace Grand.Infrastructure.Configuration
{
- public partial class RabbitConfig
+ public class RabbitConfig
{
public bool RabbitEnabled { get; set; }
public bool RabbitCachePubSubEnabled { get; set; }
diff --git a/src/Core/Grand.Infrastructure/Configuration/RedisConfig.cs b/src/Core/Grand.Infrastructure/Configuration/RedisConfig.cs
index 615ce3fcf..25aabf1fc 100644
--- a/src/Core/Grand.Infrastructure/Configuration/RedisConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/RedisConfig.cs
@@ -1,6 +1,6 @@
namespace Grand.Infrastructure.Configuration
{
- public partial class RedisConfig
+ public class RedisConfig
{
/// <summary>
/// Enable the Publish/Subscribe messaging with redis to manage memory cache on every server
diff --git a/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs b/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs
index 560a963dd..8ad28a194 100644
--- a/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs
@@ -1,6 +1,6 @@
namespace Grand.Infrastructure.Configuration
{
- public partial class SecurityConfig
+ public class SecurityConfig
{
/// <summary>
/// Gets or sets a value indicating whether to use Forwards proxied headers onto current request
diff --git a/src/Core/Grand.Infrastructure/Configuration/UrlRewriteConfig.cs b/src/Core/Grand.Infrastructure/Configuration/UrlRewriteConfig.cs
index f7a080fde..c2272a055 100644
--- a/src/Core/Grand.Infrastructure/Configuration/UrlRewriteConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/UrlRewriteConfig.cs
@@ -1,6 +1,6 @@
namespace Grand.Infrastructure.Configuration
{
- public partial class UrlRewriteConfig
+ public class UrlRewriteConfig
{
/// <summary>
/// Gets or sets a value indicating whether we use url rewrite
diff --git a/src/Core/Grand.Infrastructure/Events/EntityCacheEvent.cs b/src/Core/Grand.Infrastructure/Events/EntityCacheEvent.cs
index 9a5cdec4e..2753463c1 100644
--- a/src/Core/Grand.Infrastructure/Events/EntityCacheEvent.cs
+++ b/src/Core/Grand.Infrastructure/Events/EntityCacheEvent.cs
@@ -4,10 +4,10 @@ namespace Grand.Infrastructure.Events
{
public class EntityCacheEvent : INotification
{
- public EntityCacheEvent(string entity, CacheEvent cacheevent)
+ public EntityCacheEvent(string entity, CacheEvent @event)
{
Entity = entity;
- Event = cacheevent;
+ Event = @event;
}
public string Entity { get; private set; }
public CacheEvent Event { get; private set; }
diff --git a/src/Core/Grand.Infrastructure/Events/EntityDeleted.cs b/src/Core/Grand.Infrastructure/Events/EntityDeleted.cs
index 9daf244a8..ef8b36c83 100644
--- a/src/Core/Grand.Infrastructure/Events/EntityDeleted.cs
+++ b/src/Core/Grand.Infrastructure/Events/EntityDeleted.cs
@@ -4,7 +4,7 @@ using MediatR;
namespace Grand.Infrastructure.Events
{
/// <summary>
- /// A container for passing entities that have been deleted. This is not used for entities that are deleted logicaly via a bit column.
+ /// A container for passing entities that have been deleted.
/// </summary>
/// <typeparam name="T"></typeparam>
public class EntityDeleted<T> : INotification where T : ParentEntity
diff --git a/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs b/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs
index 6b03d8dd7..a99ba09f5 100644
--- a/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs
+++ b/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs
@@ -12,10 +12,7 @@ namespace Grand.Infrastructure.Extensions
if (method == null)
throw new ArgumentNullException(nameof(method));
- if (store == null)
- return true;
-
- return IsAuthenticateStore(method, store.Id);
+ return store == null || IsAuthenticateStore(method, store.Id);
}
public static bool IsAuthenticateStore(this IProvider method, string storeId)
@@ -29,10 +26,7 @@ namespace Grand.Infrastructure.Extensions
if (method.LimitedToStores == null || !method.LimitedToStores.Any())
return true;
- if (!method.LimitedToStores.Contains(storeId))
- return false;
-
- return true;
+ return method.LimitedToStores.Contains(storeId);
}
public static bool IsAuthenticateGroup(this IProvider method, Customer customer)
@@ -46,10 +40,7 @@ namespace Grand.Infrastructure.Extensions
if (method.LimitedToGroups == null || !method.LimitedToGroups.Any())
return true;
- if (!method.LimitedToGroups.ContainsAny(customer.Groups.Select(x => x)))
- return false;
-
- return true;
+ return method.LimitedToGroups.ContainsAny(customer.Groups.Select(x => x));
}
}
}
diff --git a/src/Core/Grand.Infrastructure/Migrations/MigrationManager.cs b/src/Core/Grand.Infrastructure/Migrations/MigrationManager.cs
index 74b25ac16..68fd4b4de 100644
--- a/src/Core/Grand.Infrastructure/Migrations/MigrationManager.cs
+++ b/src/Core/Grand.Infrastructure/Migrations/MigrationManager.cs
@@ -1,5 +1,5 @@
using Grand.Infrastructure.Plugins;
-using Grand.Infrastructure.TypeSearchers;
+using Grand.Infrastructure.TypeSearch;
namespace Grand.Infrastructure.Migrations
{
@@ -9,7 +9,7 @@ namespace Grand.Infrastructure.Migrations
public MigrationManager()
{
- var typeSearcher = new AppTypeSearcher();
+ var typeSearcher = new TypeSearcher();
_migrationConfigurations = typeSearcher.ClassesOfType<IMigration>();
}
@@ -20,15 +20,14 @@ namespace Grand.Infrastructure.Migrations
public IEnumerable<IMigration> GetAllMigrations()
{
return _migrationConfigurations
- .Where(mg => PluginExtensions.OnlyInstalledPlugins(mg))
+ .Where(PluginExtensions.OnlyInstalledPlugins)
.Select(mg => (IMigration)Activator.CreateInstance(mg))
- .OrderBy(mg => mg.Priority);
+ .OrderBy(mg => mg!.Priority);
}
/// <summary>
/// Get current migrations
/// </summary>
- /// <param name="dbVersion"></param>
/// <returns></returns>
public IEnumerable<IMigration> GetCurrentMigrations()
{
diff --git a/src/Core/Grand.Infrastructure/ModelBinding/GrandResourceDisplayNameAttribute.cs b/src/Core/Grand.Infrastructure/ModelBinding/GrandResourceDisplayNameAttribute.cs
index 4d9a83b15..3d51ce06d 100644
--- a/src/Core/Grand.Infrastructure/ModelBinding/GrandResourceDisplayNameAttribute.cs
+++ b/src/Core/Grand.Infrastructure/ModelBinding/GrandResourceDisplayNameAttribute.cs
@@ -7,12 +7,6 @@ namespace Grand.Infrastructure.ModelBinding
/// </summary>
public class GrandResourceDisplayNameAttribute : DisplayNameAttribute, IModelAttribute
{
- #region Fields
-
- private string _resourceValue = string.Empty;
-
- #endregion
-
#region Ctor
/// <summary>
@@ -36,9 +30,7 @@ namespace Grand.Infrastructure.ModelBinding
/// <summary>
/// Gets name of the attribute
/// </summary>
- public string Name {
- get { return nameof(GrandResourceDisplayNameAttribute); }
- }
+ public string Name => nameof(GrandResourceDisplayNameAttribute);
#endregion
}
diff --git a/src/Core/Grand.Infrastructure/Models/BaseModel.cs b/src/Core/Grand.Infrastructure/Models/BaseModel.cs
index 34a92d934..611c86eb8 100644
--- a/src/Core/Grand.Infrastructure/Models/BaseModel.cs
+++ b/src/Core/Grand.Infrastructure/Models/BaseModel.cs
@@ -6,7 +6,7 @@ namespace Grand.Infrastructure.Models
/// <summary>
/// Represents base model
/// </summary>
- public partial class BaseModel
+ public class BaseModel
{
#region Ctor
diff --git a/src/Core/Grand.Infrastructure/OperatingSystem.cs b/src/Core/Grand.Infrastructure/OperatingSystem.cs
index 8585d109d..d82be46a6 100644
--- a/src/Core/Grand.Infrastructure/OperatingSystem.cs
+++ b/src/Core/Grand.Infrastructure/OperatingSystem.cs
@@ -4,13 +4,19 @@ namespace Grand.Infrastructure
{
public static class OperatingSystem
{
- public static bool IsWindows() =>
- RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
+ public static bool IsWindows()
+ {
+ return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
+ }
- public static bool IsMacOS() =>
- RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
+ public static bool IsMacOs()
+ {
+ return RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
+ }
- public static bool IsLinux() =>
- RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
+ public static bool IsLinux()
+ {
+ return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
+ }
}
}
diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs b/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs
index 868c2e8a9..9ba22d048 100644
--- a/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs
+++ b/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs
@@ -7,13 +7,8 @@ namespace Grand.Infrastructure.Plugins
{
public static bool OnlyInstalledPlugins(Type type)
{
- var value = true;
var plugin = PluginManager.FindPlugin(type);
- if (plugin != null)
- {
- return plugin.Installed;
- }
- return value;
+ return plugin == null || plugin.Installed;
}
public static IList<string> ParseInstalledPluginsFile(string filePath)
@@ -22,16 +17,13 @@ namespace Grand.Infrastructure.Plugins
return new List<string>();
var text = File.ReadAllText(filePath);
- if (String.IsNullOrEmpty(text))
- return new List<string>();
-
- return JsonSerializer.Deserialize<List<string>>(text);
+ return string.IsNullOrEmpty(text) ? new List<string>() : JsonSerializer.Deserialize<List<string>>(text);
}
public static async Task SaveInstalledPluginsFile(IList<string> pluginSystemNames, string filePath)
{
//serialize
- string result = JsonSerializer.Serialize(pluginSystemNames, new JsonSerializerOptions { WriteIndented = true });
+ var result = JsonSerializer.Serialize(pluginSystemNames, new JsonSerializerOptions { WriteIndented = true });
//save
await File.WriteAllTextAsync(filePath, result);
await Task.CompletedTask;
@@ -44,11 +36,11 @@ namespace Grand.Infrastructure.Plugins
public static async Task MarkPluginAsInstalled(string systemName)
{
if (string.IsNullOrEmpty(systemName))
- throw new ArgumentNullException("systemName");
+ throw new ArgumentNullException(nameof(systemName));
var filePath = CommonPath.InstalledPluginsFilePath;
if (!File.Exists(filePath))
- using (File.Create(filePath))
+ await using (File.Create(filePath))
{
//we use 'using' to close the file after it's created
}
@@ -73,7 +65,7 @@ namespace Grand.Infrastructure.Plugins
var filePath = CommonPath.InstalledPluginsFilePath;
if (!File.Exists(filePath))
- using (File.Create(filePath))
+ await using (File.Create(filePath))
{
}
diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginInfo.cs b/src/Core/Grand.Infrastructure/Plugins/PluginInfo.cs
index 2c235057c..16d1b5f4e 100644
--- a/src/Core/Grand.Infrastructure/Plugins/PluginInfo.cs
+++ b/src/Core/Grand.Infrastructure/Plugins/PluginInfo.cs
@@ -4,7 +4,7 @@ using System.Reflection;
namespace Grand.Infrastructure.Plugins
{
- public class PluginInfo
+ public sealed class PluginInfo
{
public PluginInfo(
FileInfo originalAssemblyFile,
@@ -23,64 +23,64 @@ namespace Grand.Infrastructure.Plugins
/// <summary>
/// Plugin type
/// </summary>
- public virtual string PluginFileName { get; set; }
+ public string PluginFileName { get; set; }
/// <summary>
/// Plugin type
/// </summary>
- public virtual Type PluginType { get; set; }
+ public Type PluginType { get; set; }
/// <summary>
/// The assembly that has been shadow copied that is active in the application
/// </summary>
- public virtual Assembly ReferencedAssembly { get; internal set; }
+ public Assembly ReferencedAssembly { get; internal set; }
/// <summary>
/// The original assembly file that a shadow copy was made from it
/// </summary>
- public virtual FileInfo OriginalAssemblyFile { get; internal set; }
+ public FileInfo OriginalAssemblyFile { get; internal set; }
/// <summary>
/// Gets or sets the plugin group
/// </summary>
- public virtual string Group { get; set; }
+ public string Group { get; set; }
/// <summary>
/// Gets or sets the friendly name
/// </summary>
- public virtual string FriendlyName { get; set; }
+ public string FriendlyName { get; set; }
/// <summary>
/// Gets or sets the system name
/// </summary>
- public virtual string SystemName { get; set; }
+ public string SystemName { get; set; }
/// <summary>
/// Gets or sets the version
/// </summary>
- public virtual string Version { get; set; }
+ public string Version { get; set; }
/// <summary>
/// Gets or sets the supported version
/// </summary>
- public virtual string SupportedVersion { get; set; }
+ public string SupportedVersion { get; set; }
/// <summary>
/// Gets or sets the author
/// </summary>
- public virtual string Author { get; set; }
+ public string Author { get; set; }
/// <summary>
/// Gets or sets the display order
/// </summary>
- public virtual int DisplayOrder { get; set; }
+ public int DisplayOrder { get; set; }
/// <summary>
/// Gets or sets the value indicating whether plugin is installed
/// </summary>
- public virtual bool Installed { get; set; }
+ public bool Installed { get; set; }
- public virtual T Instance<T>(IServiceProvider serviceProvider) where T : class, IPlugin
+ public T Instance<T>(IServiceProvider serviceProvider) where T : class, IPlugin
{
object instance;
try
diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs b/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs
index c1cdb13a1..586ae4442 100644
--- a/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs
+++ b/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs
@@ -46,19 +46,17 @@ namespace Grand.Infrastructure.Plugins
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Load(IMvcCoreBuilder mvcCoreBuilder, IConfiguration configuration)
{
- var config = new ExtensionsConfig();
- configuration.GetSection("Extensions").Bind(config);
+ _config = new ExtensionsConfig();
+ configuration.GetSection("Extensions").Bind(_config);
- var advconfig = new AdvancedConfig();
- configuration.GetSection("Advanced").Bind(advconfig);
+ var advConfig = new AdvancedConfig();
+ configuration.GetSection("Advanced").Bind(advConfig);
lock (_synLock)
{
if (mvcCoreBuilder == null)
throw new ArgumentNullException(nameof(mvcCoreBuilder));
-
- _config = config ?? throw new ArgumentNullException(nameof(config));
-
+
_pluginFolder = new DirectoryInfo(CommonPath.PluginsPath);
_copyFolder = new DirectoryInfo(CommonPath.PluginsCopyPath);
@@ -66,19 +64,19 @@ namespace Grand.Infrastructure.Plugins
try
{
var installedPluginSystemNames =
- advconfig.InstalledPlugins.Any() ? advconfig.InstalledPlugins :
+ advConfig.InstalledPlugins.Any() ? advConfig.InstalledPlugins :
PluginExtensions.ParseInstalledPluginsFile(CommonPath.InstalledPluginsFilePath);
Log.Information("Creating shadow copy folder and querying for dlls");
Directory.CreateDirectory(_pluginFolder.FullName);
Directory.CreateDirectory(_copyFolder.FullName);
var binFiles = _copyFolder.GetFiles("*", SearchOption.AllDirectories);
- if (config.PluginShadowCopy)
+ if (_config.PluginShadowCopy)
{
//clear out shadow plugins
foreach (var f in binFiles)
{
- Log.Information($"Deleting {f.Name}");
+ Log.Information("Deleting {FName}", f.Name);
try
{
var fileName = Path.GetFileName(f.FullName);
@@ -99,7 +97,7 @@ namespace Grand.Infrastructure.Plugins
{
if (plugin.SupportedVersion != GrandVersion.SupportedPluginVersion)
{
- Log.Information($"Incompatible plugin {plugin.SystemName}");
+ Log.Information("Incompatible plugin {PluginSystemName}", plugin.SystemName);
//set as not installed
referencedPlugins.Add(plugin);
continue;
@@ -107,9 +105,9 @@ namespace Grand.Infrastructure.Plugins
//some validation
if (string.IsNullOrWhiteSpace(plugin.SystemName))
- throw new Exception(string.Format("The plugin '{0}' has no system name.", plugin.SystemName));
+ throw new Exception($"The plugin '{plugin.SystemName}' has no system name.");
if (referencedPlugins.Contains(plugin))
- throw new Exception(string.Format("The plugin with '{0}' system name is already defined", plugin.SystemName));
+ throw new Exception($"The plugin with '{plugin.SystemName}' system name is already defined");
//set 'Installed' property
plugin.Installed = installedPluginSystemNames
@@ -117,10 +115,10 @@ namespace Grand.Infrastructure.Plugins
try
{
- if (!config.PluginShadowCopy)
+ if (!_config.PluginShadowCopy)
{
//remove deps.json files
- var depsFiles = plugin.OriginalAssemblyFile.Directory.GetFiles("*.deps.json", SearchOption.TopDirectoryOnly);
+ var depsFiles = plugin.OriginalAssemblyFile.Directory!.GetFiles("*.deps.json", SearchOption.TopDirectoryOnly);
foreach (var f in depsFiles)
{
try
@@ -154,16 +152,15 @@ namespace Grand.Infrastructure.Plugins
}
catch (ReflectionTypeLoadException ex)
{
- var msg = string.Format("Plugin '{0}'. ", plugin.FriendlyName);
- foreach (var e in ex.LoaderExceptions)
- msg += e.Message + Environment.NewLine;
+ var msg = $"Plugin '{plugin.FriendlyName}'. ";
+ msg = ex.LoaderExceptions.Aggregate(msg, (current, e) => current + (e!.Message + Environment.NewLine));
var fail = new Exception(msg, ex);
throw fail;
}
catch (Exception ex)
{
- var msg = string.Format("Plugin '{0}'. {1}", plugin.FriendlyName, ex.Message);
+ var msg = $"Plugin '{plugin.FriendlyName}'. {ex.Message}";
var fail = new Exception(msg, ex);
throw fail;
@@ -193,11 +190,8 @@ namespace Grand.Infrastructure.Plugins
if (typeAssembly == null)
throw new ArgumentNullException(nameof(typeAssembly));
- if (ReferencedPlugins == null)
- return null;
-
- return ReferencedPlugins.FirstOrDefault(plugin => plugin.ReferencedAssembly != null
- && plugin.ReferencedAssembly.FullName.Equals(typeAssembly.GetTypeInfo().Assembly.FullName, StringComparison.OrdinalIgnoreCase));
+ return ReferencedPlugins?.FirstOrDefault(plugin => plugin.ReferencedAssembly != null
+ && plugin.ReferencedAssembly.FullName!.Equals(typeAssembly.GetTypeInfo().Assembly.FullName, StringComparison.OrdinalIgnoreCase));
}
@@ -218,7 +212,7 @@ namespace Grand.Infrastructure.Plugins
private static IList<PluginInfo> GetPluginInfo()
{
if (_pluginFolder == null)
- throw new ArgumentNullException("pluginFolder");
+ throw new ArgumentNullException(nameof(_pluginFolder));
var result = new List<PluginInfo>();
foreach (var pluginFile in _pluginFolder.GetFiles("*.dll", SearchOption.AllDirectories))
@@ -243,9 +237,9 @@ namespace Grand.Infrastructure.Plugins
private static PluginInfo PreparePluginInfo(FileInfo pluginFile)
{
- var _plug = _config.PluginShadowCopy ? ShadowCopyFile(pluginFile, Directory.CreateDirectory(_copyFolder.FullName)) : pluginFile;
+ var plug = _config.PluginShadowCopy ? ShadowCopyFile(pluginFile, Directory.CreateDirectory(_copyFolder.FullName)) : pluginFile;
- Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(_plug.FullName);
+ Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(plug.FullName);
var pluginInfo = assembly.GetCustomAttribute<PluginInfoAttribute>();
if (pluginInfo == null)
@@ -261,7 +255,7 @@ namespace Grand.Infrastructure.Plugins
Version = pluginInfo.Version,
SupportedVersion = pluginInfo.SupportedVersion,
Author = pluginInfo.Author,
- PluginFileName = _plug.Name,
+ PluginFileName = plug.Name,
OriginalAssemblyFile = pluginFile,
ReferencedAssembly = assembly
};
@@ -288,48 +282,45 @@ namespace Grand.Infrastructure.Plugins
var areFilesIdentical = shadowCopiedPlug.CreationTimeUtc.Ticks >= plug.CreationTimeUtc.Ticks;
if (areFilesIdentical)
{
- Log.Information($"Not copying; files appear identical: {shadowCopiedPlug.Name}");
+ Log.Information("Not copying; files appear identical: {Name}", shadowCopiedPlug.Name);
return shadowCopiedPlug;
}
- else
+
+ //delete an existing file
+ Log.Information("New plugin found; Deleting the old file: {Name}", shadowCopiedPlug.Name);
+ try
{
- //delete an existing file
- Log.Information($"New plugin found; Deleting the old file: {shadowCopiedPlug.Name}");
- try
- {
- File.Delete(shadowCopiedPlug.FullName);
- }
- catch (Exception ex)
- {
- shouldCopy = false;
- Log.Error(ex, "PluginManager");
- }
+ File.Delete(shadowCopiedPlug.FullName);
}
+ catch (Exception ex)
+ {
+ shouldCopy = false;
+ Log.Error(ex, "PluginManager");
+ }
+ }
+
+ if (!shouldCopy) return shadowCopiedPlug;
+ try
+ {
+ File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);
}
- if (shouldCopy)
+ catch (IOException)
{
+ Log.Information("{FullName} is locked, attempting to rename", shadowCopiedPlug.FullName);
+ //this occurs when the files are locked,
+ //for some reason devenv locks plugin files some times and for another crazy reason you are allowed to rename them
+ //which releases the lock, so that it what we are doing here, once it's renamed, we can re-shadow copy
try
{
- File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);
+ var oldFile = shadowCopiedPlug.FullName + Guid.NewGuid().ToString("N") + ".old";
+ File.Move(shadowCopiedPlug.FullName, oldFile);
}
- catch (IOException)
+ catch (IOException exc)
{
- Log.Information($"{shadowCopiedPlug.FullName} is locked, attempting to rename");
- //this occurs when the files are locked,
- //for some reason devenv locks plugin files some times and for another crazy reason you are allowed to rename them
- //which releases the lock, so that it what we are doing here, once it's renamed, we can re-shadow copy
- try
- {
- var oldFile = shadowCopiedPlug.FullName + Guid.NewGuid().ToString("N") + ".old";
- File.Move(shadowCopiedPlug.FullName, oldFile);
- }
- catch (IOException exc)
- {
- throw new IOException(shadowCopiedPlug.FullName + " rename failed, cannot initialize plugin", exc);
- }
- //ok, we've made it this far, now retry the shadow copy
- File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);
+ throw new IOException(shadowCopiedPlug.FullName + " rename failed, cannot initialize plugin", exc);
}
+ //ok, we've made it this far, now retry the shadow copy
+ File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);
}
return shadowCopiedPlug;
@@ -389,9 +380,7 @@ namespace Grand.Infrastructure.Plugins
{
if (folder == null) return false;
if (folder.Name.Equals("bin", StringComparison.InvariantCultureIgnoreCase)) return false;
- if (folder.Parent == null) return false;
- if (!folder.Parent.Name.Equals("Plugins", StringComparison.OrdinalIgnoreCase)) return false;
- return true;
+ return folder.Parent != null && folder.Parent.Name.Equals("Plugins", StringComparison.OrdinalIgnoreCase);
}
diff --git a/src/Core/Grand.Infrastructure/Roslyn/ResultCompiler.cs b/src/Core/Grand.Infrastructure/Roslyn/ResultCompiler.cs
index 8c6501ddc..679509619 100644
--- a/src/Core/Grand.Infrastructure/Roslyn/ResultCompiler.cs
+++ b/src/Core/Grand.Infrastructure/Roslyn/ResultCompiler.cs
@@ -2,7 +2,7 @@
namespace Grand.Infrastructure.Roslyn
{
- public partial class ResultCompiler
+ public class ResultCompiler
{
public ResultCompiler()
{
diff --git a/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs b/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs
index 4c645b40c..22076ee0f 100644
--- a/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs
+++ b/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs
@@ -16,8 +16,8 @@ namespace Grand.Infrastructure.Roslyn
{
#region Const
- public const string ScriptPath = "Roslyn";
- public const string ShadowCopyScriptPath = "Roslyn/bin";
+ private const string ScriptPath = "Roslyn";
+ private const string ShadowCopyScriptPath = "Roslyn/bin";
#endregion
@@ -72,12 +72,12 @@ namespace Grand.Infrastructure.Roslyn
var ctxFiles = roslynFolder.GetFiles("*.csx", SearchOption.TopDirectoryOnly);
foreach (var file in ctxFiles)
{
- var csxcript = new ResultCompiler
+ var csxScript = new ResultCompiler
{
OriginalFile = file.FullName
};
- string ctxCode = File.ReadAllText(file.FullName);
+ var ctxCode = File.ReadAllText(file.FullName);
var sourceFileResolver = new SourceFileResolver(ImmutableArray<string>.Empty, AppContext.BaseDirectory);
var opts = ScriptOptions.Default.WithSourceResolver(sourceFileResolver);
var script = CSharpScript.Create(ctxCode, opts);
@@ -92,27 +92,27 @@ namespace Grand.Infrastructure.Roslyn
var shadowFileName = Path.Combine(_shadowCopyScriptPath.FullName, file.Name + "-" + Guid.NewGuid().ToString("D") + ".dll");
File.WriteAllBytes(shadowFileName, ms.ToArray());
Assembly shadowCopiedAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(shadowFileName);
- csxcript.DLLAssemblyFile = shadowFileName;
- csxcript.ReferencedAssembly = shadowCopiedAssembly;
- csxcript.IsCompiled = true;
+ csxScript.DLLAssemblyFile = shadowFileName;
+ csxScript.ReferencedAssembly = shadowCopiedAssembly;
+ csxScript.IsCompiled = true;
applicationPartManager.ApplicationParts.Add(new AssemblyPart(shadowCopiedAssembly));
}
else
{
foreach (var diagnostic in compilationResult.Diagnostics)
{
- csxcript.ErrorInfo.Add(diagnostic.ToString());
+ csxScript.ErrorInfo.Add(diagnostic.ToString());
}
}
}
- referencedScripts.Add(csxcript);
+ referencedScripts.Add(csxScript);
}
ReferencedScripts = referencedScripts;
}
catch (Exception ex)
{
- var msg = string.Format("Roslyn '{0}'", ex.Message);
+ var msg = $"Roslyn '{ex.Message}'";
var fail = new Exception(msg, ex);
throw fail;
@@ -136,21 +136,20 @@ namespace Grand.Infrastructure.Roslyn
var opts = ScriptOptions.Default.WithSourceResolver(sourceFileResolver);
var script = CSharpScript.Create(code, opts);
var compilation = script.GetCompilation();
- using (var ms = new MemoryStream())
+ using var ms = new MemoryStream();
+ var compilationResult = compilation.Emit(ms);
+ if (compilationResult.Success)
{
- var compilationResult = compilation.Emit(ms);
- if (compilationResult.Success)
+ result.IsCompiled = true;
+ }
+ else
+ {
+ foreach (var diagnostic in compilationResult.Diagnostics)
{
- result.IsCompiled = true;
- }
- else
- {
- foreach (var diagnostic in compilationResult.Diagnostics)
- {
- result.ErrorInfo.Add(diagnostic.ToString());
- }
+ result.ErrorInfo.Add(diagnostic.ToString());
}
}
+
return result;
}
}
diff --git a/src/Core/Grand.Infrastructure/Startup/ApplicationInsightsSubscriber.cs b/src/Core/Grand.Infrastructure/Startup/ApplicationInsightsSubscriber.cs
index 207ee7700..e524a85bb 100644
--- a/src/Core/Grand.Infrastructure/Startup/ApplicationInsightsSubscriber.cs
+++ b/src/Core/Grand.Infrastructure/Startup/ApplicationInsightsSubscriber.cs
@@ -11,19 +11,12 @@ namespace Grand.Infrastructure.Startup
{
private readonly ReflectionEventSubscriber _subscriber;
- private TelemetryClient _telementryClient;
- protected TelemetryClient TelementryClient {
- get {
- if (_telementryClient == null)
- {
- _telementryClient = _services.BuildServiceProvider().GetRequiredService<TelemetryClient>();
- }
- return _telementryClient;
- }
- }
+ private TelemetryClient _telemetryClient;
+
+ private TelemetryClient TelemetryClient => _telemetryClient ??= _services.BuildServiceProvider().GetRequiredService<TelemetryClient>();
private readonly IServiceCollection _services;
- private readonly ConcurrentDictionary<int, Operation> dictionary = new ();
+ private readonly ConcurrentDictionary<int, Operation> _dictionary = new ();
record Operation(string Name, string Command);
@@ -42,25 +35,23 @@ namespace Grand.Infrastructure.Startup
private void Handle(CommandStartedEvent cmdStart)
{
- dictionary.TryAdd(cmdStart.RequestId, new Operation(cmdStart.CommandName, cmdStart.Command.ToString()));
+ _dictionary.TryAdd(cmdStart.RequestId, new Operation(cmdStart.CommandName, cmdStart.Command.ToString()));
}
private void Handle(CommandSucceededEvent cmdSuccess)
{
- if (dictionary.TryGetValue(cmdSuccess.RequestId, out var operation))
- {
- var telemetry = new DependencyTelemetry {
- Data = operation.Command,
- Name = operation.Name,
- Type = "MongoDB",
- Timestamp = DateTime.UtcNow.Subtract(cmdSuccess.Duration),
- Duration = cmdSuccess.Duration,
- Success = true,
- };
- TelementryClient?.TrackDependency(telemetry);
-
- dictionary.TryRemove(cmdSuccess.RequestId, out var _);
- }
+ if (!_dictionary.TryGetValue(cmdSuccess.RequestId, out var operation)) return;
+ var telemetry = new DependencyTelemetry {
+ Data = operation.Command,
+ Name = operation.Name,
+ Type = "MongoDB",
+ Timestamp = DateTime.UtcNow.Subtract(cmdSuccess.Duration),
+ Duration = cmdSuccess.Duration,
+ Success = true
+ };
+ TelemetryClient?.TrackDependency(telemetry);
+
+ _dictionary.TryRemove(cmdSuccess.RequestId, out _);
}
}
}
diff --git a/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs b/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs
index c7d1636e4..710edccdc 100644
--- a/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs
+++ b/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs
@@ -39,33 +39,33 @@ namespace Grand.Infrastructure.Startup
var dataProviderSettings = DataSettingsManager.LoadSettings();
if (string.IsNullOrEmpty(dataProviderSettings.ConnectionString))
{
- serviceCollection.AddTransient(c => dataProviderSettings);
+ serviceCollection.AddTransient(_ => dataProviderSettings);
if (dbConfig.UseLiteDb)
- serviceCollection.AddSingleton(c => new LiteDatabase(dbConfig.LiteDbConnectionString));
+ serviceCollection.AddSingleton(_ => new LiteDatabase(dbConfig.LiteDbConnectionString));
}
- if (dataProviderSettings != null && dataProviderSettings.IsValid())
+ if (dataProviderSettings.IsValid())
{
if (dataProviderSettings.DbProvider != DbProvider.LiteDB)
{
var connectionString = dataProviderSettings.ConnectionString;
- var mongourl = new MongoUrl(connectionString);
- var databaseName = mongourl.DatabaseName;
+ var mongoUrl = new MongoUrl(connectionString);
+ var databaseName = mongoUrl.DatabaseName;
var clientSettings = MongoClientSettings.FromConnectionString(connectionString);
clientSettings.LinqProvider = MongoDB.Driver.Linq.LinqProvider.V3;
if (applicationInsights.Enabled)
clientSettings.ClusterConfigurator = builder => { builder.Subscribe(new ApplicationInsightsSubscriber(serviceCollection)); };
- serviceCollection.AddScoped(c => new MongoClient(clientSettings).GetDatabase(databaseName));
+ serviceCollection.AddScoped(_ => new MongoClient(clientSettings).GetDatabase(databaseName));
}
else
{
if (dbConfig.Singleton)
- serviceCollection.AddSingleton(c => new LiteDatabase(dataProviderSettings.ConnectionString) { UtcDate = true });
+ serviceCollection.AddSingleton(_ => new LiteDatabase(dataProviderSettings.ConnectionString) { UtcDate = true });
else
- serviceCollection.AddScoped(c => new LiteDatabase(dataProviderSettings.ConnectionString) { UtcDate = true });
+ serviceCollection.AddScoped(_ => new LiteDatabase(dataProviderSettings.ConnectionString) { UtcDate = true });
}
}
@@ -73,7 +73,7 @@ namespace Grand.Infrastructure.Startup
{
//database context
serviceCollection.AddScoped<IDatabaseContext, MongoDBContext>();
- //store files context - gridfs
+ //store files context - grid fs
serviceCollection.AddScoped<IStoreFilesContext, MongoStoreFilesContext>();
//Mongo Repository
serviceCollection.AddScoped(typeof(IRepository<>), typeof(MongoRepository<>));
@@ -82,7 +82,7 @@ namespace Grand.Infrastructure.Startup
{
//database context
serviceCollection.AddScoped<IDatabaseContext, LiteDBContext>();
- //store files context - gridfs
+ //store files context - grid fs
serviceCollection.AddScoped<IStoreFilesContext, LiteDBStoreFilesContext>();
//Mongo Repository
serviceCollection.AddScoped(typeof(IRepository<>), typeof(LiteDBRepository<>));
diff --git a/src/Core/Grand.Infrastructure/StartupBase.cs b/src/Core/Grand.Infrastructure/StartupBase.cs
index 4c562c546..4d81ed813 100644
--- a/src/Core/Grand.Infrastructure/StartupBase.cs
+++ b/src/Core/Grand.Infrastructure/StartupBase.cs
@@ -6,7 +6,7 @@ using Grand.Infrastructure.Mapper;
using Grand.Infrastructure.Plugins;
using Grand.Infrastructure.Roslyn;
using Grand.Infrastructure.TypeConverters;
-using Grand.Infrastructure.TypeSearchers;
+using Grand.Infrastructure.TypeSearch;
using Grand.Infrastructure.Validators;
using Grand.SharedKernel;
using Grand.SharedKernel.Extensions;
@@ -36,9 +36,9 @@ namespace Grand.Infrastructure
var advancedConfig = services.StartupConfig<AdvancedConfig>(configuration.GetSection("Advanced"));
if (!string.IsNullOrEmpty(advancedConfig.DbConnectionString))
{
- DataSettingsManager.LoadDataSettings(new DataSettings() {
+ DataSettingsManager.LoadDataSettings(new DataSettings {
ConnectionString = advancedConfig.DbConnectionString,
- DbProvider = (DbProvider)advancedConfig.DbProvider,
+ DbProvider = (DbProvider)advancedConfig.DbProvider
});
}
}
@@ -54,9 +54,9 @@ namespace Grand.Infrastructure
//create and sort instances of mapper configurations
var instances = mapperConfigurations
- .Where(mapperConfiguration => PluginExtensions.OnlyInstalledPlugins(mapperConfiguration))
+ .Where(PluginExtensions.OnlyInstalledPlugins)
.Select(mapperConfiguration => (IAutoMapperProfile)Activator.CreateInstance(mapperConfiguration))
- .OrderBy(mapperConfiguration => mapperConfiguration.Order);
+ .OrderBy(mapperConfiguration => mapperConfiguration!.Order);
//create AutoMapper configuration
var config = new MapperConfiguration(cfg =>
@@ -83,7 +83,7 @@ namespace Grand.Infrastructure
//create and sort instances of typeConverter
var instances = converters
.Select(converter => (ITypeConverter)Activator.CreateInstance(converter))
- .OrderBy(converter => converter.Order);
+ .OrderBy(converter => converter!.Order);
foreach (var item in instances)
item.Register();
@@ -123,7 +123,7 @@ namespace Grand.Infrastructure
//Load plugins
PluginManager.Load(mvcCoreBuilder, configuration);
- //Load CTX sctipts
+ //Load CTX scripts
RoslynCompiler.Load(mvcCoreBuilder.PartManager, configuration);
}
@@ -131,17 +131,20 @@ namespace Grand.Infrastructure
/// Adds services for mediatR
/// </summary>
/// <param name="services">Collection of service descriptors</param>
- private static void AddMediator(this IServiceCollection services, AppTypeSearcher typeSearcher)
+ /// <param name="typeSearcher"></param>
+ private static void AddMediator(this IServiceCollection services, ITypeSearcher typeSearcher)
{
var assemblies = typeSearcher.GetAssemblies().ToArray();
services.AddMediatR(assemblies);
}
/// <summary>
- /// Add Mass Transit rabitMq message broker
+ /// Add Mass Transit rabbitmq message broker
/// </summary>
/// <param name="services"></param>
- private static void AddMassTransitRabbitMq(IServiceCollection services, IConfiguration configuration, AppTypeSearcher typeSearcher)
+ /// <param name="configuration"></param>
+ /// <param name="typeSearcher"></param>
+ private static void AddMassTransitRabbitMq(IServiceCollection services, IConfiguration configuration, ITypeSearcher typeSearcher)
{
var config = new RabbitConfig();
configuration.GetSection("Rabbit").Bind(config);
@@ -149,9 +152,8 @@ namespace Grand.Infrastructure
if (!config.RabbitEnabled) return;
services.AddMassTransit(x =>
{
- x.AddConsumers(q => !q.Equals(typeof(CacheMessageEventConsumer)), typeSearcher.GetAssemblies().ToArray());
+ x.AddConsumers(q => q != typeof(CacheMessageEventConsumer), typeSearcher.GetAssemblies().ToArray());
- // reddits have more priority
if (config.RabbitCachePubSubEnabled)
{
x.AddConsumer<CacheMessageEventConsumer>().Endpoint(t => t.Name = config.RabbitCacheReceiveEndpoint);
@@ -239,16 +241,16 @@ namespace Grand.Infrastructure
RegisterExtensions(mvcBuilder, configuration);
//find startup configurations provided by other assemblies
- var typeSearcher = new AppTypeSearcher();
+ var typeSearcher = new TypeSearcher();
services.AddSingleton<ITypeSearcher>(typeSearcher);
var startupConfigurations = typeSearcher.ClassesOfType<IStartupApplication>();
//Register startup
var instancesBefore = startupConfigurations
- .Where(startup => PluginExtensions.OnlyInstalledPlugins(startup))
+ .Where(PluginExtensions.OnlyInstalledPlugins)
.Select(startup => (IStartupApplication)Activator.CreateInstance(startup))
- .Where(startup => startup.BeforeConfigure)
+ .Where(startup => startup!.BeforeConfigure)
.OrderBy(startup => startup.Priority);
//configure services
@@ -269,16 +271,16 @@ namespace Grand.Infrastructure
//Register startup
var instancesAfter = startupConfigurations
- .Where(startup => PluginExtensions.OnlyInstalledPlugins(startup))
+ .Where(PluginExtensions.OnlyInstalledPlugins)
.Select(startup => (IStartupApplication)Activator.CreateInstance(startup))
- .Where(startup => !startup.BeforeConfigure)
+ .Where(startup => !startup!.BeforeConfigure)
.OrderBy(startup => startup.Priority);
//configure services
foreach (var instance in instancesAfter)
instance.ConfigureServices(services, configuration);
- //Execute startupbase interface
+ //Execute startup interface
ExecuteStartupBase(typeSearcher);
}
@@ -290,28 +292,28 @@ namespace Grand.Infrastructure
public static void ConfigureRequestPipeline(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
{
//find startup configurations provided by other assemblies
- var typeSearcher = new AppTypeSearcher();
+ var typeSearcher = new TypeSearcher();
var startupConfigurations = typeSearcher.ClassesOfType<IStartupApplication>();
//create and sort instances of startup configurations
var instances = startupConfigurations
- .Where(startup => PluginExtensions.OnlyInstalledPlugins(startup))
+ .Where(PluginExtensions.OnlyInstalledPlugins)
.Select(startup => (IStartupApplication)Activator.CreateInstance(startup))
- .OrderBy(startup => startup.Priority);
+ .OrderBy(startup => startup!.Priority);
//configure request pipeline
foreach (var instance in instances)
instance.Configure(application, webHostEnvironment);
}
- private static void ExecuteStartupBase(AppTypeSearcher typeSearcher)
+ private static void ExecuteStartupBase(ITypeSearcher typeSearcher)
{
var startupBaseConfigurations = typeSearcher.ClassesOfType<IStartupBase>();
//create and sort instances of startup configurations
var instances = startupBaseConfigurations
.Select(startup => (IStartupBase)Activator.CreateInstance(startup))
- .OrderBy(startup => startup.Priority);
+ .OrderBy(startup => startup!.Priority);
//execute
foreach (var instance in instances)
diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/CustomAttributeListTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/CustomAttributeListTypeConverter.cs
index 3e5c46ad9..53078324c 100644
--- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/CustomAttributeListTypeConverter.cs
+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/CustomAttributeListTypeConverter.cs
@@ -9,46 +9,31 @@ namespace Grand.Infrastructure.TypeConverters.Converter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
- if (sourceType == typeof(string))
- {
- return true;
- }
-
- return base.CanConvertFrom(context, sourceType);
+ return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
- if (value is string)
+ if (value is not string valueStr) return base.ConvertFrom(context, culture, value);
+ List<CustomAttribute> customAttributes = null;
+ if (string.IsNullOrEmpty(valueStr)) return null;
+ try
{
- List<CustomAttribute> customAttributes = null;
- var valueStr = value as string;
- if (!string.IsNullOrEmpty(valueStr))
- {
- try
- {
- customAttributes = JsonSerializer.Deserialize<List<CustomAttribute>>(valueStr);
- }
- catch
- {
- }
- }
- return customAttributes;
+ customAttributes = JsonSerializer.Deserialize<List<CustomAttribute>>(valueStr);
}
- return base.ConvertFrom(context, culture, value);
+ catch
+ {
+ // ignored
+ }
+
+ return customAttributes;
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
- var customAttributes = value as List<CustomAttribute>;
- if (customAttributes != null)
- {
- return JsonSerializer.Serialize(customAttributes);
- }
-
- return "";
+ return value is List<CustomAttribute> customAttributes ? JsonSerializer.Serialize(customAttributes) : "";
}
return base.ConvertTo(context, culture, value, destinationType);
diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericDictionaryTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericDictionaryTypeConverter.cs
index cd26eeaec..eeaaea8a0 100644
--- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericDictionaryTypeConverter.cs
+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericDictionaryTypeConverter.cs
@@ -10,19 +10,19 @@ namespace Grand.Infrastructure.TypeConverters.Converter
/// <typeparam name="V">Value type (simple)</typeparam>
public class GenericDictionaryTypeConverter<K, V> : TypeConverter
{
- protected readonly TypeConverter typeConverterKey;
- protected readonly TypeConverter typeConverterValue;
+ private readonly TypeConverter _typeConverterKey;
+ private readonly TypeConverter _typeConverterValue;
/// <summary>
/// Ctor
/// </summary>
public GenericDictionaryTypeConverter()
{
- typeConverterKey = TypeDescriptor.GetConverter(typeof(K));
- if (typeConverterKey == null)
+ _typeConverterKey = TypeDescriptor.GetConverter(typeof(K));
+ if (_typeConverterKey == null)
throw new InvalidOperationException("No type converter exists for type " + typeof(K).FullName);
- typeConverterValue = TypeDescriptor.GetConverter(typeof(V));
- if (typeConverterValue == null)
+ _typeConverterValue = TypeDescriptor.GetConverter(typeof(V));
+ if (_typeConverterValue == null)
throw new InvalidOperationException("No type converter exists for type " + typeof(V).FullName);
}
@@ -36,10 +36,7 @@ namespace Grand.Infrastructure.TypeConverters.Converter
/// <returns>Result</returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
- if (sourceType == typeof(string))
- return true;
-
- return base.CanConvertFrom(context, sourceType);
+ return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
/// <summary>
@@ -51,32 +48,23 @@ namespace Grand.Infrastructure.TypeConverters.Converter
/// <returns>Result</returns>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
- if (value is string input)
- {
- string[] items = string.IsNullOrEmpty(input) ? new string[0] : input.Split(';').Select(x => x.Trim()).ToArray();
-
- var result = new Dictionary<K, V>();
- foreach (var s in items)
- {
- string[] keyValueStr = string.IsNullOrEmpty(s) ? new string[0] : s.Split(',').Select(x => x.Trim()).ToArray();
- if (keyValueStr.Length == 2)
- {
- object dictionaryKey = typeConverterKey.ConvertFromInvariantString(keyValueStr[0]);
- object dictionaryValue = typeConverterKey.ConvertFromInvariantString(keyValueStr[1]);
- if (dictionaryKey != null && dictionaryValue != null)
- {
- if (!result.ContainsKey((K)dictionaryKey))
- {
- var itemvalue = Convert.ChangeType(dictionaryValue, typeof(V));
- result.Add((K)dictionaryKey, (V)itemvalue);
- }
- }
- }
- }
+ if (value is not string input) return base.ConvertFrom(context, culture, value);
+ var items = string.IsNullOrEmpty(input) ? Array.Empty<string>() : input.Split(';').Select(x => x.Trim()).ToArray();
- return result;
+ var result = new Dictionary<K, V>();
+ foreach (var s in items)
+ {
+ var keyValueStr = string.IsNullOrEmpty(s) ? Array.Empty<string>() : s.Split(',').Select(x => x.Trim()).ToArray();
+ if (keyValueStr.Length != 2) continue;
+ var dictionaryKey = _typeConverterKey.ConvertFromInvariantString(keyValueStr[0]);
+ var dictionaryValue = _typeConverterKey.ConvertFromInvariantString(keyValueStr[1]);
+ if (dictionaryKey == null || dictionaryValue == null) continue;
+ if (result.ContainsKey((K)dictionaryKey)) continue;
+ var itemValue = Convert.ChangeType(dictionaryValue, typeof(V));
+ result.Add((K)dictionaryKey, (V)itemValue);
}
- return base.ConvertFrom(context, culture, value);
+
+ return result;
}
/// <summary>
@@ -89,27 +77,23 @@ namespace Grand.Infrastructure.TypeConverters.Converter
/// <returns>Result</returns>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
- if (destinationType == typeof(string))
+ if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);
+ var result = string.Empty;
+ if (value == null) return result;
+ //we don't use string.Join() because it doesn't support invariant culture
+ var counter = 0;
+ var dictionary = (IDictionary<K, V>)value;
+ foreach (var keyValue in dictionary)
{
- string result = string.Empty;
- if (value != null)
- {
- //we don't use string.Join() because it doesn't support invariant culture
- int counter = 0;
- var dictionary = (IDictionary<K, V>)value;
- foreach (var keyValue in dictionary)
- {
- result += string.Format("{0},{1}", Convert.ToString(keyValue.Key, CultureInfo.InvariantCulture), Convert.ToString(keyValue.Value, CultureInfo.InvariantCulture));
- //don't add ; after the last element
- if (counter != dictionary.Count - 1)
- result += ";";
- counter++;
- }
- }
- return result;
+ result +=
+ $"{Convert.ToString(keyValue.Key, CultureInfo.InvariantCulture)},{Convert.ToString(keyValue.Value, CultureInfo.InvariantCulture)}";
+ //don't add ; after the last element
+ if (counter != dictionary.Count - 1)
+ result += ";";
+ counter++;
}
+ return result;
- return base.ConvertTo(context, culture, value, destinationType);
}
}
}
\ No newline at end of file
diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericListTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericListTypeConverter.cs
index 35314d5c6..791eed6d8 100644
--- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericListTypeConverter.cs
+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericListTypeConverter.cs
@@ -12,15 +12,15 @@ namespace Grand.Infrastructure.TypeConverters.Converter
/// <summary>
/// Type converter
/// </summary>
- protected readonly TypeConverter typeConverter;
+ private readonly TypeConverter _typeConverter;
/// <summary>
/// Ctor
/// </summary>
public GenericListTypeConverter()
{
- typeConverter = TypeDescriptor.GetConverter(typeof(T));
- if (typeConverter == null)
+ _typeConverter = TypeDescriptor.GetConverter(typeof(T));
+ if (_typeConverter == null)
throw new InvalidOperationException("No type converter exists for type " + typeof(T).FullName);
}
@@ -31,7 +31,7 @@ namespace Grand.Infrastructure.TypeConverters.Converter
/// <returns>Array</returns>
protected virtual string[] GetStringArray(string input)
{
- return string.IsNullOrEmpty(input) ? new string[0] : input.Split(',').Select(x => x.Trim()).ToArray();
+ return string.IsNullOrEmpty(input) ? Array.Empty<string>() : input.Split(',').Select(x => x.Trim()).ToArray();
}
/// <summary>
@@ -44,13 +44,10 @@ namespace Grand.Infrastructure.TypeConverters.Converter
/// <returns>Result</returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
- if (sourceType == typeof(string))
- {
- var items = GetStringArray(sourceType.ToString());
- return items.Any();
- }
+ if (sourceType != typeof(string)) return base.CanConvertFrom(context, sourceType);
+ var items = GetStringArray(sourceType.ToString());
+ return items.Any();
- return base.CanConvertFrom(context, sourceType);
}
/// <summary>
@@ -62,22 +59,19 @@ namespace Grand.Infrastructure.TypeConverters.Converter
/// <returns>Result</returns>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
- if (value is string)
+ if (value is not string strValue) return base.ConvertFrom(context, culture, value);
+ var items = GetStringArray(strValue);
+ var result = new List<T>();
+ Array.ForEach(items, s =>
{
- var items = GetStringArray((string)value);
- var result = new List<T>();
- Array.ForEach(items, s =>
+ var item = _typeConverter.ConvertFromInvariantString(s);
+ if (item != null)
{
- var item = typeConverter.ConvertFromInvariantString(s);
- if (item != null)
- {
- result.Add((T)item);
- }
- });
+ result.Add((T)item);
+ }
+ });
- return result;
- }
- return base.ConvertFrom(context, culture, value);
+ return result;
}
/// <summary>
@@ -90,25 +84,20 @@ namespace Grand.Infrastructure.TypeConverters.Converter
/// <returns>Result</returns>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
- if (destinationType == typeof(string))
+ if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);
+ var result = string.Empty;
+ if (value == null) return result;
+ //we don't use string.Join() because it doesn't support invariant culture
+ for (var i = 0; i < ((IList<T>)value).Count; i++)
{
- var result = string.Empty;
- if (value != null)
- {
- //we don't use string.Join() because it doesn't support invariant culture
- for (var i = 0; i < ((IList<T>)value).Count; i++)
- {
- var str1 = Convert.ToString(((IList<T>)value)[i], CultureInfo.InvariantCulture);
- result += str1;
- //don't add comma after the last element
- if (i != ((IList<T>)value).Count - 1)
- result += ",";
- }
- }
- return result;
+ var str1 = Convert.ToString(((IList<T>)value)[i], CultureInfo.InvariantCulture);
+ result += str1;
+ //don't add comma after the last element
+ if (i != ((IList<T>)value).Count - 1)
+ result += ",";
}
+ return result;
- return base.ConvertTo(context, culture, value, destinationType);
}
}
}
diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.cs
index c0186eccf..1e2cfe604 100644
--- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.cs
+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.cs
@@ -9,49 +9,35 @@ namespace Grand.Infrastructure.TypeConverters.Converter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
- if (sourceType == typeof(string))
- {
- return true;
- }
-
- return base.CanConvertFrom(context, sourceType);
+ return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
- if (value is string)
+ if (value is not string valueStr) return base.ConvertFrom(context, culture, value);
+ RefreshToken refreshToken = null;
+ if (string.IsNullOrEmpty(valueStr)) return null;
+ try
{
- RefreshToken refreshToken = null;
- var valueStr = value as string;
- if (!string.IsNullOrEmpty(valueStr))
- {
- try
- {
- refreshToken = JsonSerializer.Deserialize<RefreshToken>(valueStr);
- }
- catch
- {
- //deserialize error
- }
- }
- return refreshToken;
+ refreshToken = JsonSerializer.Deserialize<RefreshToken>(valueStr);
}
- return base.ConvertFrom(context, culture, value);
+ catch
+ {
+ //deserialize error
+ }
+ return refreshToken;
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
- if (destinationType == typeof(string))
+ if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);
+ if (value is RefreshToken refreshToken)
{
- if (value is RefreshToken refreshToken)
- {
- return JsonSerializer.Serialize(refreshToken);
- }
-
- return "";
+ return JsonSerializer.Serialize(refreshToken);
}
- return base.ConvertTo(context, culture, value, destinationType);
+ return "";
+
}
}
}
diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionListTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionListTypeConverter.cs
index df515c0c1..df8a0f03e 100644
--- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionListTypeConverter.cs
+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionListTypeConverter.cs
@@ -9,47 +9,30 @@ namespace Grand.Infrastructure.TypeConverters.Converter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
- if (sourceType == typeof(string))
- {
- return true;
- }
-
- return base.CanConvertFrom(context, sourceType);
+ return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
- if (value is string)
+ if (value is not string valueStr) return base.ConvertFrom(context, culture, value);
+ List<ShippingOption> shippingOptions = null;
+ if (string.IsNullOrEmpty(valueStr)) return (List<ShippingOption>)null;
+ try
{
- List<ShippingOption> shippingOptions = null;
- var valueStr = value as string;
- if (!string.IsNullOrEmpty(valueStr))
- {
- try
- {
- shippingOptions = JsonSerializer.Deserialize<List<ShippingOption>>(valueStr);
- }
- catch
- {
- //xml error
- }
- }
- return shippingOptions;
+ shippingOptions = JsonSerializer.Deserialize<List<ShippingOption>>(valueStr);
}
- return base.ConvertFrom(context, culture, value);
+ catch
+ {
+ //xml error
+ }
+ return shippingOptions;
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
- var shippingOptions = value as List<ShippingOption>;
- if (shippingOptions != null)
- {
- return JsonSerializer.Serialize(shippingOptions);
- }
-
- return "";
+ return value is List<ShippingOption> shippingOptions ? JsonSerializer.Serialize(shippingOptions) : "";
}
return base.ConvertTo(context, culture, value, destinationType);
diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionTypeConverter.cs
index 163511f99..e662a16fa 100644
--- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionTypeConverter.cs
+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionTypeConverter.cs
@@ -9,50 +9,35 @@ namespace Grand.Infrastructure.TypeConverters.Converter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
- if (sourceType == typeof(string))
- {
- return true;
- }
-
- return base.CanConvertFrom(context, sourceType);
+ return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
- if (value is string)
+ if (value is not string valueStr) return base.ConvertFrom(context, culture, value);
+ ShippingOption shippingOption = null;
+ if (string.IsNullOrEmpty(valueStr)) return null;
+ try
{
- ShippingOption shippingOption = null;
- var valueStr = value as string;
- if (!string.IsNullOrEmpty(valueStr))
- {
- try
- {
- shippingOption = JsonSerializer.Deserialize<ShippingOption>(valueStr);
- }
- catch
- {
- //deserialize error
- }
- }
- return shippingOption;
+ shippingOption = JsonSerializer.Deserialize<ShippingOption>(valueStr);
}
- return base.ConvertFrom(context, culture, value);
+ catch
+ {
+ //deserialize error
+ }
+ return shippingOption;
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
- if (destinationType == typeof(string))
+ if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);
+ if (value is ShippingOption shippingOption)
{
- var shippingOption = value as ShippingOption;
- if (shippingOption != null)
- {
- return JsonSerializer.Serialize(shippingOption);
- }
-
- return "";
+ return JsonSerializer.Serialize(shippingOption);
}
- return base.ConvertTo(context, culture, value, destinationType);
+ return "";
+
}
}
}
diff --git a/src/Core/Grand.Infrastructure/TypeSearcher/ITypeSearcher.cs b/src/Core/Grand.Infrastructure/TypeSearch/ITypeSearcher.cs
similarity index 92%
rename from src/Core/Grand.Infrastructure/TypeSearcher/ITypeSearcher.cs
rename to src/Core/Grand.Infrastructure/TypeSearch/ITypeSearcher.cs
index dfb3ed027..5da89d861 100644
--- a/src/Core/Grand.Infrastructure/TypeSearcher/ITypeSearcher.cs
+++ b/src/Core/Grand.Infrastructure/TypeSearch/ITypeSearcher.cs
@@ -1,6 +1,6 @@
using System.Reflection;
-namespace Grand.Infrastructure.TypeSearchers
+namespace Grand.Infrastructure.TypeSearch
{
/// <summary>
/// Classes implementing this interface provide information about types
diff --git a/src/Core/Grand.Infrastructure/TypeSearcher/TypeSearcher.cs b/src/Core/Grand.Infrastructure/TypeSearch/TypeSearcher.cs
similarity index 54%
rename from src/Core/Grand.Infrastructure/TypeSearcher/TypeSearcher.cs
rename to src/Core/Grand.Infrastructure/TypeSearch/TypeSearcher.cs
index 19ca90847..9b671985d 100644
--- a/src/Core/Grand.Infrastructure/TypeSearcher/TypeSearcher.cs
+++ b/src/Core/Grand.Infrastructure/TypeSearch/TypeSearcher.cs
@@ -1,7 +1,7 @@
using System.Diagnostics;
using System.Reflection;
-namespace Grand.Infrastructure.TypeSearchers
+namespace Grand.Infrastructure.TypeSearch
{
/// <summary>
/// A class that finds types needed by looping assemblies in the
@@ -9,7 +9,6 @@ namespace Grand.Infrastructure.TypeSearchers
/// </summary>
public class TypeSearcher : ITypeSearcher
{
-
#region Methods
public IEnumerable<Type> ClassesOfType<T>(bool onlyConcreteClasses = true)
@@ -22,21 +21,19 @@ namespace Grand.Infrastructure.TypeSearchers
return ClassesOfType(assignTypeFrom, GetAssemblies(), onlyConcreteClasses);
}
- public IEnumerable<Type> ClassesOfType(Type assignTypeFrom, IEnumerable<Assembly> assemblies, bool onlyConcreteClasses = true)
+ public IEnumerable<Type> ClassesOfType(Type assignTypeFrom, IEnumerable<Assembly> assemblies,
+ bool onlyConcreteClasses = true)
{
var result = new List<Type>();
try
{
foreach (var a in assemblies)
{
- Type[] types = null;
- types = a.GetTypes();
- if (types == null)
- continue;
-
+ Type[] types = a.GetTypes();
foreach (var t in types)
{
- if (!assignTypeFrom.IsAssignableFrom(t) && (!assignTypeFrom.IsGenericTypeDefinition || !DoesTypeImplementOpenGeneric(t, assignTypeFrom)))
+ if (!assignTypeFrom.IsAssignableFrom(t) && (!assignTypeFrom.IsGenericTypeDefinition ||
+ !DoesTypeImplementOpenGeneric(t, assignTypeFrom)))
continue;
if (t.IsInterface)
@@ -58,39 +55,32 @@ namespace Grand.Infrastructure.TypeSearchers
}
catch (ReflectionTypeLoadException ex)
{
- var msg = string.Empty;
- foreach (var e in ex.LoaderExceptions)
- msg += e.Message + Environment.NewLine;
+ var msg = ex.LoaderExceptions.Aggregate(string.Empty,
+ (current, e) => current + e!.Message + Environment.NewLine);
var fail = new Exception(msg, ex);
Debug.WriteLine(fail.Message, fail);
throw fail;
}
+
return result;
}
-
/// <summary>
/// Does type implement generic?
/// </summary>
/// <param name="type"></param>
/// <param name="openGeneric"></param>
/// <returns></returns>
- protected virtual bool DoesTypeImplementOpenGeneric(Type type, Type openGeneric)
+ private static bool DoesTypeImplementOpenGeneric(Type type, Type openGeneric)
{
try
{
var genericTypeDefinition = openGeneric.GetGenericTypeDefinition();
- foreach (var implementedInterface in type.FindInterfaces((objType, objCriteria) => true, null))
- {
- if (!implementedInterface.IsGenericType)
- continue;
-
- var isMatch = genericTypeDefinition.IsAssignableFrom(implementedInterface.GetGenericTypeDefinition());
- return isMatch;
- }
-
- return false;
+ return (from implementedInterface in type.FindInterfaces((_, _) => true, null)
+ where implementedInterface.IsGenericType
+ select genericTypeDefinition.IsAssignableFrom(implementedInterface.GetGenericTypeDefinition()))
+ .FirstOrDefault();
}
catch
{
@@ -109,7 +99,7 @@ namespace Grand.Infrastructure.TypeSearchers
#region Utilities
- private IList<Assembly> AssembliesInAppDomain()
+ private static IList<Assembly> AssembliesInAppDomain()
{
var addedAssemblyNames = new List<string>();
var assemblies = new List<Assembly>();
@@ -118,48 +108,26 @@ namespace Grand.Infrastructure.TypeSearchers
{
var product = assembly.GetCustomAttribute<AssemblyProductAttribute>();
var referencedAssemblies = assembly.GetReferencedAssemblies().ToList();
- if (referencedAssemblies.Where(x => x.FullName == currentAssem.FullName).Any()
- || product?.Product == "grandnode")
- {
- if (!addedAssemblyNames.Contains(assembly.FullName))
- {
- assemblies.Add(assembly);
- addedAssemblyNames.Add(assembly.FullName);
- }
- }
+ if (referencedAssemblies.All(x => x.FullName != currentAssem.FullName) &&
+ product?.Product != "grandnode") continue;
+ if (addedAssemblyNames.Contains(assembly.FullName)) continue;
+ assemblies.Add(assembly);
+ addedAssemblyNames.Add(assembly.FullName);
}
- //add scripts
- if (Roslyn.RoslynCompiler.ReferencedScripts != null)
- foreach (var scripts in Roslyn.RoslynCompiler.ReferencedScripts)
- {
- if (!string.IsNullOrEmpty(scripts.ReferencedAssembly.FullName))
- {
- if (!addedAssemblyNames.Contains(scripts.ReferencedAssembly.FullName))
- {
- assemblies.Add(scripts.ReferencedAssembly);
- addedAssemblyNames.Add(scripts.ReferencedAssembly.FullName);
- }
- }
- }
-
- return assemblies;
- }
- /// <summary>
- /// Makes sure matching assemblies in the supplied folder are loaded in the app domain.
- /// </summary>
- /// <param name="directoryPath">
- /// The physical path to a directory containing dlls to load in the app domain.
- /// </param>
- protected virtual void LoadMatchingAssemblies()
- {
- var loadedAssemblyNames = new List<string>();
- foreach (Assembly a in GetAssemblies())
+ //add scripts
+ if (Roslyn.RoslynCompiler.ReferencedScripts == null) return assemblies;
+ foreach (var scripts in Roslyn.RoslynCompiler.ReferencedScripts)
{
- loadedAssemblyNames.Add(a.FullName);
+ if (string.IsNullOrEmpty(scripts.ReferencedAssembly.FullName)) continue;
+ if (addedAssemblyNames.Contains(scripts.ReferencedAssembly.FullName)) continue;
+ assemblies.Add(scripts.ReferencedAssembly);
+ addedAssemblyNames.Add(scripts.ReferencedAssembly.FullName);
}
+
+ return assemblies;
}
#endregion
}
-}
+}
\ No newline at end of file
diff --git a/src/Core/Grand.Infrastructure/TypeSearcher/AppTypeSearcher.cs b/src/Core/Grand.Infrastructure/TypeSearcher/AppTypeSearcher.cs
deleted file mode 100644
index e9e8ac7b7..000000000
--- a/src/Core/Grand.Infrastructure/TypeSearcher/AppTypeSearcher.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-using System.Reflection;
-
-namespace Grand.Infrastructure.TypeSearchers
-{
- public class AppTypeSearcher : TypeSearcher
- {
- #region Fields
-
- private bool _ensureBinFolderAssembliesLoaded = true;
- private bool _binFolderAssembliesLoaded;
-
- #endregion
-
- #region Properties
-
- /// <summary>
- /// Gets or sets wether assemblies in the bin folder of the web application should be specificly checked for beeing loaded on application load. This is need in situations where plugins need to be loaded in the AppDomain after the application been reloaded.
- /// </summary>
- public bool EnsureBinFolderAssembliesLoaded
- {
- get { return _ensureBinFolderAssembliesLoaded; }
- set { _ensureBinFolderAssembliesLoaded = value; }
- }
-
- #endregion
-
- #region Methods
-
- /// <summary>
- /// Gets a physical disk path of \Bin directory
- /// </summary>
- /// <returns>The physical path. E.g. "c:\inetpub\wwwroot\bin"</returns>
- public virtual string GetBinDirectory()
- {
- return System.AppContext.BaseDirectory;
- }
-
- public override IList<Assembly> GetAssemblies()
- {
- if (EnsureBinFolderAssembliesLoaded && !_binFolderAssembliesLoaded)
- {
- _binFolderAssembliesLoaded = true;
- LoadMatchingAssemblies();
- }
- return base.GetAssemblies();
- }
-
- #endregion
- }
-}
diff --git a/src/Core/Grand.Infrastructure/Validators/BaseGrandValidator.cs b/src/Core/Grand.Infrastructure/Validators/BaseGrandValidator.cs
index 31eaaae13..53d241fb7 100644
--- a/src/Core/Grand.Infrastructure/Validators/BaseGrandValidator.cs
+++ b/src/Core/Grand.Infrastructure/Validators/BaseGrandValidator.cs
@@ -10,7 +10,7 @@ namespace Grand.Infrastructure.Validators
PostInitialize(validators);
}
- protected virtual void PostInitialize(IEnumerable<IValidatorConsumer<T>> validators)
+ private void PostInitialize(IEnumerable<IValidatorConsumer<T>> validators)
{
foreach (var item in validators)
{
diff --git a/src/Core/Grand.Infrastructure/Validators/FluentValidationFilter.cs b/src/Core/Grand.Infrastructure/Validators/FluentValidationFilter.cs
index 9a45f8bbf..4934772ba 100644
--- a/src/Core/Grand.Infrastructure/Validators/FluentValidationFilter.cs
+++ b/src/Core/Grand.Infrastructure/Validators/FluentValidationFilter.cs
@@ -10,7 +10,7 @@ namespace Grand.Infrastructure.Validators
#region Fields
private readonly IServiceProvider _serviceProvider;
-
+
#endregion
#region Ctor
@@ -28,6 +28,7 @@ namespace Grand.Infrastructure.Validators
/// Called before the action executes, after model binding is complete
/// </summary>
/// <param name="context">A context for action filters</param>
+ /// <param name="next"></param>
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
//only in POST requests
@@ -36,22 +37,22 @@ namespace Grand.Infrastructure.Validators
await next();
return;
}
+
if (context.ActionArguments.TryGetValue("model", out var model))
{
- Type genericType = typeof(IValidator<>).MakeGenericType(model.GetType());
- if (genericType is not null)
+ Type genericType = typeof(IValidator<>).MakeGenericType(model!.GetType());
+ var validator = (IValidator)_serviceProvider.GetService(genericType);
+ if (validator is not null)
{
- var validator = (IValidator)_serviceProvider.GetService(genericType);
- if (validator is not null)
- {
- var contextvalidator = new ValidationContext<object>(model);
- var result = await validator.ValidateAsync(contextvalidator);
- if (!result.IsValid) result.AddToModelState(context.ModelState, "");
- }
+ var contextValidator = new ValidationContext<object>(model);
+ var result = await validator.ValidateAsync(contextValidator);
+ if (!result.IsValid) result.AddToModelState(context.ModelState, "");
}
}
+
await next();
}
+
#endregion
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/BrandImportDataObjectTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/BrandImportDataObjectTests.cs
index ab5825ac3..8c38d9021 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/BrandImportDataObjectTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/BrandImportDataObjectTests.cs
@@ -14,6 +14,7 @@ using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Mapper;
using Grand.Infrastructure.Tests.Caching;
+using Grand.Infrastructure.TypeSearch;
using Grand.Infrastructure.TypeSearchers;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CategoryImportDataObjectTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CategoryImportDataObjectTests.cs
index 2b2e85518..8a247af23 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CategoryImportDataObjectTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CategoryImportDataObjectTests.cs
@@ -15,7 +15,7 @@ using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Mapper;
using Grand.Infrastructure.Tests.Caching;
-using Grand.Infrastructure.TypeSearchers;
+using Grand.Infrastructure.TypeSearch;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CollectionImportDataObjectTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CollectionImportDataObjectTests.cs
index 0bab5063f..840874b4e 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CollectionImportDataObjectTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CollectionImportDataObjectTests.cs
@@ -15,7 +15,7 @@ using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Mapper;
using Grand.Infrastructure.Tests.Caching;
-using Grand.Infrastructure.TypeSearchers;
+using Grand.Infrastructure.TypeSearch;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/ProductImportDataObjectTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/ProductImportDataObjectTests.cs
index 37b116a72..dcbe8dfe7 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/ProductImportDataObjectTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/ProductImportDataObjectTests.cs
@@ -25,6 +25,7 @@ using Grand.Business.Core.Interfaces.Catalog.Directory;
using Grand.Business.Core.Interfaces.Catalog.Categories;
using Grand.Business.Core.Interfaces.Catalog.Brands;
using Grand.Business.Core.Interfaces.Catalog.Collections;
+using Grand.Infrastructure.TypeSearch;
namespace Grand.Business.Catalog.Services.ExportImport.Tests
{
diff --git a/src/Tests/Grand.Infrastructure.Tests/TypeSearcher/TypeSearcherTests.cs b/src/Tests/Grand.Infrastructure.Tests/TypeSearcher/TypeSearcherTests.cs
index b49a0720f..2be3652f0 100644
--- a/src/Tests/Grand.Infrastructure.Tests/TypeSearcher/TypeSearcherTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/TypeSearcher/TypeSearcherTests.cs
@@ -1,4 +1,5 @@
using Grand.Infrastructure.Caching;
+using Grand.Infrastructure.TypeSearch;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Grand.Infrastructure.TypeSearchers.Tests
diff --git a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs
index b18962587..fd974c7fb 100644
--- a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs
+++ b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs
@@ -6,7 +6,7 @@ using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Endpoints;
using Grand.Infrastructure.Plugins;
-using Grand.Infrastructure.TypeSearchers;
+using Grand.Infrastructure.TypeSearch;
using Grand.SharedKernel.Extensions;
using Grand.Web.Common.Middleware;
using Microsoft.AspNetCore.Authentication.JwtBearer;
diff --git a/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs
index 95e77b76f..b99db003e 100644
--- a/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs
+++ b/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs
@@ -11,7 +11,8 @@ using Grand.Domain.Data;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Plugins;
-using Grand.Infrastructure.TypeSearchers;
+using Grand.Infrastructure.TypeSearch;
+using Grand.Infrastructure.Validators;
using Grand.SharedKernel.Extensions;
using Grand.Web.Common.Themes;
using Microsoft.AspNetCore.Builder;
@@ -183,7 +184,7 @@ namespace Grand.Web.Common.Infrastructure
});
//register external authentication plugins now
- var typeSearcher = new AppTypeSearcher();
+ var typeSearcher = new TypeSearcher();
var externalAuthConfigurations = typeSearcher.ClassesOfType<IAuthenticationBuilder>();
var externalAuthInstances = externalAuthConfigurations
.Where(PluginExtensions.OnlyInstalledPlugins)
@@ -244,7 +245,7 @@ namespace Grand.Web.Common.Infrastructure
//Add fluentValidation
services.AddFluentValidationClientsideAdapters();
- var typeSearcher = new AppTypeSearcher();
+ var typeSearcher = new TypeSearcher();
var assemblies = typeSearcher.GetAssemblies();
services.AddValidatorsFromAssemblies(assemblies);
@@ -283,7 +284,7 @@ namespace Grand.Web.Common.Infrastructure
public static void AddSettings(this IServiceCollection services)
{
- var typeSearcher = new AppTypeSearcher();
+ var typeSearcher = new TypeSearcher();
var settings = typeSearcher.ClassesOfType<ISettings>();
var instances = settings.Select(x => (ISettings)Activator.CreateInstance(x));
foreach (var item in instances)
@@ -301,7 +302,7 @@ namespace Grand.Web.Common.Infrastructure
});
}
}
-
+
public static void AddGrandHealthChecks(this IServiceCollection services)
{
var connection = DataSettingsManager.LoadSettings();
diff --git a/src/Web/Grand.Web.Common/Startup/TaskHandler.cs b/src/Web/Grand.Web.Common/Startup/TaskHandler.cs
index 80d536995..864f55b79 100644
--- a/src/Web/Grand.Web.Common/Startup/TaskHandler.cs
+++ b/src/Web/Grand.Web.Common/Startup/TaskHandler.cs
@@ -2,7 +2,7 @@
using Grand.Domain.Data;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Plugins;
-using Grand.Infrastructure.TypeSearchers;
+using Grand.Infrastructure.TypeSearch;
using Grand.Web.Common.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
@@ -18,7 +18,7 @@ namespace Grand.Web.Common.Startup
if (!DataSettingsManager.DatabaseIsInstalled()) return;
var appConfig = services.BuildServiceProvider().GetRequiredService<AppConfig>();
if (appConfig.DisableHostedService) return;
- var typeSearcher = new AppTypeSearcher();
+ var typeSearcher = new TypeSearcher();
var scheduleTasks = typeSearcher.ClassesOfType<IScheduleTask>();
var scheduleTasksInstalled = scheduleTasks