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.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Add LiteDB database support - Embedded NoSQL database (#244)
Krzysztof Pajaka8c9155bf61f
diff --git a/GrandNode.sln b/GrandNode.slnindex a9c84fbee..6b57baf40 100644--- a/GrandNode.sln+++ b/GrandNode.sln@@ -112,6 +112,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{B7D07028src\Builds\Grand.Targets.props = src\Builds\Grand.Targets.propsEndProjectSectionEndProject+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Grand.Data.Tests", "src\Tests\Grand.Data.Tests\Grand.Data.Tests.csproj", "{ACCAAA38-FBF0-4C18-9227-4A7A3897C5AC}"+EndProjectGlobalGlobalSection(SolutionConfigurationPlatforms) = preSolutionDebug|Any CPU = Debug|Any CPU@@ -289,6 +291,10 @@ Global{F591E2F4-69F7-40B2-A623-9BF62B1F3CD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU{F591E2F4-69F7-40B2-A623-9BF62B1F3CD4}.Release|Any CPU.ActiveCfg = Release|Any CPU{F591E2F4-69F7-40B2-A623-9BF62B1F3CD4}.Release|Any CPU.Build.0 = Release|Any CPU+ {ACCAAA38-FBF0-4C18-9227-4A7A3897C5AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {ACCAAA38-FBF0-4C18-9227-4A7A3897C5AC}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {ACCAAA38-FBF0-4C18-9227-4A7A3897C5AC}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {ACCAAA38-FBF0-4C18-9227-4A7A3897C5AC}.Release|Any CPU.Build.0 = Release|Any CPUEndGlobalSectionGlobalSection(SolutionProperties) = preSolutionHideSolutionNode = FALSE@@ -336,6 +342,7 @@ Global{E0CDC8F3-2F79-40ED-AD7C-EF3F7B056BEA} = {6360202A-F931-4BBD-ADBD-C9A628EE59F8}{3CCCC424-B13F-479B-94A2-A0A6B05C0858} = {6360202A-F931-4BBD-ADBD-C9A628EE59F8}{B34CA673-578B-46D8-BEC0-2C32BF6997F9} = {6360202A-F931-4BBD-ADBD-C9A628EE59F8}+ {ACCAAA38-FBF0-4C18-9227-4A7A3897C5AC} = {6360202A-F931-4BBD-ADBD-C9A628EE59F8}EndGlobalSectionGlobalSection(ExtensibilityGlobals) = postSolutionSolutionGuid = {88B478F4-FD3B-4C24-9E84-4FAAF0254397}diff --git a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.csindex 2a0aeb0fb..633d7db60 100644--- a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs@@ -316,8 +316,10 @@ namespace Grand.Business.Authentication.Servicesif (parameters == null)throw new ArgumentNullException(nameof(parameters));- var associationRecord = await _externalAuthenticationRecordRepository.FirstOrDefaultAsync(record =>- record.ExternalIdentifier.Equals(parameters.Identifier) && record.ProviderSystemName.Equals(parameters.ProviderSystemName));+ var associationRecord = (from q in _externalAuthenticationRecordRepository.Table+ where q.ExternalIdentifier.ToLowerInvariant() == parameters.Identifier+ && q.ProviderSystemName.ToLowerInvariant() == parameters.ProviderSystemName.ToLowerInvariant()+ select q).FirstOrDefault();if (associationRecord == null)return null;diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/CategoryDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/CategoryDeletedEventHandler.csindex f4c404717..ffa14c0b9 100644--- a/src/Business/Grand.Business.Catalog/Events/Handlers/CategoryDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/CategoryDeletedEventHandler.cs@@ -32,7 +32,7 @@ namespace Grand.Business.Catalog.Events.Handlersawait _entityUrlRepository.DeleteManyAsync(x => x.EntityId == notification.Entity.Id && x.EntityName == "Category");//delete on the product- await _productRepository.PullFilter(string.Empty, x => x.ProductCategories, z => z.CategoryId, notification.Entity.Id, true);+ await _productRepository.PullFilter(string.Empty, x => x.ProductCategories, z => z.CategoryId, notification.Entity.Id);//clear cacheawait _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/CollectionDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/CollectionDeletedEventHandler.csindex d68d49213..50792ea96 100644--- a/src/Business/Grand.Business.Catalog/Events/Handlers/CollectionDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/CollectionDeletedEventHandler.cs@@ -30,7 +30,7 @@ namespace Grand.Business.Catalog.Events.Handlersawait _entityUrlRepository.DeleteManyAsync(x => x.EntityId == notification.Entity.Id && x.EntityName == "Collection");//delete on the product- await _productRepository.PullFilter(string.Empty, x => x.ProductCollections, z => z.CollectionId, notification.Entity.Id, true);+ await _productRepository.PullFilter(string.Empty, x => x.ProductCollections, z => z.CollectionId, notification.Entity.Id);//clear cacheawait _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/DiscountDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/DiscountDeletedEventHandler.csindex 42e081a2c..69860ddfc 100644--- a/src/Business/Grand.Business.Catalog/Events/Handlers/DiscountDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/DiscountDeletedEventHandler.cs@@ -51,7 +51,7 @@ namespace Grand.Business.Catalog.Events.Handlersif (discount.DiscountTypeId == DiscountType.AssignedToSkus){//delete on the product- await _productRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id, true);+ await _productRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);}@@ -59,28 +59,28 @@ namespace Grand.Business.Catalog.Events.Handlersif (discount.DiscountTypeId == DiscountType.AssignedToCategories){//delete on the category- await _categoryRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id, true);+ await _categoryRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);//clear cacheawait _cacheBase.RemoveByPrefix(CacheKey.CATEGORIES_PATTERN_KEY);}if (discount.DiscountTypeId == DiscountType.AssignedToBrands){//delete on the brand- await _brandRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id, true);+ await _brandRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);//clear cacheawait _cacheBase.RemoveByPrefix(CacheKey.BRANDS_PATTERN_KEY);}if (discount.DiscountTypeId == DiscountType.AssignedToCollections){//delete on the collection- await _collectionRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id, true);+ await _collectionRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);//clear cacheawait _cacheBase.RemoveByPrefix(CacheKey.COLLECTIONS_PATTERN_KEY);}if (discount.DiscountTypeId == DiscountType.AssignedToVendors){//delete on the vendor- await _vendorRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id, true);+ await _vendorRepository.Pull(string.Empty, x => x.AppliedDiscounts, discount.Id);//clear cacheawait _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);}diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.csindex 3be3be15e..cfecc473e 100644--- a/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.cs@@ -43,22 +43,22 @@ namespace Grand.Business.Catalog.Events.Handlerspublic async Task Handle(EntityDeleted<Product> notification, CancellationToken cancellationToken){//delete related product- await _productRepository.PullFilter(string.Empty, x => x.RelatedProducts, z => z.ProductId2, notification.Entity.Id, true);+ await _productRepository.PullFilter(string.Empty, x => x.RelatedProducts, z => z.ProductId2, notification.Entity.Id);//delete similar product- await _productRepository.PullFilter(string.Empty, x => x.SimilarProducts, z => z.ProductId2, notification.Entity.Id, true);+ await _productRepository.PullFilter(string.Empty, x => x.SimilarProducts, z => z.ProductId2, notification.Entity.Id);//delete cross sales product- await _productRepository.Pull(string.Empty, x => x.CrossSellProduct, notification.Entity.Id, true);+ await _productRepository.Pull(string.Empty, x => x.CrossSellProduct, notification.Entity.Id);//delete recomended product- await _productRepository.Pull(string.Empty, x => x.RecommendedProduct, notification.Entity.Id, true);+ await _productRepository.Pull(string.Empty, x => x.RecommendedProduct, notification.Entity.Id);//delete reviewawait _productReviewRepository.DeleteManyAsync(x=>x.ProductId == notification.Entity.Id);//delete from shopping cart- await _customerRepository.PullFilter(string.Empty, x => x.ShoppingCartItems, z => z.ProductId, notification.Entity.Id, true);+ await _customerRepository.PullFilter(string.Empty, x => x.ShoppingCartItems, z => z.ProductId, notification.Entity.Id);//delete customer group productawait _customerGroupProductRepository.DeleteManyAsync(x => x.ProductId == notification.Entity.Id);diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/WarehouseDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/WarehouseDeletedEventHandler.csindex 17f77231d..3ad780d73 100644--- a/src/Business/Grand.Business.Catalog/Events/Handlers/WarehouseDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/WarehouseDeletedEventHandler.cs@@ -17,7 +17,7 @@ namespace Grand.Business.Catalog.Events.Handlerspublic async Task Handle(EntityDeleted<Warehouse> notification, CancellationToken cancellationToken){- await _productRepository.PullFilter(string.Empty, x => x.ProductWarehouseInventory, z => z.WarehouseId, notification.Entity.Id, true);+ await _productRepository.PullFilter(string.Empty, x => x.ProductWarehouseInventory, z => z.WarehouseId, notification.Entity.Id);await _productRepository.UpdateManyAsync(x => x.WarehouseId == notification.Entity.Id,UpdateBuilder<Product>.Create().Set(x => x.WarehouseId, ""));diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.csindex 2b6dd417c..eb1a8f9ed 100644--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs@@ -149,7 +149,7 @@ namespace Grand.Business.Catalog.Queries.Handlers||p.Locales.Any(x => x.LocaleKey == "Name" && x.LocaleValue != null && x.LocaleValue.ToLower().Contains(request.Keywords.ToLower()))||- (request.SearchSku && p.Sku.ToLower().Contains(request.Keywords.ToLower()))+ (request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower())));else{@@ -162,7 +162,7 @@ namespace Grand.Business.Catalog.Queries.Handlers||(p.Locales.Any(x => x.LocaleValue != null && x.LocaleValue.ToLower().Contains(request.Keywords.ToLower())))||- (request.SearchSku && p.Sku.ToLower().Contains(request.Keywords.ToLower()))+ (request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower())));}diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.csindex 11ce94f85..f0bc87774 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs@@ -131,7 +131,7 @@ namespace Grand.Business.Catalog.Services.Productsthrow new ArgumentNullException(nameof(productAttribute));//delete from all product collections- await _productRepository.PullFilter(string.Empty, x => x.ProductAttributeMappings, z => z.ProductAttributeId, productAttribute.Id, true);+ await _productRepository.PullFilter(string.Empty, x => x.ProductAttributeMappings, z => z.ProductAttributeId, productAttribute.Id);//delete from productAttribute collectionawait _productAttributeRepository.DeleteAsync(productAttribute);diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.csindex d36352da8..b16a40513 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs@@ -162,7 +162,7 @@ namespace Grand.Business.Catalog.Services.Productsawait _productTagRepository.UpdateAsync(productTag);//update on products- await _productRepository.UpdateToSet(x => x.ProductTags, previouse.Name, productTag.Name, true);+ await _productRepository.UpdateToSet(x => x.ProductTags, previouse.Name, productTag.Name);//cacheawait _cacheBase.RemoveByPrefix(CacheKey.PRODUCTTAG_PATTERN_KEY);@@ -180,7 +180,7 @@ namespace Grand.Business.Catalog.Services.Productsthrow new ArgumentNullException(nameof(productTag));//update product- await _productRepository.Pull(string.Empty, x => x.ProductTags, productTag.Name, true);+ await _productRepository.Pull(string.Empty, x => x.ProductTags, productTag.Name);//delete tagawait _productTagRepository.DeleteAsync(productTag);diff --git a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.csindex 1dc736016..e1a361d49 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs@@ -135,7 +135,7 @@ namespace Grand.Business.Catalog.Services.Productsthrow new ArgumentNullException(nameof(specificationAttribute));//delete from all product collections- await _productRepository.PullFilter(string.Empty, x => x.ProductSpecificationAttributes, z => z.SpecificationAttributeId, specificationAttribute.Id, true);+ await _productRepository.PullFilter(string.Empty, x => x.ProductSpecificationAttributes, z => z.SpecificationAttributeId, specificationAttribute.Id);await _specificationAttributeRepository.DeleteAsync(specificationAttribute);@@ -181,7 +181,7 @@ namespace Grand.Business.Catalog.Services.Productsthrow new ArgumentNullException(nameof(specificationAttributeOption));//delete from all product collections- await _productRepository.PullFilter(string.Empty, x => x.ProductSpecificationAttributes, z => z.SpecificationAttributeOptionId, specificationAttributeOption.Id, true);+ await _productRepository.PullFilter(string.Empty, x => x.ProductSpecificationAttributes, z => z.SpecificationAttributeOptionId, specificationAttributeOption.Id);var specificationAttribute = await GetSpecificationAttributeByOptionId(specificationAttributeOption.Id);var sao = specificationAttribute.SpecificationAttributeOptions.Where(x => x.Id == specificationAttributeOption.Id).FirstOrDefault();diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetGiftVoucherQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetGiftVoucherQueryHandler.csindex 8ccc6a9c1..7581622a1 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetGiftVoucherQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetGiftVoucherQueryHandler.cs@@ -32,11 +32,10 @@ namespace Grand.Business.Checkout.Queries.Handlers.Ordersif (request.IsGiftVoucherActivated.HasValue)query = query.Where(gc => gc.IsGiftVoucherActivated == request.IsGiftVoucherActivated.Value);if (!string.IsNullOrEmpty(request.Code))- {- query = query.Where(gc => gc.Code == request.Code.ToLowerInvariant());- }+ query = query.Where(gc => gc.Code!=null && gc.Code == request.Code.ToLowerInvariant());if (!string.IsNullOrWhiteSpace(request.RecipientName))- query = query.Where(c => c.RecipientName.Contains(request.RecipientName));+ query = query.Where(c => c.RecipientName!=null && c.RecipientName.Contains(request.RecipientName));+query = query.OrderByDescending(gc => gc.CreatedOnUtc);return Task.FromResult(query);diff --git a/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs b/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.csindex af9af2042..d194eac1f 100644--- a/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs+++ b/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs@@ -37,7 +37,7 @@ namespace Grand.Business.Checkout.Services.GiftVouchers#region Methods-+/// <summary>/// Gets a gift voucher/// </summary>@@ -66,8 +66,7 @@ namespace Grand.Business.Checkout.Services.GiftVouchersstring recipientName = null,int pageIndex = 0, int pageSize = int.MaxValue){- var model = new GetGiftVoucherQuery()- {+ var model = new GetGiftVoucherQuery() {CreatedFromUtc = createdFromUtc,CreatedToUtc = createdToUtc,Code = giftVoucherCouponCode,@@ -147,13 +146,13 @@ namespace Grand.Business.Checkout.Services.GiftVouchers/// <returns>Gift voucher entries</returns>public virtual async Task<IList<GiftVoucher>> GetGiftVouchersByPurchasedWithOrderItemId(string purchasedWithOrderItemId){- if (String.IsNullOrEmpty(purchasedWithOrderItemId))+ if (string.IsNullOrEmpty(purchasedWithOrderItemId))return new List<GiftVoucher>();var query = from p in _giftVoucherRepository.Tableselect p;- query = query.Where(gc => gc.PurchasedWithOrderItem.Id == purchasedWithOrderItemId);+ query = query.Where(gc => gc.PurchasedWithOrderItem!=null && gc.PurchasedWithOrderItem.Id == purchasedWithOrderItemId);query = query.OrderBy(gc => gc.Id);return await Task.FromResult(query.ToList());diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.csindex e4506b7e2..cd2971c59 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs@@ -143,7 +143,7 @@ namespace Grand.Business.Checkout.Services.Ordersthrow new ArgumentNullException(nameof(orderTag));//update orders- await _orderRepository.Pull(string.Empty, x => x.OrderTags, orderTag.Id, true);+ await _orderRepository.Pull(string.Empty, x => x.OrderTags, orderTag.Id);//delete tagawait _orderTagRepository.DeleteAsync(orderTag);diff --git a/src/Business/Grand.Business.Common/Events/GroupDeletedEventHandler.cs b/src/Business/Grand.Business.Common/Events/GroupDeletedEventHandler.csindex 66753b057..a07232d10 100644--- a/src/Business/Grand.Business.Common/Events/GroupDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Common/Events/GroupDeletedEventHandler.cs@@ -17,7 +17,7 @@ namespace Grand.Business.Common.Eventspublic async Task Handle(EntityDeleted<CustomerGroup> notification, CancellationToken cancellationToken){//delete from customers- await _customerRepository.Pull(string.Empty, x => x.Groups, notification.Entity.Id, true);+ await _customerRepository.Pull(string.Empty, x => x.Groups, notification.Entity.Id);}}}diff --git a/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs b/src/Business/Grand.Business.Common/Services/Configuration/SettingService.csindex 3f4f43095..2073461e1 100644--- a/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs+++ b/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs@@ -220,8 +220,8 @@ namespace Grand.Business.Common.Services.Configuration{var setting = settings.FirstOrDefault(x => x.StoreId == storeId);- if (setting == null && !String.IsNullOrEmpty(storeId))- setting = settings.FirstOrDefault(x => x.StoreId == "");+ if (setting == null && !string.IsNullOrEmpty(storeId))+ setting = settings.FirstOrDefault(x => string.IsNullOrEmpty(x.StoreId));return JsonSerializer.Deserialize(setting.Metadata, type) as ISettings;}diff --git a/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs b/src/Business/Grand.Business.Common/Services/Localization/LanguageService.csindex e7630f0be..cfcec2375 100644--- a/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs+++ b/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs@@ -95,7 +95,14 @@ namespace Grand.Business.Common.Services.Localizationthrow new ArgumentNullException(nameof(languageCode));var key = string.Format(CacheKey.LANGUAGES_BY_CODE, languageCode);- return await _cacheBase.GetAsync(key, async () => await _languageRepository.FirstOrDefaultAsync(x=>x.UniqueSeoCode.ToLowerInvariant() == languageCode.ToLowerInvariant()));+ return await _cacheBase.GetAsync(key, async () =>+ {+ var query = from q in _languageRepository.Table+ where q.UniqueSeoCode.ToLowerInvariant() == languageCode.ToLowerInvariant()+ select q;+ return await Task.FromResult(query.FirstOrDefault());+ });+}/// <summary>diff --git a/src/Business/Grand.Business.Customers/Services/AffiliateService.cs b/src/Business/Grand.Business.Customers/Services/AffiliateService.csindex 9de125495..1986bb1b9 100644--- a/src/Business/Grand.Business.Customers/Services/AffiliateService.cs+++ b/src/Business/Grand.Business.Customers/Services/AffiliateService.cs@@ -60,7 +60,7 @@ namespace Grand.Business.Customers.Servicespublic virtual async Task<Affiliate> GetAffiliateByFriendlyUrlName(string friendlyUrlName){var query = from a in _affiliateRepository.Table- where a.FriendlyUrlName.Contains(friendlyUrlName.ToLowerInvariant())+ where a.FriendlyUrlName!=null && a.FriendlyUrlName.Contains(friendlyUrlName.ToLowerInvariant())select a;var affiliate = await Task.FromResult(query.FirstOrDefault());return affiliate;diff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.csindex 1b0afb516..ac2c87b08 100644--- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs@@ -67,7 +67,7 @@ namespace Grand.Business.Marketing.Services.Customersthrow new ArgumentNullException(nameof(customerTag));//update customer- await _customerRepository.Pull(string.Empty, x => x.CustomerTags, customerTag.Id, true);+ await _customerRepository.Pull(string.Empty, x => x.CustomerTags, customerTag.Id);//deleteawait _customerTagRepository.DeleteAsync(customerTag);diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs b/src/Business/Grand.Business.System/Services/Installation/InstallationService.csindex 891dbd7c2..3d055a8ba 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallationService.cs@@ -757,7 +757,7 @@ namespace Grand.Business.System.Services.Installation{try{- var dataSettings = DataSettingsManager.LoadSettings();+ var dataSettings = DataSettingsManager.LoadSettings(reloadSettings: true);var dbContext = _serviceProvider.GetRequiredService<IDatabaseContext>();dbContext.SetConnection(dataSettings.ConnectionString);diff --git a/src/Core/Grand.Domain/Data/DataSettingsManager.cs b/src/Core/Grand.Domain/Data/DataSettingsManager.csindex 849dd40cd..fe87abb97 100644--- a/src/Core/Grand.Domain/Data/DataSettingsManager.cs+++ b/src/Core/Grand.Domain/Data/DataSettingsManager.cs@@ -70,7 +70,7 @@ namespace Grand.Domain.Datausing FileStream fs = File.Create(filePath);}var data = JsonSerializer.Serialize(settings, new JsonSerializerOptions { WriteIndented = true });- await File.WriteAllTextAsync(filePath, data);+ await File.WriteAllTextAsync(filePath, data);}}}diff --git a/src/Core/Grand.Domain/Data/DbProvider.cs b/src/Core/Grand.Domain/Data/DbProvider.csindex 839f3fc8e..8e478a455 100644--- a/src/Core/Grand.Domain/Data/DbProvider.cs+++ b/src/Core/Grand.Domain/Data/DbProvider.cs@@ -5,5 +5,6 @@MongoDB,CosmosDB,DocumentDB,+ LiteDB}}diff --git a/src/Core/Grand.Domain/Data/ExpressionFieldDefinition.cs b/src/Core/Grand.Domain/Data/ExpressionFieldDefinition.csnew file mode 100644index 000000000..42359746b--- /dev/null+++ b/src/Core/Grand.Domain/Data/ExpressionFieldDefinition.cs@@ -0,0 +1,17 @@+using System.Linq.Expressions;++namespace Grand.Domain.Data+{+ public class ExpressionFieldDefinition<TDocument, TField>+ {+ public ExpressionFieldDefinition(LambdaExpression expression, TField value)+ {+ Expression = expression;+ Value = value;+ }++ public LambdaExpression Expression { get; }+ public TField Value { get; }++ }+}diff --git a/src/Core/Grand.Domain/Data/IRepository.cs b/src/Core/Grand.Domain/Data/IRepository.csindex 8673a3a6f..f7ebd7994 100644--- a/src/Core/Grand.Domain/Data/IRepository.cs+++ b/src/Core/Grand.Domain/Data/IRepository.cs@@ -33,14 +33,7 @@ namespace Grand.Domain.Data/// </summary>/// <returns>collection of entities</returns>Task<List<T>> GetAllAsync();-- /// <summary>- /// get first item in query as async- /// </summary>- /// <param name="filter"></param>- /// <returns></returns>- Task<T> FirstOrDefaultAsync(Expression<Func<T, bool>> filter);-+/// <summary>/// Insert entity/// </summary>@@ -147,9 +140,8 @@ namespace Grand.Domain.Data/// <param name="elemFieldMatch">Subdocument field to match</param>/// <param name="elemMatch">Subdocument ident value</param>/// <param name="value">Subdocument - to update (all values)</param>- /// <param name="updateMany">Update many records</param>/// <returns></returns>- Task UpdateToSet<U>(string id, Expression<Func<T, IEnumerable<U>>> field, Expression<Func<U, bool>> elemFieldMatch, U value, bool updateMany = false);+ Task UpdateToSet<U>(string id, Expression<Func<T, IEnumerable<U>>> field, Expression<Func<U, bool>> elemFieldMatch, U value);// <summary>/// Update subdocuments@@ -160,9 +152,8 @@ namespace Grand.Domain.Data/// <param name="field"></param>/// <param name="elemFieldMatch">Subdocument field to match</param>/// <param name="value">Subdocument - to update (all values)</param>- /// <param name="updateMany">Update many records</param>/// <returns></returns>- Task UpdateToSet<U>(Expression<Func<T, IEnumerable<U>>> field, U elemFieldMatch, U value, bool updateMany = false);+ Task UpdateToSet<U>(Expression<Func<T, IEnumerable<U>>> field, U elemFieldMatch, U value);/// <summary>@@ -175,7 +166,7 @@ namespace Grand.Domain.Data/// <param name="elemFieldMatch"></param>/// <param name="elemMatch"></param>/// <returns></returns>- Task PullFilter<U, Z>(string id, Expression<Func<T, IEnumerable<U>>> field, Expression<Func<U, Z>> elemFieldMatch, Z elemMatch, bool updateMany = false);+ Task PullFilter<U, Z>(string id, Expression<Func<T, IEnumerable<U>>> field, Expression<Func<U, Z>> elemFieldMatch, Z elemMatch);/// <summary>/// Delete subdocument@@ -192,9 +183,9 @@ namespace Grand.Domain.Data/// </summary>/// <param name="id"></param>/// <param name="field"></param>- /// <param name="elemMatch"></param>+ /// <param name="element"></param>/// <returns></returns>- Task Pull(string id, Expression<Func<T, IEnumerable<string>>> field, string element, bool updateMany = false);+ Task Pull(string id, Expression<Func<T, IEnumerable<string>>> field, string element);/// <summary>/// Async Update entitiesdiff --git a/src/Core/Grand.Domain/Data/LiteDb/LiteDBContext.cs b/src/Core/Grand.Domain/Data/LiteDb/LiteDBContext.csnew file mode 100644index 000000000..26c2118e8--- /dev/null+++ b/src/Core/Grand.Domain/Data/LiteDb/LiteDBContext.cs@@ -0,0 +1,85 @@+using LiteDB;++namespace Grand.Domain.Data.LiteDb+{+ public class LiteDBContext : IDatabaseContext+ {+ protected LiteDatabase _database;++ public LiteDBContext(LiteDatabase database)+ {+ _database = database;+ }++ public void SetConnection(string connectionString)+ {+ if (string.IsNullOrEmpty(connectionString))+ throw new ArgumentNullException(nameof(connectionString));++ }+ //Not supported by LiteDB+ public bool InstallProcessCreateTable => false;+ public bool InstallProcessCreateIndex => true;++ public IQueryable<T> Table<T>(string collectionName)+ {+ if (string.IsNullOrEmpty(collectionName))+ throw new ArgumentNullException(nameof(collectionName));++ return _database.GetCollection<T>(collectionName).FindAll().AsQueryable();+ }++ public async Task<bool> DatabaseExist()+ {+ return await Task.FromResult(_database.CollectionExists(nameof(Common.GrandNodeVersion)));+ }++ public Task CreateTable(string name, string collation)+ {+ //Not supported by LiteDB+ return Task.CompletedTask;+ }++ public Task DeleteTable(string name)+ {+ if (string.IsNullOrEmpty(name))+ throw new ArgumentNullException(nameof(name));++ _database.DropCollection(name);++ return Task.CompletedTask;+ }++ public Task CreateIndex<T>(IRepository<T> repository, OrderBuilder<T> orderBuilder, string indexName, bool unique = false) where T : BaseEntity+ {+ if (string.IsNullOrEmpty(indexName))+ throw new ArgumentNullException(nameof(indexName));+ try+ {+ foreach (var (selector, value, fieldName) in orderBuilder?.Fields)+ {+ var col = _database.GetCollection<T>();+ if (selector != null)+ col.EnsureIndex(selector, unique);+ }+ }+ catch { }++ return Task.CompletedTask;+ }++ public Task DeleteIndex<T>(IRepository<T> repository, string indexName) where T : BaseEntity+ {++ if (string.IsNullOrEmpty(indexName))+ throw new ArgumentNullException(nameof(indexName));+ try+ {+ _database.GetCollection<T>().DropIndex(indexName);+ }+ catch { }++ return Task.CompletedTask;+ }+ }+}diff --git a/src/Core/Grand.Domain/Data/LiteDb/LiteDBRepository.cs b/src/Core/Grand.Domain/Data/LiteDb/LiteDBRepository.csnew file mode 100644index 000000000..ff4c1b7d1--- /dev/null+++ b/src/Core/Grand.Domain/Data/LiteDb/LiteDBRepository.cs@@ -0,0 +1,658 @@+using Grand.SharedKernel.Attributes;+using LiteDB;+using System.Linq.Expressions;+using System.Reflection;++namespace Grand.Domain.Data.LiteDb+{+ /// <summary>+ /// MongoDB repository+ /// </summary>+ public partial class LiteDBRepository<T> : IRepository<T> where T : BaseEntity+ {+ #region Fields++ /// <summary>+ /// Gets the collection+ /// </summary>+ protected ILiteCollection<T> _collection;++ public ILiteCollection<T> Collection {+ get {+ return _collection;+ }+ }++ /// <summary>+ /// Sets a collection+ /// </summary>+ public bool SetCollection(string collectionName)+ {+ _collection = _database.GetCollection<T>(collectionName);+ return true;+ }++ /// <summary>+ /// Mongo Database+ /// </summary>+ protected LiteDatabase _database;+ public LiteDatabase Database {+ get {+ return _database;+ }+ }++ #endregion++ #region Ctor++ /// <summary>+ /// Ctor+ /// </summary>+ public LiteDBRepository()+ {+ var connection = DataSettingsManager.LoadSettings();++ if (!string.IsNullOrEmpty(connection.ConnectionString))+ {+ _database = new LiteDatabase(connection.ConnectionString);+ _collection = _database.GetCollection<T>(typeof(T).Name);+ }+ }+ public LiteDBRepository(string connectionString)+ {+ _database = new LiteDatabase(connectionString);+ _collection = _database.GetCollection<T>(typeof(T).Name);+ }+++ public LiteDBRepository(LiteDatabase database)+ {+ _database = database;+ _collection = _database.GetCollection<T>(typeof(T).Name);+ }++ #endregion++ #region Methods++ /// <summary>+ /// Get entity by identifier+ /// </summary>+ /// <param name="id">Identifier</param>+ /// <returns>Entity</returns>+ public virtual T GetById(string id)+ {+ return _collection.Find(e => e.Id == id).FirstOrDefault();+ }+ /// <summary>+ /// Get async entity by identifier+ /// </summary>+ /// <param name="id">Identifier</param>+ /// <returns>Entity</returns>+ public virtual async Task<T> GetByIdAsync(string id)+ {+ return await Task.FromResult(GetById(id));+ }++ /// <summary>+ /// Get all entities in collection+ /// </summary>+ /// <returns>collection of entities</returns>+ public virtual async Task<List<T>> GetAllAsync()+ {+ return await Task.FromResult(_collection.Query().ToList());+ }++ /// <summary>+ /// Insert entity+ /// </summary>+ /// <param name="entity">Entity</param>+ public virtual T Insert(T entity)+ {+ _collection.Insert(entity);+ return entity;+ }++ /// <summary>+ /// Async Insert entity+ /// </summary>+ /// <param name="entity">Entity</param>+ public virtual async Task<T> InsertAsync(T entity)+ {+ Insert(entity);+ return await Task.FromResult(entity);+ }++ /// <summary>+ /// Async Insert many entities+ /// </summary>+ /// <param name="entities">Entities</param>+ public virtual Task InsertManyAsync(IEnumerable<T> entities)+ {+ Insert(entities);+ return Task.CompletedTask;+ }++ /// <summary>+ /// Insert entities+ /// </summary>+ /// <param name="entities">Entities</param>+ public virtual void Insert(IEnumerable<T> entities)+ {+ _collection.InsertBulk(entities);+ }++ /// <summary>+ /// Async Insert entities+ /// </summary>+ /// <param name="entities">Entities</param>+ public virtual async Task<IEnumerable<T>> InsertAsync(IEnumerable<T> entities)+ {+ Insert(entities);+ return await Task.FromResult(entities);+ }+++ /// <summary>+ /// Update entity+ /// </summary>+ /// <param name="entity">Entity</param>+ public virtual T Update(T entity)+ {+ _collection.Update(entity);+ return entity;++ }++ /// <summary>+ /// Async Update entity+ /// </summary>+ /// <param name="entity">Entity</param>+ public virtual async Task<T> UpdateAsync(T entity)+ {+ Update(entity);+ return await Task.FromResult(entity);+ }+++ /// <summary>+ /// Update entities+ /// </summary>+ /// <param name="entities">Entities</param>+ public virtual void Update(IEnumerable<T> entities)+ {+ foreach (T entity in entities)+ {+ Update(entity);+ }+ }++ /// <summary>+ /// Update field for entity+ /// </summary>+ /// <typeparam name="U">Value</typeparam>+ /// <param name="id">Ident record</param>+ /// <param name="expression">Linq Expression</param>+ /// <param name="value">value</param>+ public virtual Task UpdateField<U>(string id, Expression<Func<T, U>> expression, U value)+ {+ var entity = _database.GetCollection(typeof(T).Name).FindById(new(id));+ var bsonValue = BsonMapper.Global.Serialize<U>(value);+ entity[GetName(expression)] = bsonValue;+ _database.GetCollection(typeof(T).Name).Update(entity);++ return Task.CompletedTask;+ }++ /// <summary>+ /// Updates a single entity.+ /// </summary>+ /// <param name="filterexpression"></param>+ /// <param name="updateBuilder"></param>+ /// <returns></returns>+ public virtual Task UpdateOneAsync(Expression<Func<T, bool>> filterexpression, UpdateBuilder<T> updateBuilder)+ {+ var entity = _collection.FindOne(filterexpression);+ Update(entity, updateBuilder);+ return Task.CompletedTask;+ }++ /// <summary>+ /// Updates a many entities+ /// </summary>+ /// <param name="filterexpression"></param>+ /// <param name="updateBuilder"></param>+ /// <returns></returns>+ public virtual Task UpdateManyAsync(Expression<Func<T, bool>> filterexpression, UpdateBuilder<T> updateBuilder)+ {+ var entities = _collection.Find(filterexpression);+ foreach (var entity in entities)+ {+ Update(entity, updateBuilder);+ }+ return Task.CompletedTask;+ }++ private Task Update(T entity, UpdateBuilder<T> updateBuilder)+ {+ foreach (var item in updateBuilder.ExpressionFields)+ {+ var name = GetName(item.Expression);++ var propertyInfo = entity?.GetType().GetProperty(name,+ BindingFlags.Public | BindingFlags.Instance);++ propertyInfo.SetValue(entity, item.Value);+ }+ _collection.Update(entity);+ return Task.CompletedTask;+ }++ // <summary>+ /// Add to set - add subdocument+ /// </summary>+ /// <typeparam name="U"></typeparam>+ /// <param name="id"></param>+ /// <param name="field"></param>+ /// <param name="value"></param>+ /// <returns></returns>+ public virtual Task AddToSet<U>(string id, Expression<Func<T, IEnumerable<U>>> field, U value)+ {+ var collection = _database.GetCollection(_collection.Name);+ var entity = collection.FindById(new(id));+ var fieldName = ((MemberExpression)field.Body).Member.Name;++ if (entity[fieldName].IsArray)+ {+ var bsonValue = BsonMapper.Global.Serialize<U>(value);+ var list = entity[fieldName].AsArray.ToList();+ list.Add(bsonValue);+ entity[fieldName] = new BsonArray(list);+ collection.Update(entity);+ }+ return Task.CompletedTask;++ }++ /// <summary>+ /// Update subdocument+ /// </summary>+ /// <typeparam name="U">Document</typeparam>+ /// <typeparam name="Z">Subdocuments</typeparam>+ /// <param name="id">Ident of entitie</param>+ /// <param name="field"></param>+ /// <param name="elemFieldMatch">Subdocument field to match</param>+ /// <param name="elemMatch">Subdocument ident value</param>+ /// <param name="value">Subdocument - to update (all values)</param>+ public virtual Task UpdateToSet<U, Z>(string id, Expression<Func<T, IEnumerable<U>>> field, Expression<Func<U, Z>> elemFieldMatch, Z elemMatch, U value)+ {+ var collection = _database.GetCollection(_collection.Name);+ var entity = collection.FindById(new(id));+ var fieldName = ((MemberExpression)field.Body).Member.Name;++ var member = ((MemberExpression)elemFieldMatch.Body).Member;+ var dBFieldName = member.GetCustomAttribute<DBFieldNameAttribute>();+ var elementfieldName = dBFieldName?.Name ?? member.Name;++ if (entity[fieldName].IsArray)+ {+ var bsonValue = BsonMapper.Global.Serialize<U>(value);+ var list = entity[fieldName].AsArray.ToList();+ var document = list.FirstOrDefault(x => x[elementfieldName] == new BsonValue(elemMatch));+ if (document == null) return Task.CompletedTask;++ foreach (var key in bsonValue.AsDocument.Keys)+ {+ document[key] = bsonValue[key];+ }+ entity[fieldName] = new BsonArray(list);+ collection.Update(entity);+ }++ return Task.CompletedTask;++ }++ /// <summary>+ /// Update subdocument+ /// </summary>+ /// <typeparam name="U">Document</typeparam>+ /// <param name="id">Ident of entitie</param>+ /// <param name="field"></param>+ /// <param name="elemFieldMatch">Subdocument field to match</param>+ /// <param name="elemMatch">Subdocument ident value</param>+ /// <param name="value">Subdocument - to update (all values)</param>+ public virtual Task UpdateToSet<U>(string id, Expression<Func<T, IEnumerable<U>>> field, Expression<Func<U, bool>> elemFieldMatch, U value)+ {+ var collection = _database.GetCollection(_collection.Name);+ var entity = collection.FindById(new(id));+ var fieldName = ((MemberExpression)field.Body).Member.Name;+ if (entity == null) return Task.CompletedTask;++ if (entity[fieldName].IsArray)+ {+ var bsonValue = BsonMapper.Global.Serialize<U>(value);+ var list = BsonMapper.Global.Deserialize<IList<U>>(entity[fieldName]).ToList();+ var position = list.FirstOrDefault(elemFieldMatch.Compile());+ if (position == null) return Task.CompletedTask;++ foreach (var item in position.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))+ {+ var propertyField = position.GetType().GetProperty(item.Name,+ BindingFlags.Public | BindingFlags.Instance);++ propertyField.SetValue(position, item.GetValue(value));+ }++ var updatelist = BsonMapper.Global.Serialize<IList<U>>(list);+ entity[fieldName] = updatelist;+ collection.Update(entity);+ }+ return Task.CompletedTask;++ }+ // <summary>+ /// Update subdocuments+ /// </summary>+ /// <typeparam name="T">Document</typeparam>+ /// <typeparam name="Z">Subdocuments</typeparam>+ /// <param name="id">Ident of entitie</param>+ /// <param name="field"></param>+ /// <param name="elemFieldMatch">Subdocument field to match</param>+ /// <param name="value">Subdocument - to update (all values)</param>+ /// <param name="updateMany">Update many records</param>+ /// <returns></returns>+ public virtual Task UpdateToSet<U>(Expression<Func<T, IEnumerable<U>>> field, U elemFieldMatch, U value)+ {+ var collection = _database.GetCollection(_collection.Name);+ var fieldName = ((MemberExpression)field.Body).Member.Name;+ var records = collection.Find(Query.EQ($"{fieldName}[*] ANY", elemFieldMatch.ToString())).ToList();+ foreach (var entity in records)+ {+ if (entity[fieldName].IsArray)+ {+ var bsonValue = BsonMapper.Global.Serialize<U>(value);+ var oldbsonValue = BsonMapper.Global.Serialize<U>(elemFieldMatch);+ var list = entity[fieldName].AsArray.ToList();+ if (list!=null && list.Any())+ {+ list.Add(bsonValue);+ list.Remove(oldbsonValue);+ entity[fieldName] = new BsonArray(list);+ collection.Update(entity);+ }+ }+ }+ return Task.CompletedTask;++ }+ /// <summary>+ /// Delete subdocument+ /// </summary>+ /// <typeparam name="U"></typeparam>+ /// <typeparam name="Z"></typeparam>+ /// <param name="id"></param>+ /// <param name="field"></param>+ /// <param name="elemFieldMatch"></param>+ /// <param name="elemMatch"></param>+ /// <returns></returns>+ public virtual Task PullFilter<U, Z>(string id, Expression<Func<T, IEnumerable<U>>> field, Expression<Func<U, Z>> elemFieldMatch, Z elemMatch)+ {+ var collection = _database.GetCollection(_collection.Name);+ var fieldName = ((MemberExpression)field.Body).Member.Name;++ var member = ((MemberExpression)elemFieldMatch.Body).Member;+ var dBFieldName = member.GetCustomAttribute<DBFieldNameAttribute>();+ var elementfieldName = dBFieldName?.Name ?? member.Name;++ if (string.IsNullOrEmpty(id))+ {+ //update many+ var entities = collection.FindAll();+ foreach (var entity in entities)+ {+ UpdateEntity(entity);+ }+ }+ else+ {+ //update one+ var entity = collection.FindById(new(id));+ UpdateEntity(entity);+ }++ void UpdateEntity(BsonDocument entity)+ {+ if (entity != null && entity[fieldName].IsArray)+ {+ var bsonValue = BsonMapper.Global.Serialize<Z>(elemMatch);+ var list = entity[fieldName].AsArray.ToList();+ var documents = list.Where(x => x[elementfieldName] == new BsonValue(elemMatch)).ToList();+ if (documents != null && documents.Any())+ {+ foreach (var document in documents)+ {+ list.Remove(document);+ }+ entity[fieldName] = new BsonArray(list);+ collection.Update(entity);+ }+ }+ }++ return Task.CompletedTask;++ }++ /// <summary>+ /// Delete subdocument+ /// </summary>+ /// <typeparam name="U"></typeparam>+ /// <param name="id"></param>+ /// <param name="field"></param>+ /// <param name="elemFieldMatch"></param>+ /// <returns></returns>+ public virtual Task PullFilter<U>(string id, Expression<Func<T, IEnumerable<U>>> field, Expression<Func<U, bool>> elemFieldMatch)+ {++ var collection = _database.GetCollection(_collection.Name);+ var entity = collection.FindById(new(id));+ var fieldName = ((MemberExpression)field.Body).Member.Name;+ if (entity == null) return Task.CompletedTask;++ if (entity[fieldName].IsArray)+ {+ var list = BsonMapper.Global.Deserialize<IList<U>>(entity[fieldName]).ToList();+ var position = list.FirstOrDefault(elemFieldMatch.Compile());+ if (position == null) return Task.CompletedTask;++ list.Remove(position);++ var updatelist = BsonMapper.Global.Serialize<IList<U>>(list);+ entity[fieldName] = updatelist;+ collection.Update(entity);+ }+ return Task.CompletedTask;+ }++ /// <summary>+ /// Delete subdocument+ /// </summary>+ /// <param name="id"></param>+ /// <param name="field"></param>+ /// <param name="element"></param>+ /// <returns></returns>+ public virtual Task Pull(string id, Expression<Func<T, IEnumerable<string>>> field, string element)+ {+ var collection = _database.GetCollection(_collection.Name);+ var fieldName = ((MemberExpression)field.Body).Member.Name;+ if (string.IsNullOrEmpty(id))+ {+ var entities = collection.Find(Query.EQ($"{fieldName}[*] ANY", element.ToString())).ToList();+ foreach (var entity in entities)+ {+ UpdateEntity(entity);+ }+ }+ else+ {+ //update one+ var entity = collection.FindById(new(id));+ UpdateEntity(entity);+ }++ void UpdateEntity(BsonDocument entity)+ {+ if (entity != null && entity[fieldName].IsArray)+ {+ var list = entity[fieldName].AsArray.ToList();+ if (list!=null && list.Any())+ {+ list.Remove(new BsonValue(element));+ entity[fieldName] = new BsonArray(list);+ collection.Update(entity);+ }+ }+ }++ return Task.CompletedTask;++ }+ /// <summary>+ /// Async Update entities+ /// </summary>+ /// <param name="entities">Entities</param>+ public virtual async Task<IEnumerable<T>> UpdateAsync(IEnumerable<T> entities)+ {+ foreach (T entity in entities)+ {+ await UpdateAsync(entity);+ }+ return entities;+ }++ /// <summary>+ /// Delete entity+ /// </summary>+ /// <param name="entity">Entity</param>+ public virtual void Delete(T entity)+ {+ _collection.Delete(new BsonValue(entity.Id));+ }++ /// <summary>+ /// Async Delete entity+ /// </summary>+ /// <param name="entity">Entity</param>+ public virtual async Task<T> DeleteAsync(T entity)+ {+ Delete(entity);+ return await Task.FromResult(entity);+ }++ /// <summary>+ /// Delete entities+ /// </summary>+ /// <param name="entities">Entities</param>+ public virtual void Delete(IEnumerable<T> entities)+ {+ foreach (T entity in entities)+ {+ Delete(entity);+ }+ }++ /// <summary>+ /// Async Delete entities+ /// </summary>+ /// <param name="entities">Entities</param>+ public virtual async Task<IEnumerable<T>> DeleteAsync(IEnumerable<T> entities)+ {+ foreach (T entity in entities)+ {+ await DeleteAsync(entity);+ }+ return entities;+ }+ /// <summary>+ /// Delete a many entities+ /// </summary>+ /// <param name="filterexpression"></param>+ /// <returns></returns>+ public virtual Task DeleteManyAsync(Expression<Func<T, bool>> filterexpression)+ {+ _collection.DeleteMany(filterexpression);+ return Task.CompletedTask;+ }++ /// <summary>+ /// Clear entities+ /// </summary>+ public Task ClearAsync()+ {+ _collection.DeleteAll();+ return Task.CompletedTask;+ }++ #endregion++ #region Properties++ /// <summary>+ /// Gets a table+ /// </summary>+ public virtual IQueryable<T> Table {+ get { return _collection.Query().ToEnumerable().AsQueryable(); }+ }++ /// <summary>+ /// Gets a table collection+ /// </summary>+ public virtual IQueryable<T> TableCollection(string collectionName)+ {+ return _database.GetCollection<T>(collectionName).Query().ToEnumerable().AsQueryable();+ }++ #endregion++ #region Helpers++++ private string GetName(LambdaExpression lambdaexpression)+ {+ var expression = (MemberExpression)lambdaexpression.Body;+ return expression.Member.Name;+ }+ private string GetName<TSource, TField>(Expression<Func<TSource, TField>> Field)+ {+ if (object.Equals(Field, null))+ {+ throw new NullReferenceException("Field is required");+ }++ MemberExpression expr = null;++ if (Field.Body is MemberExpression expression)+ {+ expr = expression;+ }+ else if (Field.Body is UnaryExpression)+ {+ expr = (MemberExpression)((UnaryExpression)Field.Body).Operand;+ }+ else+ {+ const string Format = "Expression '{0}' not supported.";+ var message = string.Format(Format, Field);++ throw new ArgumentException(message, "Field");+ }++ return expr.Member.Name;+ }++ #endregion+ }+}\ No newline at end of filediff --git a/src/Core/Grand.Domain/Data/LiteDb/LiteDBStartupBase.cs b/src/Core/Grand.Domain/Data/LiteDb/LiteDBStartupBase.csnew file mode 100644index 000000000..d65b06dc5--- /dev/null+++ b/src/Core/Grand.Domain/Data/LiteDb/LiteDBStartupBase.cs@@ -0,0 +1,17 @@+using Grand.SharedKernel;+using LiteDB;++namespace Grand.Domain.Data.LiteDb+{+ public class LiteDBStartupBase : IStartupBase+ {+ public int Priority => 0;++ public void Execute()+ {+ BsonMapper.Global.EmptyStringToNull = false;+ BsonMapper.Global.SerializeNullValues = true;+ BsonMapper.Global.EnumAsInteger = true;+ }+ }+}diff --git a/src/Core/Grand.Domain/Data/LiteDb/LiteDBStoreFilesContext.cs b/src/Core/Grand.Domain/Data/LiteDb/LiteDBStoreFilesContext.csnew file mode 100644index 000000000..105067b17--- /dev/null+++ b/src/Core/Grand.Domain/Data/LiteDb/LiteDBStoreFilesContext.cs@@ -0,0 +1,46 @@+using LiteDB;++namespace Grand.Domain.Data.LiteDb+{+ public class LiteDBStoreFilesContext : IStoreFilesContext+ {+ protected LiteDatabase _database;++ public LiteDBStoreFilesContext(LiteDatabase database)+ {+ _database = database;+ }++ public async Task<byte[]> BucketDownload(string id)+ {+ var fs = _database.FileStorage;+ var file = fs.FindById(id);++ if (file == null)+ throw new ArgumentNullException(nameof(file));++ using (var stream = file.OpenRead())+ using (MemoryStream mstream = new ())+ {+ stream.CopyTo(mstream);+ return await Task.FromResult(mstream.ToArray());+ }+ }+ public Task BucketDelete(string id)+ {+ var fs = _database.FileStorage;+ fs.Delete(id);++ return Task.CompletedTask;+ }++ public async Task<string> BucketUploadFromBytes(string filename, byte[] source)+ {+ var id = UniqueIdentifier.New;+ var fs = _database.FileStorage;+ fs.Upload(id, filename, new MemoryStream(source));++ return await Task.FromResult(id);+ }+ }+}diff --git a/src/Core/Grand.Domain/Data/Mongo/BsonUtcDateTimeSerializer.cs b/src/Core/Grand.Domain/Data/Mongo/BsonUtcDateTimeSerializer.csindex ce66a20dc..8d1287ee7 100644--- a/src/Core/Grand.Domain/Data/Mongo/BsonUtcDateTimeSerializer.cs+++ b/src/Core/Grand.Domain/Data/Mongo/BsonUtcDateTimeSerializer.cs@@ -7,7 +7,7 @@ namespace Grand.Domain.Data.Mongo{public override DateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args){- return new DateTime(base.Deserialize(context, args).Ticks, DateTimeKind.Unspecified);+ return new DateTime(base.Deserialize(context, args).Ticks, DateTimeKind.Utc);}public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTime value)diff --git a/src/Core/Grand.Domain/Data/Mongo/MongoDBMapperConfiguration.cs b/src/Core/Grand.Domain/Data/Mongo/MongoDBStartupBase.cssimilarity index 73%rename from src/Core/Grand.Domain/Data/Mongo/MongoDBMapperConfiguration.csrename to src/Core/Grand.Domain/Data/Mongo/MongoDBStartupBase.csindex 76462276a..305a040fe 100644--- a/src/Core/Grand.Domain/Data/Mongo/MongoDBMapperConfiguration.cs+++ b/src/Core/Grand.Domain/Data/Mongo/MongoDBStartupBase.cs@@ -1,20 +1,20 @@-using MongoDB.Bson.Serialization;+using Grand.SharedKernel;+using MongoDB.Bson.Serialization;using MongoDB.Bson.Serialization.Conventions;using MongoDB.Bson.Serialization.Options;using MongoDB.Bson.Serialization.Serializers;namespace Grand.Domain.Data.Mongo{- public static class MongoDBMapperConfiguration+ public class MongoDBStartupBase : IStartupBase{+ public int Priority => 0;/// <summary>/// Register MongoDB mappings/// </summary>- public static void RegisterMongoDBMappings()+ public void Execute(){- //BsonSerializer.RegisterSerializer(new DecimalSerializer(BsonType.Decimal128));- //BsonSerializer.RegisterSerializer(typeof(double?), new NullableSerializer<double>(new DecimalSerializer(BsonType.Decimal128)));BsonSerializer.RegisterSerializer(typeof(DateTime), new BsonUtcDateTimeSerializer());BsonSerializer.RegisterSerializer(typeof(Dictionary<int, int>),@@ -26,7 +26,6 @@ namespace Grand.Domain.Data.Mongo};ConventionRegistry.Register("ApplicationConventions", cp, t => true);-BsonClassMap.RegisterClassMap<Media.Download>(cm =>{cm.AutoMap();diff --git a/src/Core/Grand.Domain/Data/Mongo/MongoRepository.cs b/src/Core/Grand.Domain/Data/Mongo/MongoRepository.csindex 9c2078bd6..8bf313283 100644--- a/src/Core/Grand.Domain/Data/Mongo/MongoRepository.cs+++ b/src/Core/Grand.Domain/Data/Mongo/MongoRepository.cs@@ -108,17 +108,7 @@ namespace Grand.Domain.Data.Mongo{return _collection.AsQueryable().ToListAsync();}-- /// <summary>- /// get first item in query as async- /// </summary>- /// <param name="filter"></param>- /// <returns></returns>- public virtual Task<T> FirstOrDefaultAsync(Expression<Func<T, bool>> filter)- {- return _collection.Find(filter).FirstOrDefaultAsync();- }-+/// <summary>/// Insert entity/// </summary>@@ -292,7 +282,7 @@ namespace Grand.Domain.Data.Mongo/// <param name="elemFieldMatch">Subdocument field to match</param>/// <param name="elemMatch">Subdocument ident value</param>/// <param name="value">Subdocument - to update (all values)</param>- public virtual async Task UpdateToSet<U>(string id, Expression<Func<T, IEnumerable<U>>> field, Expression<Func<U, bool>> elemFieldMatch, U value, bool updateMany = false)+ public virtual async Task UpdateToSet<U>(string id, Expression<Func<T, IEnumerable<U>>> field, Expression<Func<U, bool>> elemFieldMatch, U value){var filter = string.IsNullOrEmpty(id) ? Builders<T>.Filter.Where(x => true) : Builders<T>.Filter.Eq(x => x.Id, id)& Builders<T>.Filter.ElemMatch(field, elemFieldMatch);@@ -301,7 +291,7 @@ namespace Grand.Domain.Data.MongoMemberInfo minfo = me.Member;var update = Builders<T>.Update.Set($"{minfo.Name}.$", value);- if (updateMany)+ if (string.IsNullOrEmpty(id)){await _collection.UpdateManyAsync(filter, update);}@@ -322,7 +312,7 @@ namespace Grand.Domain.Data.Mongo/// <param name="value">Subdocument - to update (all values)</param>/// <param name="updateMany">Update many records</param>/// <returns></returns>- public virtual async Task UpdateToSet<U>(Expression<Func<T, IEnumerable<U>>> field, U elemFieldMatch, U value, bool updateMany = false)+ public virtual async Task UpdateToSet<U>(Expression<Func<T, IEnumerable<U>>> field, U elemFieldMatch, U value){MemberExpression me = field.Body as MemberExpression;MemberInfo minfo = me.Member;@@ -346,11 +336,11 @@ namespace Grand.Domain.Data.Mongo/// <param name="elemFieldMatch"></param>/// <param name="elemMatch"></param>/// <returns></returns>- public virtual async Task PullFilter<U, Z>(string id, Expression<Func<T, IEnumerable<U>>> field, Expression<Func<U, Z>> elemFieldMatch, Z elemMatch, bool updateMany = false)+ public virtual async Task PullFilter<U, Z>(string id, Expression<Func<T, IEnumerable<U>>> field, Expression<Func<U, Z>> elemFieldMatch, Z elemMatch){var filter = string.IsNullOrEmpty(id) ? Builders<T>.Filter.Where(x => true) : Builders<T>.Filter.Eq(x => x.Id, id);var update = Builders<T>.Update.PullFilter(field, Builders<U>.Filter.Eq(elemFieldMatch, elemMatch));- if (updateMany)+ if (string.IsNullOrEmpty(id)){await _collection.UpdateManyAsync(filter, update);}@@ -379,19 +369,18 @@ namespace Grand.Domain.Data.Mongo/// </summary>/// <param name="id"></param>/// <param name="field"></param>- /// <param name="elemMatch"></param>+ /// <param name="element"></param>/// <returns></returns>- public virtual async Task Pull(string id, Expression<Func<T, IEnumerable<string>>> field, string element, bool updateMany = false)+ public virtual async Task Pull(string id, Expression<Func<T, IEnumerable<string>>> field, string element){- var filter = string.IsNullOrEmpty(id) ? Builders<T>.Filter.Where(x => true) : Builders<T>.Filter.Eq(x => x.Id, id);var update = Builders<T>.Update.Pull(field, element);- if (updateMany)+ if (string.IsNullOrEmpty(id)){- await _collection.UpdateManyAsync(filter, update);+ await _collection.UpdateManyAsync(Builders<T>.Filter.Where(x => true), update);}else{- await _collection.UpdateOneAsync(filter, update);+ await _collection.UpdateOneAsync(Builders<T>.Filter.Eq(x => x.Id, id), update);}}/// <summary>diff --git a/src/Core/Grand.Domain/Data/UpdateBuilder.cs b/src/Core/Grand.Domain/Data/UpdateBuilder.csindex 4141d7f12..90820f431 100644--- a/src/Core/Grand.Domain/Data/UpdateBuilder.cs+++ b/src/Core/Grand.Domain/Data/UpdateBuilder.cs@@ -6,6 +6,7 @@ namespace Grand.Domain.Datapublic class UpdateBuilder<T>{private readonly List<UpdateDefinition<T>> _list = new();+ private readonly List<ExpressionFieldDefinition<T, object>> _expressionFieldDefinitions = new();protected UpdateBuilder() { }@@ -16,13 +17,22 @@ namespace Grand.Domain.Datapublic UpdateBuilder<T> Set<TProperty>(Expression<Func<T, TProperty>> selector, TProperty value){+ //for mongodb_list.Add(Builders<T>.Update.Set(selector, value));++ //for other Db+ _expressionFieldDefinitions.Add(new ExpressionFieldDefinition<T, object>(selector, value));+return this;}public IEnumerable<UpdateDefinition<T>> Fields {get { return _list; }}++ public IEnumerable<ExpressionFieldDefinition<T, object>> ExpressionFields {+ get { return _expressionFieldDefinitions; }+ }}}diff --git a/src/Core/Grand.Domain/Grand.Domain.csproj b/src/Core/Grand.Domain/Grand.Domain.csprojindex 437b64591..1213dc6fb 100644--- a/src/Core/Grand.Domain/Grand.Domain.csproj+++ b/src/Core/Grand.Domain/Grand.Domain.csproj@@ -1,6 +1,7 @@<Project Sdk="Microsoft.NET.Sdk"><Import Project="..\..\Build\Grand.Common.props" /><ItemGroup>+ <PackageReference Include="LiteDB" Version="5.0.11" /><PackageReference Include="MongoDB.Bson" Version="2.14.1" /><PackageReference Include="MongoDB.Driver" Version="2.14.1" /><PackageReference Include="MongoDB.Driver.Core" Version="2.14.1" />diff --git a/src/Core/Grand.Domain/ParentEntity.cs b/src/Core/Grand.Domain/ParentEntity.csindex a5e84bfdf..78e60cfd4 100644--- a/src/Core/Grand.Domain/ParentEntity.cs+++ b/src/Core/Grand.Domain/ParentEntity.cs@@ -1,4 +1,5 @@using Grand.Domain.Data;+using Grand.SharedKernel.Attributes;namespace Grand.Domain{@@ -9,6 +10,7 @@ namespace Grand.Domain_id = UniqueIdentifier.New;}+ [DBFieldName("_id")]public string Id{get { return _id; }diff --git a/src/Core/Grand.Infrastructure/Configuration/LiteDbConfig.cs b/src/Core/Grand.Infrastructure/Configuration/LiteDbConfig.csnew file mode 100644index 000000000..4af09cf9b--- /dev/null+++ b/src/Core/Grand.Infrastructure/Configuration/LiteDbConfig.cs@@ -0,0 +1,20 @@+namespace Grand.Infrastructure.Configuration+{+ public partial class LiteDbConfig+ {+ /// <summary>+ /// Gets or sets a value indicating whether use LiteDB database for your application+ /// </summary>+ public bool UseLiteDb { get; set; }++ /// <summary>+ /// Gets or sets a value indicating whether use LiteDB database as a singleton service in the application+ /// </summary>+ public bool Singleton{ get; set; }++ /// <summary>+ /// Gets or sets a value indicating whether use LiteDB database (only for installation process)+ /// </summary>+ public string LiteDbConnectionString { get; set; }+ }+}diff --git a/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs b/src/Core/Grand.Infrastructure/Startup/StartupApplication.csindex 528be0491..b9c1702c8 100644--- a/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs+++ b/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs@@ -1,5 +1,8 @@using Grand.Domain.Data;+using Grand.Domain.Data.LiteDb;using Grand.Domain.Data.Mongo;+using Grand.Infrastructure.Configuration;+using LiteDB;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;@@ -22,33 +25,60 @@ namespace Grand.Infrastructure.Startuppublic void ConfigureServices(IServiceCollection services, IConfiguration configuration){- RegisterDataLayer(services);+ var config = new LiteDbConfig();+ configuration.GetSection("LiteDb").Bind(config);+ RegisterDataLayer(services, config);}- private void RegisterDataLayer(IServiceCollection serviceCollection)+ private void RegisterDataLayer(IServiceCollection serviceCollection, LiteDbConfig litedbConfig){var dataProviderSettings = DataSettingsManager.LoadSettings();if (string.IsNullOrEmpty(dataProviderSettings.ConnectionString)){serviceCollection.AddTransient(c => dataProviderSettings);++ if(litedbConfig.UseLiteDb)+ serviceCollection.AddSingleton(c => new LiteDatabase(litedbConfig.LiteDbConnectionString));}if (dataProviderSettings != null && dataProviderSettings.IsValid()){- var connectionString = dataProviderSettings.ConnectionString;- var mongourl = new MongoUrl(connectionString);- var databaseName = mongourl.DatabaseName;- var clientSettings = MongoClientSettings.FromConnectionString(connectionString);- clientSettings.LinqProvider = MongoDB.Driver.Linq.LinqProvider.V3;- serviceCollection.AddScoped(c => new MongoClient(clientSettings).GetDatabase(databaseName));- }+ if (dataProviderSettings.DbProvider != DbProvider.LiteDB)+ {+ var connectionString = dataProviderSettings.ConnectionString;+ var mongourl = new MongoUrl(connectionString);+ var databaseName = mongourl.DatabaseName;+ var clientSettings = MongoClientSettings.FromConnectionString(connectionString);+ clientSettings.LinqProvider = MongoDB.Driver.Linq.LinqProvider.V3;+ serviceCollection.AddScoped(c => new MongoClient(clientSettings).GetDatabase(databaseName));+ }+ else+ {+ if(litedbConfig.Singleton)+ serviceCollection.AddSingleton(c => new LiteDatabase(dataProviderSettings.ConnectionString) { UtcDate = true });+ else+ serviceCollection.AddScoped(c => new LiteDatabase(dataProviderSettings.ConnectionString) { UtcDate = true });- //database context- serviceCollection.AddScoped<IDatabaseContext, MongoDBContext>();- //store files context - gridfs- serviceCollection.AddScoped<IStoreFilesContext, MongoStoreFilesContext>();+ }+ }+ if (!litedbConfig.UseLiteDb)+ {+ //database context+ serviceCollection.AddScoped<IDatabaseContext, MongoDBContext>();+ //store files context - gridfs+ serviceCollection.AddScoped<IStoreFilesContext, MongoStoreFilesContext>();+ //Mongo Repository+ serviceCollection.AddScoped(typeof(IRepository<>), typeof(MongoRepository<>));+ }+ else+ {+ //database context+ serviceCollection.AddScoped<IDatabaseContext, LiteDBContext>();+ //store files context - gridfs+ serviceCollection.AddScoped<IStoreFilesContext, LiteDBStoreFilesContext>();+ //Mongo Repository+ serviceCollection.AddScoped(typeof(IRepository<>), typeof(LiteDBRepository<>));- //Mongo Repository- serviceCollection.AddScoped(typeof(IRepository<>), typeof(MongoRepository<>));+ }}}diff --git a/src/Core/Grand.Infrastructure/StartupBase.cs b/src/Core/Grand.Infrastructure/StartupBase.csindex 6955cb224..13cf2fedb 100644--- a/src/Core/Grand.Infrastructure/StartupBase.cs+++ b/src/Core/Grand.Infrastructure/StartupBase.cs@@ -1,6 +1,5 @@using AutoMapper;using FluentValidation.AspNetCore;-using Grand.Domain.Data.Mongo;using Grand.Infrastructure.Caching.RabbitMq;using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Mapper;@@ -8,6 +7,7 @@ using Grand.Infrastructure.Plugins;using Grand.Infrastructure.Roslyn;using Grand.Infrastructure.TypeConverters;using Grand.Infrastructure.TypeSearchers;+using Grand.SharedKernel;using Grand.SharedKernel.Extensions;using MassTransit;using MediatR;@@ -194,6 +194,8 @@ namespace Grand.Infrastructureservices.StartupConfig<ApiConfig>(configuration.GetSection("Api"));//add grand.web api token configservices.StartupConfig<GrandWebApiConfig>(configuration.GetSection("GrandWebApi"));+ //add litedb configuration parameters+ services.StartupConfig<LiteDbConfig>(configuration.GetSection("LiteDb"));//set base application pathvar provider = services.BuildServiceProvider();@@ -210,9 +212,6 @@ namespace Grand.InfrastructureCommonHelper.IgnoreAcl = config.IgnoreAcl;CommonHelper.IgnoreStoreLimitations = config.IgnoreStoreLimitations;- //register mongo mappings- MongoDBMapperConfiguration.RegisterMongoDBMappings();-var mvcCoreBuilder = services.AddMvcCore();return mvcCoreBuilder;@@ -282,6 +281,9 @@ namespace Grand.Infrastructure//configure servicesforeach (var instance in instancesAfter)instance.ConfigureServices(services, configuration);++ //Execute startupbase interface+ ExecuteStartupBase(typeSearcher);}/// <summary>@@ -306,6 +308,20 @@ namespace Grand.Infrastructureinstance.Configure(application, webHostEnvironment);}+ private static void ExecuteStartupBase(AppTypeSearcher 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);++ //execute+ foreach (var instance in instances)+ instance.Execute();+ }+#endregion}diff --git a/src/Core/Grand.SharedKernel/Attributes/DBFieldNameAttribute.cs b/src/Core/Grand.SharedKernel/Attributes/DBFieldNameAttribute.csnew file mode 100644index 000000000..1c5dfe326--- /dev/null+++ b/src/Core/Grand.SharedKernel/Attributes/DBFieldNameAttribute.cs@@ -0,0 +1,16 @@+namespace Grand.SharedKernel.Attributes+{+ [AttributeUsage(AttributeTargets.Property)]+ public class DBFieldNameAttribute : Attribute+ {+ private string name;++ public DBFieldNameAttribute(string name)+ {+ this.name = name;+ }+ public virtual string Name {+ get { return name; }+ }+ }+}diff --git a/src/Core/Grand.SharedKernel/Extensions/CommonPath.cs b/src/Core/Grand.SharedKernel/Extensions/CommonPath.csindex 384e3bcd0..5888fcb7d 100644--- a/src/Core/Grand.SharedKernel/Extensions/CommonPath.cs+++ b/src/Core/Grand.SharedKernel/Extensions/CommonPath.cs@@ -4,7 +4,7 @@ namespace Grand.SharedKernel.Extensions{public static class CommonPath{- private static string AppData => "App_Data";+ public static string AppData => "App_Data";/// <summary>/// Extra parameter to path/// </summary>diff --git a/src/Core/Grand.SharedKernel/IStartupBase.cs b/src/Core/Grand.SharedKernel/IStartupBase.csnew file mode 100644index 000000000..346a78aad--- /dev/null+++ b/src/Core/Grand.SharedKernel/IStartupBase.cs@@ -0,0 +1,15 @@+namespace Grand.SharedKernel+{+ public interface IStartupBase+ {+ /// <summary>+ /// Execute+ /// </summary>+ void Execute();++ /// <summary>+ /// Priority+ /// </summary>+ int Priority { get; }+ }+}diff --git a/src/Plugins/Authentication.Facebook/Areas/Admin/Controllers/FacebookAuthenticationSettingsController.cs b/src/Plugins/Authentication.Facebook/Areas/Admin/Controllers/FacebookAuthenticationSettingsController.csindex c0ae4712f..d6208c8dc 100644--- a/src/Plugins/Authentication.Facebook/Areas/Admin/Controllers/FacebookAuthenticationSettingsController.cs+++ b/src/Plugins/Authentication.Facebook/Areas/Admin/Controllers/FacebookAuthenticationSettingsController.cs@@ -7,6 +7,7 @@ using Grand.Web.Common.Controllers;using Grand.Web.Common.Filters;using Grand.Web.Common.Security.Authorization;using Microsoft.AspNetCore.Mvc;+using Microsoft.Extensions.Configuration;namespace Authentication.Facebook.Controllers{@@ -21,6 +22,7 @@ namespace Authentication.Facebook.Controllersprivate readonly ITranslationService _translationService;private readonly IPermissionService _permissionService;private readonly ISettingService _settingService;+ private readonly IConfiguration _configuration;#endregion@@ -29,12 +31,14 @@ namespace Authentication.Facebook.Controllerspublic FacebookAuthenticationSettingsController(FacebookExternalAuthSettings facebookExternalAuthSettings,ITranslationService translationService,IPermissionService permissionService,- ISettingService settingService)+ ISettingService settingService,+ IConfiguration configuration){_facebookExternalAuthSettings = facebookExternalAuthSettings;_translationService = translationService;_permissionService = permissionService;_settingService = settingService;+ _configuration = configuration;}#endregion@@ -47,8 +51,8 @@ namespace Authentication.Facebook.Controllersreturn AccessDeniedView();var model = new ConfigurationModel {- ClientId = _facebookExternalAuthSettings.ClientKeyIdentifier,- ClientSecret = _facebookExternalAuthSettings.ClientSecret,+ ClientId = _configuration["FacebookSettings:AppId"],+ ClientSecret = _configuration["FacebookSettings:AppSecret"],DisplayOrder = _facebookExternalAuthSettings.DisplayOrder};@@ -65,8 +69,6 @@ namespace Authentication.Facebook.Controllersif (!ModelState.IsValid)return await Configure();- _facebookExternalAuthSettings.ClientKeyIdentifier = model.ClientId;- _facebookExternalAuthSettings.ClientSecret = model.ClientSecret;_facebookExternalAuthSettings.DisplayOrder = model.DisplayOrder;await _settingService.SaveSetting(_facebookExternalAuthSettings);diff --git a/src/Plugins/Authentication.Facebook/Areas/Admin/Views/FacebookAuthenticationSettings/Configure.cshtml b/src/Plugins/Authentication.Facebook/Areas/Admin/Views/FacebookAuthenticationSettings/Configure.cshtmlindex c9073cab2..5f3cb6078 100644--- a/src/Plugins/Authentication.Facebook/Areas/Admin/Views/FacebookAuthenticationSettings/Configure.cshtml+++ b/src/Plugins/Authentication.Facebook/Areas/Admin/Views/FacebookAuthenticationSettings/Configure.cshtml@@ -21,13 +21,19 @@8. Click the <b>Dashboard</b> link in the left navigation.<br />9. Copy your App ID and App secret below.<br /></p>+ <p>+ <br /><br />+ To edit facebook settings in the grandnode application, please open the file App_Settings.json,+ find section FacebookSettings and enter the correct values.+ </p></div><div class="form-group"><div class="col-md-3 col-sm-3 text-right"><admin-label asp-for="ClientId" class="control-label" /></div><div class="col-md-9 col-sm-9">- <admin-input asp-for="ClientId" />+ <input asp-for=ClientId type="text"+ disabled class="form-control k-input text-box single-line" /><span asp-validation-for="ClientId"></span></div></div>@@ -36,7 +42,7 @@<admin-label asp-for="ClientSecret" class="control-label" /></div><div class="col-md-9 col-sm-9">- <admin-input asp-for="ClientSecret" />+ <input asp-for=ClientSecret type="text" disabled class="form-control k-input text-box single-line" /><span asp-validation-for="ClientSecret"></span></div></div>diff --git a/src/Plugins/Authentication.Facebook/Controllers/FacebookAuthenticationController.cs b/src/Plugins/Authentication.Facebook/Controllers/FacebookAuthenticationController.csindex 9b57de8c9..891c41815 100644--- a/src/Plugins/Authentication.Facebook/Controllers/FacebookAuthenticationController.cs+++ b/src/Plugins/Authentication.Facebook/Controllers/FacebookAuthenticationController.cs@@ -6,6 +6,7 @@ using Grand.Web.Common.Controllers;using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Authentication.Facebook;using Microsoft.AspNetCore.Mvc;+using Microsoft.Extensions.Configuration;using System.Security.Claims;namespace Authentication.Facebook.Controllers@@ -14,18 +15,19 @@ namespace Authentication.Facebook.Controllers{#region Fields- private readonly FacebookExternalAuthSettings _facebookExternalAuthSettings;private readonly IExternalAuthenticationService _externalAuthenticationService;+ private readonly IConfiguration _configuration;#endregion#region Ctor- public FacebookAuthenticationController(FacebookExternalAuthSettings facebookExternalAuthSettings,- IExternalAuthenticationService externalAuthenticationService)+ public FacebookAuthenticationController(+ IExternalAuthenticationService externalAuthenticationService,+ IConfiguration configuration){- _facebookExternalAuthSettings = facebookExternalAuthSettings;_externalAuthenticationService = externalAuthenticationService;+ _configuration = configuration;}#endregion@@ -37,7 +39,7 @@ namespace Authentication.Facebook.Controllersif (!_externalAuthenticationService.AuthenticationProviderIsAvailable(FacebookAuthenticationDefaults.ProviderSystemName))throw new GrandException("Facebook authentication module cannot be loaded");- if (string.IsNullOrEmpty(_facebookExternalAuthSettings.ClientKeyIdentifier) || string.IsNullOrEmpty(_facebookExternalAuthSettings.ClientSecret))+ if (string.IsNullOrEmpty(_configuration["FacebookSettings:AppId"]) || string.IsNullOrEmpty(_configuration["FacebookSettings:AppSecret"]))throw new GrandException("Facebook authentication module not configured");//configure login callback actiondiff --git a/src/Plugins/Authentication.Facebook/FacebookAuthenticationPlugin.cs b/src/Plugins/Authentication.Facebook/FacebookAuthenticationPlugin.csindex 9b05a9e87..097170377 100644--- a/src/Plugins/Authentication.Facebook/FacebookAuthenticationPlugin.cs+++ b/src/Plugins/Authentication.Facebook/FacebookAuthenticationPlugin.cs@@ -54,9 +54,7 @@ namespace Authentication.Facebook//localesawait this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Authentication.Facebook.Login", "Login using Facebook account");await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Authentication.Facebook.ClientKeyIdentifier", "App ID/API Key");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Authentication.Facebook.ClientKeyIdentifier.Hint", "Enter your app ID/API key here. You can find it on your FaceBook application page.");await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Authentication.Facebook.ClientSecret", "App Secret");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Authentication.Facebook.ClientSecret.Hint", "Enter your app secret here. You can find it on your FaceBook application page.");await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Authentication.Facebook.Failed", "Facebook - Login error");await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Authentication.Facebook.Failed.ErrorCode", "Error code");await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Authentication.Facebook.Failed.ErrorMessage", "Error message");@@ -76,9 +74,7 @@ namespace Authentication.Facebook//localesawait this.DeletePluginTranslationResource(_translationService, _languageService, "Authentication.Facebook.Login");await this.DeletePluginTranslationResource(_translationService, _languageService, "Authentication.Facebook.ClientKeyIdentifier");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Authentication.Facebook.ClientKeyIdentifier.Hint");await this.DeletePluginTranslationResource(_translationService, _languageService, "Authentication.Facebook.ClientSecret");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Authentication.Facebook.ClientSecret.Hint");await base.Uninstall();}diff --git a/src/Plugins/Authentication.Facebook/FacebookExternalAuthSettings.cs b/src/Plugins/Authentication.Facebook/FacebookExternalAuthSettings.csindex 0f32c9ab1..e5f2f1845 100644--- a/src/Plugins/Authentication.Facebook/FacebookExternalAuthSettings.cs+++ b/src/Plugins/Authentication.Facebook/FacebookExternalAuthSettings.cs@@ -6,17 +6,7 @@ namespace Authentication.Facebook/// Represents settings of the Facebook authentication mehod/// </summary>public class FacebookExternalAuthSettings : ISettings- {- /// <summary>- /// Gets or sets OAuth2 client identifier- /// </summary>- public string ClientKeyIdentifier { get; set; }-- /// <summary>- /// Gets or sets OAuth2 client secret- /// </summary>- public string ClientSecret { get; set; }-+ {/// <summary>/// Gets or sets display order/// </summary>diff --git a/src/Plugins/Authentication.Facebook/Infrastructure/FacebookAuthenticationBuilder.cs b/src/Plugins/Authentication.Facebook/Infrastructure/FacebookAuthenticationBuilder.csindex be7357e5b..ba78beb21 100644--- a/src/Plugins/Authentication.Facebook/Infrastructure/FacebookAuthenticationBuilder.cs+++ b/src/Plugins/Authentication.Facebook/Infrastructure/FacebookAuthenticationBuilder.cs@@ -1,15 +1,10 @@using Grand.Business.Authentication.Interfaces;-using Grand.Domain.Configuration;-using Grand.Domain.Data;-using Grand.Domain.Data.Mongo;using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Authentication.Facebook;using Microsoft.AspNetCore.Authentication.OAuth;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-using Serilog;using System.Net;-using System.Text.Json;namespace Authentication.Facebook.Infrastructure{@@ -26,23 +21,12 @@ namespace Authentication.Facebook.Infrastructure{builder.AddFacebook(FacebookDefaults.AuthenticationScheme, options =>{- var connection = DataSettingsManager.LoadSettings();-- var settings = new FacebookExternalAuthSettings();- try- {- var fbSettings = new MongoRepository<Setting>(connection.ConnectionString).Table.Where(x => x.Name.StartsWith("facebookexternalauthsettings"));- if (fbSettings.Any())- {- var metadata = fbSettings.FirstOrDefault().Metadata;- settings = JsonSerializer.Deserialize<FacebookExternalAuthSettings>(metadata);- }- }- catch (Exception ex) { Log.Error(ex, "AddFacebook"); };+ var appId = configuration["FacebookSettings:AppId"];+ var appSecret = configuration["FacebookSettings:AppSecret"];//no empty values allowed. otherwise, an exception could be thrown on application startup- options.AppId = !string.IsNullOrWhiteSpace(settings.ClientKeyIdentifier) ? settings.ClientKeyIdentifier : "000";- options.AppSecret = !string.IsNullOrWhiteSpace(settings.ClientSecret) ? settings.ClientSecret : "000";+ options.AppId = !string.IsNullOrWhiteSpace(appId) ? appId : "000";+ options.AppSecret = !string.IsNullOrWhiteSpace(appSecret) ? appSecret : "000";options.SaveTokens = true;//handles exception thrown by external auth provideroptions.Events = new OAuthEvents() {diff --git a/src/Plugins/Authentication.Google/Areas/Admin/Controllers/GoogleAuthenticationSettingsController.cs b/src/Plugins/Authentication.Google/Areas/Admin/Controllers/GoogleAuthenticationSettingsController.csindex 858255523..53d079cfa 100644--- a/src/Plugins/Authentication.Google/Areas/Admin/Controllers/GoogleAuthenticationSettingsController.cs+++ b/src/Plugins/Authentication.Google/Areas/Admin/Controllers/GoogleAuthenticationSettingsController.cs@@ -7,6 +7,7 @@ using Grand.Web.Common.Controllers;using Grand.Web.Common.Filters;using Grand.Web.Common.Security.Authorization;using Microsoft.AspNetCore.Mvc;+using Microsoft.Extensions.Configuration;namespace Authentication.Google.Controllers{@@ -21,6 +22,7 @@ namespace Authentication.Google.Controllersprivate readonly ITranslationService _translationService;private readonly IPermissionService _permissionService;private readonly ISettingService _settingService;+ private readonly IConfiguration _configuration;#endregion@@ -30,12 +32,14 @@ namespace Authentication.Google.ControllersGoogleExternalAuthSettings googleExternalAuthSettings,ITranslationService translationService,IPermissionService permissionService,- ISettingService settingService)+ ISettingService settingService,+ IConfiguration configuration){_googleExternalAuthSettings = googleExternalAuthSettings;_translationService = translationService;_permissionService = permissionService;_settingService = settingService;+ _configuration = configuration;}#endregion@@ -49,8 +53,8 @@ namespace Authentication.Google.Controllersreturn AccessDeniedView();var model = new ConfigurationModel {- ClientKeyIdentifier = _googleExternalAuthSettings.ClientKeyIdentifier,- ClientSecret = _googleExternalAuthSettings.ClientSecret,+ ClientKeyIdentifier = _configuration["GoogleSettings:ClientId"],+ ClientSecret = _configuration["GoogleSettings:ClientSecret"],DisplayOrder = _googleExternalAuthSettings.DisplayOrder};@@ -66,8 +70,6 @@ namespace Authentication.Google.Controllersif (!ModelState.IsValid)return await Configure();- _googleExternalAuthSettings.ClientKeyIdentifier = model.ClientKeyIdentifier;- _googleExternalAuthSettings.ClientSecret = model.ClientSecret;_googleExternalAuthSettings.DisplayOrder = model.DisplayOrder;await _settingService.SaveSetting(_googleExternalAuthSettings);diff --git a/src/Plugins/Authentication.Google/Areas/Admin/Views/GoogleAuthenticationSettings/Configure.cshtml b/src/Plugins/Authentication.Google/Areas/Admin/Views/GoogleAuthenticationSettings/Configure.cshtmlindex d5779f7d7..873ff6e1a 100644--- a/src/Plugins/Authentication.Google/Areas/Admin/Views/GoogleAuthenticationSettings/Configure.cshtml+++ b/src/Plugins/Authentication.Google/Areas/Admin/Views/GoogleAuthenticationSettings/Configure.cshtml@@ -13,12 +13,18 @@</div><div class="panel-body">@Html.Raw(Loc["Plugins.ExternalAuth.Google.Description"])+ <p>+ <br /><br />+ To edit google settings in the grandnode application, please open the file App_Settings.json,+ find section GoogleSettings and enter the correct values.+ </p><div class="form-group"><div class="col-md-3 col-sm-3 text-right"><admin-label asp-for="ClientKeyIdentifier" class="control-label" /></div><div class="col-md-9 col-sm-9">- <admin-input asp-for="ClientKeyIdentifier" />+ <input asp-for=ClientKeyIdentifier type="text"+ disabled class="form-control k-input text-box single-line" /><span asp-validation-for="ClientKeyIdentifier"></span></div></div>@@ -27,7 +33,7 @@<admin-label asp-for="ClientSecret" class="control-label" /></div><div class="col-md-9 col-sm-9">- <admin-input asp-for="ClientSecret" />+ <input asp-for=ClientSecret type="text" disabled class="form-control k-input text-box single-line" /><span asp-validation-for="ClientSecret"></span></div></div>diff --git a/src/Plugins/Authentication.Google/Controllers/GoogleAuthenticationController.cs b/src/Plugins/Authentication.Google/Controllers/GoogleAuthenticationController.csindex e6f516dad..51820dc5d 100644--- a/src/Plugins/Authentication.Google/Controllers/GoogleAuthenticationController.cs+++ b/src/Plugins/Authentication.Google/Controllers/GoogleAuthenticationController.cs@@ -6,6 +6,7 @@ using Grand.Web.Common.Controllers;using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Authentication.Google;using Microsoft.AspNetCore.Mvc;+using Microsoft.Extensions.Configuration;using System.Security.Claims;namespace Authentication.Google.Controllers@@ -15,16 +16,17 @@ namespace Authentication.Google.Controllers#region Fieldsprivate readonly IExternalAuthenticationService _externalAuthenticationService;- private readonly GoogleExternalAuthSettings _googleExternalAuthSettings;+ private readonly IConfiguration _configuration;+#endregion#region Ctorpublic GoogleAuthenticationController(IExternalAuthenticationService externalAuthenticationService,- GoogleExternalAuthSettings googleExternalAuthSettings)+ IConfiguration configuration){_externalAuthenticationService = externalAuthenticationService;- _googleExternalAuthSettings = googleExternalAuthSettings;+ _configuration = configuration;}#endregion@@ -36,7 +38,7 @@ namespace Authentication.Google.Controllersif (!_externalAuthenticationService.AuthenticationProviderIsAvailable(GoogleAuthenticationDefaults.ProviderSystemName))throw new GrandException("Google authentication module cannot be loaded");- if (string.IsNullOrEmpty(_googleExternalAuthSettings.ClientKeyIdentifier) || string.IsNullOrEmpty(_googleExternalAuthSettings.ClientSecret))+ if (string.IsNullOrEmpty(_configuration["GoogleSettings:ClientId"]) || string.IsNullOrEmpty(_configuration["GoogleSettings:ClientSecret"]))throw new GrandException("Google authentication module not configured");//configure login callback actiondiff --git a/src/Plugins/Authentication.Google/GoogleAuthenticationPlugin.cs b/src/Plugins/Authentication.Google/GoogleAuthenticationPlugin.csindex 4434fdbee..d89f74f8c 100644--- a/src/Plugins/Authentication.Google/GoogleAuthenticationPlugin.cs+++ b/src/Plugins/Authentication.Google/GoogleAuthenticationPlugin.cs@@ -51,9 +51,7 @@ namespace Authentication.Googleawait this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.Description", "<h4>Google Developers Console</h4><ul><li>Go to the <a href=\"https://console.developers.google.com/\" target=\"_blank\">Google Developers Console</a> and log in with your Google Developer Account</li><li>Select \"Create Project\"</li><li>Go to APIs & Auth -> Credentials in the left-hand navigation panel</li><li>Select \"Create new Client ID\" in the OAuth Panel</li><li>In the creation panel:<ul><li>Select \"Web application\" as Application Type</li><li>Set \"Authorized JavaScript origins\" to the URL of your store (http://www.yourStore.com)</li><li>Set \"Authorized redirect URI\" to URL of login callback (http://www.yourStore.com/signin-google)</li></ul></li><li>Then go to APIs & Auth -> Consent Screen and fill out</li><li>Now get your API key (Client ID and Client Secret) and configure your store</li><li>Please remember to restart the application after changes.</li></ul><p>For more details, read the Google docs: <a href=\"https://developers.google.com/accounts/docs/OAuth2\">Using OAuth 2.0 to Access Google APIs</a>.</p>");await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.Login", "Login using Google account");await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.ClientKeyIdentifier", "Client ID");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.ClientKeyIdentifier.Hint", "Enter your Client ID key here. You can find it on Google Developers console page.");await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.ClientSecret", "Client Secret");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.ClientSecret.Hint", "Enter your client secret here. You can find it on your Google Developers console page.");await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.Title", "<h4>Configuring Google OAuth2</h4>");await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Externalauth.Google.Failed", "Failed authentication");await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Externalauth.Google.Failed.Errormessage", "Error message: ");@@ -74,9 +72,7 @@ namespace Authentication.Googleawait this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.Description");await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.Login");await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.ClientKeyIdentifier");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.ClientKeyIdentifier.Hint");await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.ClientSecret");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.ClientSecret.Hint");await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.Title");await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.ExternalAuth.Google.DisplayOrder");await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Externalauth.Google.Failed");diff --git a/src/Plugins/Authentication.Google/GoogleExternalAuthSettings.cs b/src/Plugins/Authentication.Google/GoogleExternalAuthSettings.csindex 86271cfa3..eaa80f682 100644--- a/src/Plugins/Authentication.Google/GoogleExternalAuthSettings.cs+++ b/src/Plugins/Authentication.Google/GoogleExternalAuthSettings.cs@@ -3,9 +3,7 @@namespace Authentication.Google{public class GoogleExternalAuthSettings : ISettings- {- public string ClientKeyIdentifier { get; set; }- public string ClientSecret { get; set; }+ {public int DisplayOrder { get; set; }}}diff --git a/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationBuilder.cs b/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationBuilder.csindex 40b1703f7..5a214c355 100644--- a/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationBuilder.cs+++ b/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationBuilder.cs@@ -26,22 +26,11 @@ namespace Authentication.Google.Infrastructure{builder.AddGoogle(GoogleDefaults.AuthenticationScheme, options =>{- var connection = DataSettingsManager.LoadSettings();+ var clientId = configuration["GoogleSettings:ClientId"];+ var clientSecret = configuration["GoogleSettings:ClientSecret"];- var settings = new GoogleExternalAuthSettings();- try- {- var gSettings = new MongoRepository<Setting>(connection.ConnectionString).Table.Where(x => x.Name.StartsWith("googleexternalauthsettings"));- if (gSettings.Any())- {- var metadata = gSettings.FirstOrDefault().Metadata;- settings = JsonSerializer.Deserialize<GoogleExternalAuthSettings>(metadata);- }- }- catch (Exception ex) { Log.Error(ex, "AddGoogle"); };-- options.ClientId = !string.IsNullOrWhiteSpace(settings.ClientKeyIdentifier) ? settings.ClientKeyIdentifier : "000";- options.ClientSecret = !string.IsNullOrWhiteSpace(settings.ClientSecret) ? settings.ClientSecret : "000";+ options.ClientId = !string.IsNullOrWhiteSpace(clientId) ? clientId : "000";+ options.ClientSecret = !string.IsNullOrWhiteSpace(clientSecret) ? clientSecret : "000";options.SaveTokens = true;//handles exception thrown by external auth providerdiff --git a/src/Plugins/Authentication.Google/Manifest.cs b/src/Plugins/Authentication.Google/Manifest.csindex d7909d726..93989bad8 100644--- a/src/Plugins/Authentication.Google/Manifest.cs+++ b/src/Plugins/Authentication.Google/Manifest.cs@@ -8,5 +8,5 @@ using Grand.Infrastructure.Plugins;SystemName = GoogleAuthenticationDefaults.ProviderSystemName,SupportedVersion = GrandVersion.SupportedPluginVersion,Author = "grandnode team",- Version = "1.00"+ Version = "1.01")]\ No newline at end of filediff --git a/src/Plugins/Widgets.Slider/Services/SliderService.cs b/src/Plugins/Widgets.Slider/Services/SliderService.csindex 959efcd52..11d15257d 100644--- a/src/Plugins/Widgets.Slider/Services/SliderService.cs+++ b/src/Plugins/Widgets.Slider/Services/SliderService.cs@@ -90,7 +90,7 @@ namespace Widgets.Slider.Services/// <returns>Tax rate</returns>public virtual Task<PictureSlider> GetById(string slideId){- return _reporistoryPictureSlider.FirstOrDefaultAsync(x => x.Id == slideId);+ return _reporistoryPictureSlider.GetByIdAsync(slideId);}/// <summary>diff --git a/src/Tests/Grand.Data.Tests/Grand.Data.Tests.csproj b/src/Tests/Grand.Data.Tests/Grand.Data.Tests.csprojnew file mode 100644index 000000000..e7ffdd0fb--- /dev/null+++ b/src/Tests/Grand.Data.Tests/Grand.Data.Tests.csproj@@ -0,0 +1,24 @@+<Project Sdk="Microsoft.NET.Sdk">+ <Import Project="..\..\Build\Grand.Common.props" />+ <PropertyGroup>+ <IsPackable>false</IsPackable>+ </PropertyGroup>++ <ItemGroup>+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />+ <PackageReference Include="Moq" Version="4.16.1" />+ <PackageReference Include="MSTest.TestAdapter" Version="2.2.8" />+ <PackageReference Include="MSTest.TestFramework" Version="2.2.8" />+ <PackageReference Include="coverlet.collector" Version="3.1.2">+ <PrivateAssets>all</PrivateAssets>+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>+ </PackageReference>+ <PackageReference Include="NUnit" Version="3.13.2" />+ </ItemGroup>++ <ItemGroup>+ <ProjectReference Include="..\..\Core\Grand.Domain\Grand.Domain.csproj" />+ <ProjectReference Include="..\..\Core\Grand.SharedKernel\Grand.SharedKernel.csproj" />+ </ItemGroup>++</Project>diff --git a/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryMock.cs b/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryMock.csnew file mode 100644index 000000000..41a126a8b--- /dev/null+++ b/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryMock.cs@@ -0,0 +1,17 @@+using Grand.Domain;+using Grand.Domain.Data;+using Grand.Domain.Data.LiteDb;+using LiteDB;++namespace Grand.Data.Tests.LiteDb+{+ public partial class MongoDBRepositoryMock<T> : LiteDBRepository<T>, IRepository<T> where T : BaseEntity+ {+ public MongoDBRepositoryMock(): base("MemoryStream")+ {+ _database = new LiteDatabase(new MemoryStream());+ _database.DropCollection(typeof(T).Name);+ _collection = _database.GetCollection<T>(typeof(T).Name);+ }+ }+}diff --git a/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryTests.cs b/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryTests.csnew file mode 100644index 000000000..ecbb2b18a--- /dev/null+++ b/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryTests.cs@@ -0,0 +1,455 @@+using Grand.Domain.Data;+using Grand.SharedKernel.Extensions;+using Microsoft.VisualStudio.TestTools.UnitTesting;++namespace Grand.Data.Tests.LiteDb+{+ [TestClass()]+ public class LiteDbRepositoryTests+ {+ private IRepository<SampleCollection> _myRepository;++ [TestInitialize()]+ public void Init()+ {+ _myRepository = new MongoDBRepositoryMock<SampleCollection>();++ CommonPath.BaseDirectory = "";+ }++ [TestMethod()]+ public void Insert_MongoRepository_Success()+ {+ var product = new SampleCollection();+ _myRepository.Insert(product);++ Assert.AreEqual(1, _myRepository.Table.Count());+ }++ [TestMethod()]+ public async Task InsertAsync_MongoRepository_Success()+ {+ var product = new SampleCollection();+ await _myRepository.InsertAsync(product);++ Assert.AreEqual(1, _myRepository.Table.Count());+ }+ [TestMethod()]+ public async Task InsertManyAsync_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1" },+ new SampleCollection(){ Id = "2" },+ new SampleCollection(){ Id = "3" },++ };+ await _myRepository.InsertManyAsync(products);++ Assert.IsTrue(_myRepository.Table.Count() == 3);+ }+ [TestMethod()]+ public async Task GetById_MongoRepository_Success()+ {+ var product = new SampleCollection() { Id = "1" };+ await _myRepository.InsertAsync(product);++ var p = _myRepository.GetById("1");++ Assert.IsNotNull(p);+ }++ [TestMethod()]+ public async Task GetByIdAsync_MongoRepository_Success()+ {+ var product = new SampleCollection() { Id = "1" };+ await _myRepository.InsertAsync(product);++ var p = await _myRepository.GetByIdAsync("1");++ Assert.IsNotNull(p);+ }++ [TestMethod()]+ public async Task ClearAsync_MongoRepository_Success()+ {+ var product = new SampleCollection() { Id = "1" };+ await _myRepository.InsertAsync(product);++ await _myRepository.ClearAsync();++ Assert.IsTrue(_myRepository.Table.Count() == 0);+ }++ [TestMethod()]+ public async Task AddToSet_MongoRepository_Success()+ {+ var product = new SampleCollection() { Id = "1" };+ await _myRepository.InsertAsync(product);++ await _myRepository.AddToSet("1", x => x.UserFields,+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" });++ await _myRepository.AddToSet("1", x => x.UserFields,+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" });++ var p = _myRepository.GetById("1");++ Assert.IsTrue(p.UserFields.Count == 2);+ }++ [TestMethod()]+ public async Task Delete_MongoRepository_Success()+ {+ var product = new SampleCollection() { Id = "1" };+ await _myRepository.InsertAsync(product);++ _myRepository.Delete(product);++ var p = _myRepository.GetById("1");++ Assert.IsNull(p);+ }++ [TestMethod()]+ public async Task DeleteAsync_MongoRepository_Success()+ {+ var product = new SampleCollection() { Id = "1" };+ await _myRepository.InsertAsync(product);++ await _myRepository.DeleteAsync(product);++ var p = _myRepository.GetById("1");++ Assert.IsNull(p);+ }+ [TestMethod()]+ public async Task DeleteManyAsync_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test" },+ new SampleCollection(){ Id = "2", Name = "Test" },+ new SampleCollection(){ Id = "3", Name = "Test2" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.DeleteManyAsync(x => x.Name == "Test");++ Assert.IsTrue(_myRepository.Table.Count() == 1);+ }++ [TestMethod()]+ public async Task GetAllAsync_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test" },+ new SampleCollection(){ Id = "2", Name = "Test2" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ var p = await _myRepository.GetAllAsync();++ Assert.IsTrue(p.Count() == 3);+ }+++ [TestMethod()]+ public async Task Pull_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ Phones = new [] { "Phone1", "Phone2", "Phone3" }+ },+ new SampleCollection(){ Id = "2", Name = "Test2",+ Phones = new [] { "Phone1", "Phone2", "Phone3" }+ },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.Pull("1", x => x.Phones, "Phone2");++ var p = _myRepository.GetById("1");++ Assert.IsTrue(p.Phones.Count() == 2);+ }+ [TestMethod()]+ public async Task Pull_Many_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ Phones = new [] { "Phone1", "Phone2", "Phone3" }+ },+ new SampleCollection(){ Id = "2", Name = "Test2",+ Phones = new [] { "Phone1", "Phone2", "Phone3" }+ },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.Pull(String.Empty, x => x.Phones, "Phone2");++ var p1 = _myRepository.GetById("1");+ var p2 = _myRepository.GetById("2");+ var p3 = _myRepository.GetById("3");++ Assert.IsTrue(p1.Phones.Count() == 2 && p2.Phones.Count() == 2 && p3.Phones.Count() == 0);+ }++ [TestMethod()]+ public async Task PullFilter_1_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test2" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.PullFilter("1", x => x.UserFields, x => x.Value == "value");++ var p1 = _myRepository.GetById("1");++ Assert.IsTrue(p1.UserFields.Count() == 1);+ }++ [TestMethod()]+ public async Task PullFilter_2_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test2" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.PullFilter("1", x => x.UserFields, x => x.Value, "value");++ var p1 = _myRepository.GetById("1");++ Assert.IsTrue(p1.UserFields.Count() == 1);+ }+ [TestMethod()]+ public async Task PullFilter_2_Many_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test2",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value1", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ }+ },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.PullFilter(String.Empty, x => x.UserFields, x => x.Value, "value");++ var p1 = _myRepository.GetById("1");+ var p2 = _myRepository.GetById("2");++ Assert.IsTrue(p1.UserFields.Count() == 1 && p2.UserFields.Count() == 2);+ }+++ [TestMethod()]+ public async Task Update_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test2" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ var p1_update = products.FirstOrDefault();+ p1_update.Name = "update";++ _myRepository.Update(p1_update);++ var p1 = _myRepository.GetById("1");++ Assert.IsTrue(p1.Name == "update");+ }+ [TestMethod()]+ public async Task UpdateAsync_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test2" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ var p1_update = products.FirstOrDefault();+ p1_update.Name = "update";++ await _myRepository.UpdateAsync(p1_update);++ var p1 = _myRepository.GetById("1");++ Assert.IsTrue(p1.Name == "update");+ }++ [TestMethod()]+ public async Task UpdateField_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test2" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.UpdateField("1", x => x.Name, "update");++ var p1 = _myRepository.GetById("1");++ Assert.IsTrue(p1.Name == "update");+ }++ [TestMethod()]+ public async Task UpdateManyAsync_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);+ await _myRepository.UpdateManyAsync(x => x.Name == "Test",+ UpdateBuilder<SampleCollection>.Create().Set(x => x.Name, "UpdateTest"));++ var pUpdated = _myRepository.Table.Where(x=>x.Name == "UpdateTest");++ Assert.IsTrue(pUpdated.Count() == 2);+ }++ [TestMethod()]+ public async Task UpdateOneAsync_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);+ await _myRepository.UpdateOneAsync(x => x.Name == "Test",+ UpdateBuilder<SampleCollection>.Create().Set(x => x.Name, "UpdateTest"));++ var pUpdated = _myRepository.Table.Where(x => x.Name == "UpdateTest");++ Assert.IsTrue(pUpdated.Count() == 1);+ }+ [TestMethod()]+ public async Task UpdateToSet_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.UpdateToSet("1", x => x.UserFields, z => z.Key, "key", new Domain.Common.UserField() { Key = "key", Value = "update", StoreId = "1" });++ var p = _myRepository.GetById("1");++ Assert.IsTrue(p.UserFields.FirstOrDefault(x=>x.Key=="key").Value == "update");+ }++ [TestMethod()]+ public async Task UpdateToSet_2_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.UpdateToSet("1", x => x.UserFields, z => z.Key == "key", new Domain.Common.UserField() { Key = "key", Value = "update", StoreId = "1" });++ var p = _myRepository.GetById("1");++ Assert.IsTrue(p.UserFields.FirstOrDefault(x => x.Key == "key").Value == "update");+ }+ }+}diff --git a/src/Tests/Grand.Data.Tests/MongoDb/CoreTestConfiguration.cs b/src/Tests/Grand.Data.Tests/MongoDb/CoreTestConfiguration.csnew file mode 100644index 000000000..532433942--- /dev/null+++ b/src/Tests/Grand.Data.Tests/MongoDb/CoreTestConfiguration.cs@@ -0,0 +1,307 @@+/* Copyright 2010-2015 MongoDB Inc.+*+* Licensed under the Apache License, Version 2.0 (the "License");+* you may not use this file except in compliance with the License.+* You may obtain a copy of the License at+*+* http://www.apache.org/licenses/LICENSE-2.0+*+* Unless required by applicable law or agreed to in writing, software+* distributed under the License is distributed on an "AS IS" BASIS,+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+* See the License for the specific language governing permissions and+* limitations under the License.+*/++using MongoDB.Bson;+using MongoDB.Bson.Serialization.Serializers;+using MongoDB.Driver;+using MongoDB.Driver.Core.Bindings;+using MongoDB.Driver.Core.Clusters;+using MongoDB.Driver.Core.Clusters.ServerSelectors;+using MongoDB.Driver.Core.Configuration;+using MongoDB.Driver.Core.Misc;+using MongoDB.Driver.Core.Operations;+using MongoDB.Driver.Core.Servers;+using MongoDB.Driver.Core.WireProtocol.Messages.Encoders;+using NUnit.Framework;+using System;+using System.Collections.Generic;+using System.Diagnostics;+using System.Linq;+using System.Reflection;+using System.Security.Cryptography.X509Certificates;+using System.Threading;+++namespace Grand.Data.Tests.MongoDb+{+ public static class CoreTestConfiguration+ {+ #region static+ // static fields+ private static Lazy<ICluster> __cluster = new Lazy<ICluster>(CreateCluster, isThreadSafe: true);+ private static ConnectionString __connectionString = GetConnectionString();+ private static DatabaseNamespace __databaseNamespace = GetDatabaseNamespace();+ private static MessageEncoderSettings __messageEncoderSettings = new MessageEncoderSettings();+ private static TraceSource __traceSource;++ // static properties+ public static ICluster Cluster {+ get { return __cluster.Value; }+ }++ public static ConnectionString ConnectionString {+ get { return __connectionString; }+ }++ public static DatabaseNamespace DatabaseNamespace {+ get { return __databaseNamespace; }+ }++ public static MessageEncoderSettings MessageEncoderSettings {+ get { return __messageEncoderSettings; }+ }++ public static SemanticVersion ServerVersion {+ get {+ var server = __cluster.Value.SelectServer(WritableServerSelector.Instance, CancellationToken.None);+ return server.Description.Version;+ }+ }++ public static TraceSource TraceSource {+ get { return __traceSource; }+ }++ // static methods+ public static ClusterBuilder ConfigureCluster()+ {+ return ConfigureCluster(new ClusterBuilder());+ }++ public static ClusterBuilder ConfigureCluster(ClusterBuilder builder)+ {+ var serverSelectionTimeoutString = Environment.GetEnvironmentVariable("MONGO_SERVER_SELECTION_TIMEOUT_MS");+ if (serverSelectionTimeoutString == null)+ {+ serverSelectionTimeoutString = "30000";+ }++ builder = builder+ .ConfigureWithConnectionString(__connectionString)+ .ConfigureCluster(c => c.With(serverSelectionTimeout: TimeSpan.FromMilliseconds(int.Parse(serverSelectionTimeoutString))));++ if (__connectionString.Tls.HasValue && __connectionString.Tls.Value)+ {+ var certificateFilename = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_FILE");+ if (certificateFilename != null)+ {+ builder.ConfigureSsl(ssl =>+ {+ var password = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_PASS");+ X509Certificate cert;+ if (password == null)+ {+ cert = new X509Certificate2(certificateFilename);+ }+ else+ {+ cert = new X509Certificate2(certificateFilename, password);+ }+ return ssl.With(+ clientCertificates: new[] { cert });+ });+ }+ }++ return ConfigureLogging(builder);+ }++ public static ClusterBuilder ConfigureLogging(ClusterBuilder builder)+ {+ var environmentVariable = Environment.GetEnvironmentVariable("MONGO_LOGGING");+ if (environmentVariable == null)+ {+ return builder;+ }++ SourceLevels defaultLevel;+ if (!Enum.TryParse<SourceLevels>(environmentVariable, ignoreCase: true, result: out defaultLevel))+ {+ return builder;+ }++ __traceSource = new TraceSource("mongodb-tests", defaultLevel);+ __traceSource.Listeners.Clear();+ return builder.TraceWith(__traceSource);+ }++ public static ICluster CreateCluster()+ {+ var hasWritableServer = 0;+ var builder = ConfigureCluster();+ var cluster = builder.BuildCluster();+ cluster.DescriptionChanged += (o, e) =>+ {+ var anyWritableServer = e.NewClusterDescription.Servers.Any(+ description => description.Type.IsWritable());+ if (__traceSource != null)+ {+ __traceSource.TraceEvent(TraceEventType.Information, 0, $"CreateCluster: DescriptionChanged event handler called.");+ __traceSource.TraceEvent(TraceEventType.Information, 0, $"CreateCluster: anyWritableServer = {anyWritableServer}.");+ __traceSource.TraceEvent(TraceEventType.Information, 0, $"CreateCluster: new description: {e.NewClusterDescription.ToString()}.");+ }+ Interlocked.Exchange(ref hasWritableServer, anyWritableServer ? 1 : 0);+ };+ if (__traceSource != null)+ {+ __traceSource.TraceEvent(TraceEventType.Information, 0, "CreateCluster: initializing cluster.");+ }+ cluster.Initialize();++ // wait until the cluster has connected to a writable server+ SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref hasWritableServer, 0, 0) != 0, TimeSpan.FromSeconds(30));+ if (Interlocked.CompareExchange(ref hasWritableServer, 0, 0) == 0)+ {+ var message = string.Format(+ "Test cluster has no writable server. Client view of the cluster is {0}.",+ cluster.Description.ToString());+ throw new Exception(message);+ }++ if (__traceSource != null)+ {+ __traceSource.TraceEvent(TraceEventType.Information, 0, "CreateCluster: writable server found.");+ }++ return cluster;+ }++ public static CollectionNamespace GetCollectionNamespaceForTestFixture()+ {+ var testFixtureType = GetTestFixtureTypeFromCallStack();+ var collectionName = TruncateCollectionNameIfTooLong(__databaseNamespace, testFixtureType.Name);+ return new CollectionNamespace(__databaseNamespace, collectionName);+ }++ public static CollectionNamespace GetCollectionNamespaceForTestMethod()+ {+ var testMethodInfo = GetTestMethodInfoFromCallStack();+ var collectionName = TruncateCollectionNameIfTooLong(__databaseNamespace, testMethodInfo.DeclaringType.Name + "-" + testMethodInfo.Name);+ return new CollectionNamespace(__databaseNamespace, collectionName);+ }++ private static ConnectionString GetConnectionString()+ {+ return new ConnectionString(Environment.GetEnvironmentVariable("MONGO_URI") ?? "mongodb://localhost");+ }++ private static DatabaseNamespace GetDatabaseNamespace()+ {+ if (!string.IsNullOrEmpty(__connectionString.DatabaseName))+ {+ return new DatabaseNamespace(__connectionString.DatabaseName);+ }++ var timestamp = DateTime.Now.ToString("MMddHHmm");+ return new DatabaseNamespace("Tests" + timestamp);+ }++ public static DatabaseNamespace GetDatabaseNamespaceForTestFixture()+ {+ var testFixtureType = GetTestFixtureTypeFromCallStack();+ var databaseName = TruncateDatabaseNameIfTooLong(__databaseNamespace.DatabaseName + "-" + testFixtureType.Name);+ if (databaseName.Length >= 64)+ {+ databaseName = databaseName.Substring(0, 63);+ }+ return new DatabaseNamespace(databaseName);+ }+++++ private static Type GetTestFixtureTypeFromCallStack()+ {+ var stackTrace = new StackTrace();+ for (var index = 0; index < stackTrace.FrameCount; index++)+ {+ var frame = stackTrace.GetFrame(index);+ var methodInfo = frame.GetMethod();+ var declaringType = methodInfo.DeclaringType;+ var testFixtureAttribute = declaringType.GetCustomAttribute<TestFixtureAttribute>(inherit: false);+ if (testFixtureAttribute != null)+ {+ return declaringType;+ }+ }++ throw new Exception("No [TestFixture] found on the call stack.");+ }++ private static MethodInfo GetTestMethodInfoFromCallStack()+ {+ var stackTrace = new StackTrace();+ for (var index = 0; index < stackTrace.FrameCount; index++)+ {+ var frame = stackTrace.GetFrame(index);+ var methodInfo = frame.GetMethod() as MethodInfo;+ if (methodInfo != null)+ {+ var testAttribute = methodInfo.GetCustomAttribute<TestAttribute>(inherit: false);+ if (testAttribute != null)+ {+ return methodInfo;+ }+ var testCaseAttribute = methodInfo.GetCustomAttribute<TestCaseAttribute>(inherit: false);+ if (testCaseAttribute != null)+ {+ return methodInfo;+ }+ }+ }++ throw new Exception("No [TestFixture] found on the call stack.");+ }++ private static string TruncateCollectionNameIfTooLong(DatabaseNamespace databaseNamespace, string collectionName)+ {+ var fullNameLength = databaseNamespace.DatabaseName.Length + 1 + collectionName.Length;+ if (fullNameLength < 123)+ {+ return collectionName;+ }+ else+ {+ var maxCollectionNameLength = 123 - (databaseNamespace.DatabaseName.Length + 1);+ return collectionName.Substring(0, maxCollectionNameLength);+ }+ }++ private static string TruncateDatabaseNameIfTooLong(string databaseName)+ {+ if (databaseName.Length < 64)+ {+ return databaseName;+ }+ else+ {+ return databaseName.Substring(0, 63);+ }+ }+ #endregion+++ public static void TearDown()+ {+ if (__cluster.IsValueCreated)+ {+ // TODO: DropDatabase+ //DropDatabase();+ __cluster.Value.Dispose();+ __cluster = new Lazy<ICluster>(CreateCluster, isThreadSafe: true);+ }+ }+ }+}diff --git a/src/Tests/Grand.Data.Tests/MongoDb/DriverTestConfiguration.cs b/src/Tests/Grand.Data.Tests/MongoDb/DriverTestConfiguration.csnew file mode 100644index 000000000..01e542cef--- /dev/null+++ b/src/Tests/Grand.Data.Tests/MongoDb/DriverTestConfiguration.cs@@ -0,0 +1,64 @@++using MongoDB.Driver;+using System;++namespace Grand.Data.Tests.MongoDb+{+ /// <summary>+ /// A static class to handle online test configuration.+ /// </summary>+ public static class DriverTestConfiguration+ {+ // private static fields+ private static Lazy<MongoClient> __client;+ private static CollectionNamespace __collectionNamespace;+ private static DatabaseNamespace __databaseNamespace;++ // static constructor+ static DriverTestConfiguration()+ {+ var connectionString = CoreTestConfiguration.ConnectionString.ToString();+ var clientSettings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));++ var serverSelectionTimeoutString = Environment.GetEnvironmentVariable("MONGO_SERVER_SELECTION_TIMEOUT_MS");+ if (serverSelectionTimeoutString == null)+ {+ serverSelectionTimeoutString = "30000";+ }+ clientSettings.ServerSelectionTimeout = TimeSpan.FromMilliseconds(int.Parse(serverSelectionTimeoutString));+ clientSettings.ClusterConfigurator = cb => CoreTestConfiguration.ConfigureLogging(cb);++ __client = new Lazy<MongoClient>(() => new MongoClient(clientSettings), true);+ __databaseNamespace = CoreTestConfiguration.DatabaseNamespace;+ __collectionNamespace = new CollectionNamespace(__databaseNamespace, "testcollection");+ }++ // public static properties+ /// <summary>+ /// Gets the test client.+ /// </summary>+ public static MongoClient Client {+ get { return __client.Value; }+ }++ /// <summary>+ /// Gets the collection namespace.+ /// </summary>+ /// <value>+ /// The collection namespace.+ /// </value>+ public static CollectionNamespace CollectionNamespace {+ get { return __collectionNamespace; }+ }++ /// <summary>+ /// Gets the database namespace.+ /// </summary>+ /// <value>+ /// The database namespace.+ /// </value>+ public static DatabaseNamespace DatabaseNamespace {+ get { return __databaseNamespace; }+ }+ }+}diff --git a/src/Tests/Grand.Data.Tests/MongoDb/MongoDBRepositoryTest.cs b/src/Tests/Grand.Data.Tests/MongoDb/MongoDBRepositoryTest.csnew file mode 100644index 000000000..300a84102--- /dev/null+++ b/src/Tests/Grand.Data.Tests/MongoDb/MongoDBRepositoryTest.cs@@ -0,0 +1,17 @@+using Grand.Domain;+using Grand.Domain.Data;+using Grand.Domain.Data.Mongo;++namespace Grand.Data.Tests.MongoDb+{+ public partial class MongoDBRepositoryTest<T> : MongoRepository<T>, IRepository<T> where T : BaseEntity+ {+ public MongoDBRepositoryTest():base(DriverTestConfiguration.Client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName))+ {+ var client = DriverTestConfiguration.Client;+ _database = client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName);+ _database.DropCollection(typeof(T).Name);+ _collection = _database.GetCollection<T>(typeof(T).Name);+ }+ }+}diff --git a/src/Tests/Grand.Data.Tests/MongoDb/MongoRepositoryTests.cs b/src/Tests/Grand.Data.Tests/MongoDb/MongoRepositoryTests.csnew file mode 100644index 000000000..b5b56dbf9--- /dev/null+++ b/src/Tests/Grand.Data.Tests/MongoDb/MongoRepositoryTests.cs@@ -0,0 +1,431 @@+using Grand.Domain.Data;+using Grand.SharedKernel.Extensions;+using Microsoft.VisualStudio.TestTools.UnitTesting;++namespace Grand.Data.Tests.MongoDb+{+ [TestClass()]+ public class MongoRepositoryTests+ {+ private IRepository<SampleCollection> _myRepository;++ [TestInitialize()]+ public void Init()+ {+ _myRepository = new MongoDBRepositoryTest<SampleCollection>();++ CommonPath.BaseDirectory = "";+ }++ [TestMethod()]+ public void Insert_MongoRepository_Success()+ {+ var product = new SampleCollection();+ _myRepository.Insert(product);++ Assert.AreEqual(1, _myRepository.Table.Count());+ }++ [TestMethod()]+ public async Task InsertAsync_MongoRepository_Success()+ {+ var product = new SampleCollection();+ await _myRepository.InsertAsync(product);++ Assert.AreEqual(1, _myRepository.Table.Count());+ }+ [TestMethod()]+ public async Task InsertManyAsync_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1" },+ new SampleCollection(){ Id = "2" },+ new SampleCollection(){ Id = "3" },++ };+ await _myRepository.InsertManyAsync(products);++ Assert.IsTrue(_myRepository.Table.Count() == 3);+ }+ [TestMethod()]+ public async Task GetById_MongoRepository_Success()+ {+ var product = new SampleCollection() { Id = "1" };+ await _myRepository.InsertAsync(product);++ var p = _myRepository.GetById("1");++ Assert.IsNotNull(p);+ }++ [TestMethod()]+ public async Task GetByIdAsync_MongoRepository_Success()+ {+ var product = new SampleCollection() { Id = "1" };+ await _myRepository.InsertAsync(product);++ var p = await _myRepository.GetByIdAsync("1");++ Assert.IsNotNull(p);+ }++ [TestMethod()]+ public async Task ClearAsync_MongoRepository_Success()+ {+ var product = new SampleCollection() { Id = "1" };+ await _myRepository.InsertAsync(product);++ await _myRepository.ClearAsync();++ Assert.IsTrue(_myRepository.Table.Count() == 0);+ }++ [TestMethod()]+ public async Task AddToSet_MongoRepository_Success()+ {+ var product = new SampleCollection() { Id = "1" };+ await _myRepository.InsertAsync(product);++ await _myRepository.AddToSet("1", x => x.UserFields,+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" });++ await _myRepository.AddToSet("1", x => x.UserFields,+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" });++ var p = _myRepository.GetById("1");++ Assert.IsTrue(p.UserFields.Count == 2);+ }++ [TestMethod()]+ public async Task Delete_MongoRepository_Success()+ {+ var product = new SampleCollection() { Id = "1" };+ await _myRepository.InsertAsync(product);++ _myRepository.Delete(product);++ var p = _myRepository.GetById("1");++ Assert.IsNull(p);+ }++ [TestMethod()]+ public async Task DeleteAsync_MongoRepository_Success()+ {+ var product = new SampleCollection() { Id = "1" };+ await _myRepository.InsertAsync(product);++ await _myRepository.DeleteAsync(product);++ var p = _myRepository.GetById("1");++ Assert.IsNull(p);+ }+ [TestMethod()]+ public async Task DeleteManyAsync_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test" },+ new SampleCollection(){ Id = "2", Name = "Test" },+ new SampleCollection(){ Id = "3", Name = "Test2" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.DeleteManyAsync(x => x.Name == "Test");++ Assert.IsTrue(_myRepository.Table.Count() == 1);+ }++ [TestMethod()]+ public async Task GetAllAsync_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test" },+ new SampleCollection(){ Id = "2", Name = "Test2" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ var p = await _myRepository.GetAllAsync();++ Assert.IsTrue(p.Count() == 3);+ }+++ [TestMethod()]+ public async Task Pull_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ Phones = new [] { "Phone1", "Phone2", "Phone3" }+ },+ new SampleCollection(){ Id = "2", Name = "Test2",+ Phones = new [] { "Phone1", "Phone2", "Phone3" }+ },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.Pull("1", x => x.Phones, "Phone2");++ var p = _myRepository.GetById("1");++ Assert.IsTrue(p.Phones.Count() == 2);+ }+ [TestMethod()]+ public async Task Pull_Many_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ Phones = new [] { "Phone1", "Phone2", "Phone3" }+ },+ new SampleCollection(){ Id = "2", Name = "Test2",+ Phones = new [] { "Phone1", "Phone2", "Phone3" }+ },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.Pull(String.Empty, x => x.Phones, "Phone2");++ var p1 = _myRepository.GetById("1");+ var p2 = _myRepository.GetById("2");+ var p3 = _myRepository.GetById("3");++ Assert.IsTrue(p1.Phones.Count() == 2 && p2.Phones.Count() == 2 && p3.Phones.Count() == 0);+ }++ [TestMethod()]+ public async Task PullFilter_1_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test2" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.PullFilter("1", x => x.UserFields, x => x.Value == "value");++ var p1 = _myRepository.GetById("1");++ Assert.IsTrue(p1.UserFields.Count() == 1);+ }++ [TestMethod()]+ public async Task PullFilter_2_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test2" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.PullFilter("1", x => x.UserFields, x => x.Value, "value");++ var p1 = _myRepository.GetById("1");++ Assert.IsTrue(p1.UserFields.Count() == 1);+ }+ [TestMethod()]+ public async Task PullFilter_2_Many_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test2",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value1", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ }+ },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.PullFilter(String.Empty, x => x.UserFields, x => x.Value, "value");++ var p1 = _myRepository.GetById("1");+ var p2 = _myRepository.GetById("2");++ Assert.IsTrue(p1.UserFields.Count() == 1 && p2.UserFields.Count() == 2);+ }+++ [TestMethod()]+ public async Task Update_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test2" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ var p1_update = products.FirstOrDefault();+ p1_update.Name = "update";++ _myRepository.Update(p1_update);++ var p1 = _myRepository.GetById("1");++ Assert.IsTrue(p1.Name == "update");+ }+ [TestMethod()]+ public async Task UpdateAsync_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test2" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ var p1_update = products.FirstOrDefault();+ p1_update.Name = "update";++ await _myRepository.UpdateAsync(p1_update);++ var p1 = _myRepository.GetById("1");++ Assert.IsTrue(p1.Name == "update");+ }++ [TestMethod()]+ public async Task UpdateField_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test2" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.UpdateField("1", x => x.Name, "update");++ var p1 = _myRepository.GetById("1");++ Assert.IsTrue(p1.Name == "update");+ }++ [TestMethod()]+ public async Task UpdateManyAsync_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);+ await _myRepository.UpdateManyAsync(x => x.Name == "Test",+ UpdateBuilder<SampleCollection>.Create().Set(x => x.Name, "UpdateTest"));++ var pUpdated = _myRepository.Table.Where(x=>x.Name == "UpdateTest");++ Assert.IsTrue(pUpdated.Count() == 2);+ }++ [TestMethod()]+ public async Task UpdateOneAsync_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);+ await _myRepository.UpdateOneAsync(x => x.Name == "Test",+ UpdateBuilder<SampleCollection>.Create().Set(x => x.Name, "UpdateTest"));++ var pUpdated = _myRepository.Table.Where(x => x.Name == "UpdateTest");++ Assert.IsTrue(pUpdated.Count() == 1);+ }+ [TestMethod()]+ public async Task UpdateToSet_MongoRepository_Success()+ {+ var products = new List<SampleCollection>() {+ new SampleCollection(){ Id = "1", Name = "Test",+ UserFields = new List<Domain.Common.UserField>()+ {+ new Domain.Common.UserField() { Key = "key", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key1", Value = "value", StoreId = "" },+ new Domain.Common.UserField() { Key = "key2", Value = "value2", StoreId = "" }+ } },+ new SampleCollection(){ Id = "2", Name = "Test" },+ new SampleCollection(){ Id = "3", Name = "Test3" },++ };+ await _myRepository.InsertManyAsync(products);++ await _myRepository.UpdateToSet("1", x => x.UserFields, z => z.Key, "key", new Domain.Common.UserField() { Key = "key", Value = "update", StoreId = "1" });++ var p = _myRepository.GetById("1");++ Assert.IsTrue(p.UserFields.FirstOrDefault(x=>x.Key=="key").Value == "update");+ }+ }+}diff --git a/src/Tests/Grand.Data.Tests/SampleCollection.cs b/src/Tests/Grand.Data.Tests/SampleCollection.csnew file mode 100644index 000000000..b869c1f70--- /dev/null+++ b/src/Tests/Grand.Data.Tests/SampleCollection.cs@@ -0,0 +1,25 @@+using Grand.Domain;++namespace Grand.Data.Tests+{+ public class SampleCollection : BaseEntity+ {+ public SampleCollection()+ {+ Phones = new List<string>();+ Category = new List<SampleCategory>();+ }+ public string Name { get; set; }++ public IList<string> Phones { get; set; }++ public IList<SampleCategory> Category { get; set; }++ public class SampleCategory+ {+ public string Name { get; set; }+ public int DisplayOrder { get; set; }+ }++ }+}diff --git a/src/Web/Grand.Web.Admin/Extensions/Mapping/DateTimeMappingExtensions.cs b/src/Web/Grand.Web.Admin/Extensions/Mapping/DateTimeMappingExtensions.csindex 7901b8951..6144ced02 100644--- a/src/Web/Grand.Web.Admin/Extensions/Mapping/DateTimeMappingExtensions.cs+++ b/src/Web/Grand.Web.Admin/Extensions/Mapping/DateTimeMappingExtensions.cs@@ -7,8 +7,9 @@ namespace Grand.Web.Admin.Extensionspublic static DateTime? ConvertToUserTime(this DateTime? datetime, IDateTimeService dateTimeService){if (datetime.HasValue)- {- datetime = dateTimeService.ConvertToUserTime(datetime.Value, TimeZoneInfo.Utc, dateTimeService.CurrentTimeZone);+ {+ if(datetime.Value.Kind == DateTimeKind.Utc)+ datetime = dateTimeService.ConvertToUserTime(datetime.Value, TimeZoneInfo.Utc, dateTimeService.CurrentTimeZone);}return datetime;}@@ -17,19 +18,26 @@ namespace Grand.Web.Admin.Extensions{if (datetime.HasValue){- datetime = dateTimeService.ConvertToUtcTime(datetime.Value, dateTimeService.CurrentTimeZone);+ if (datetime.Value.Kind != DateTimeKind.Utc)+ datetime = dateTimeService.ConvertToUtcTime(datetime.Value, dateTimeService.CurrentTimeZone);}return datetime;}public static DateTime ConvertToUserTime(this DateTime datetime, IDateTimeService dateTimeService){- return dateTimeService.ConvertToUserTime(datetime, TimeZoneInfo.Utc, dateTimeService.CurrentTimeZone);+ if(datetime.Kind == DateTimeKind.Utc)+ return dateTimeService.ConvertToUserTime(datetime, TimeZoneInfo.Utc, dateTimeService.CurrentTimeZone);++ return datetime;}public static DateTime ConvertToUtcTime(this DateTime datetime, IDateTimeService dateTimeService){- return dateTimeService.ConvertToUtcTime(datetime, dateTimeService.CurrentTimeZone);+ if (datetime.Kind == DateTimeKind.Local)+ return dateTimeService.ConvertToUtcTime(datetime, dateTimeService.CurrentTimeZone);++ return datetime;}}}\ No newline at end of filediff --git a/src/Web/Grand.Web/App_Data/Resources/Installation/installation.en.xml b/src/Web/Grand.Web/App_Data/Resources/Installation/installation.en.xmlindex 4ca36ba41..dc1b2a074 100644--- a/src/Web/Grand.Web/App_Data/Resources/Installation/installation.en.xml+++ b/src/Web/Grand.Web/App_Data/Resources/Installation/installation.en.xml@@ -137,6 +137,12 @@<LocaleResource Name="MongoDBStandard"><Value>Use MongoDB Server database</Value></LocaleResource>+ <LocaleResource Name="UseLiteDbEnable">+ <Value>The installation process for LiteDB database requires enabling a setting UseLiteDb in Appsettings</Value>+ </LocaleResource>+ <LocaleResource Name="UseLiteDbDisable">+ <Value>The installation process for MongoDB database requires disabling a setting UseLiteDb in Appsettings</Value>+ </LocaleResource><LocaleResource Name="StoreInformation"><Value>Store information</Value></LocaleResource>diff --git a/src/Web/Grand.Web/App_Data/appsettings.json b/src/Web/Grand.Web/App_Data/appsettings.jsonindex 387cb1604..ba1e92c55 100644--- a/src/Web/Grand.Web/App_Data/appsettings.json+++ b/src/Web/Grand.Web/App_Data/appsettings.json@@ -153,46 +153,65 @@//(Serilog) Request logging - The package includes middleware for smarter HTTP request logging."UseSerilogRequestLogging": false},- //access to the api to web controllers- "GrandWebApi": {- "Enabled": false,- "SecretKey": "your private secret key", //at least 16 characters- "ValidateIssuer": false,- "ValidIssuer": "",- "ValidateAudience": false,- "ValidAudience": "",- "ValidateLifetime": true,- "ValidateIssuerSigningKey": true,- "ExpiryInMinutes": 1440,- "RefreshTokenExpiryInMinutes": 1440+ "FacebookSettings": {+ //Facebook-assigned App ID+ "AppId": "",+ //Facebook-assigned app secret+ "AppSecret": ""},- //api for admin- "Api": {- "Enabled": false,- "UseSwagger": false,- "SecretKey": "your private secret key", //at least 16 characters- "ValidateIssuer": false,- "ValidIssuer": "",- "ValidateAudience": false,- "ValidAudience": "",- "ValidateLifetime": true,- "ValidateIssuerSigningKey": true,- "ExpiryInMinutes": 1440,- //generate system model- "SystemModel": true+ "GoogleSettings": {+ "ClientId": "",+ "ClientSecret": ""},- "Serilog": {- "Using": [ "Serilog.Sinks.File" ]- //,- //"MinimumLevel": {- // "Default": "Warning"- // }- //,- //"WriteTo": [- // {- // "Name": "File",- // "Args": { "path": "logs/log.txt" }- // }- // ]- }-}\ No newline at end of file+ "LiteDb": {+ //This setting is required to use LiteDB database+ "UseLiteDb": false,+ //LiteDB database as a singleton service in the application+ "Singleton": true,+ //Init connection string - it's required only for the installation process!+ "LiteDbConnectionString": "Filename=App_Data/database.db"+ },++ //access to the api to web controllers+ "GrandWebApi": {+ "Enabled": false,+ "SecretKey": "your private secret key", //at least 16 characters+ "ValidateIssuer": false,+ "ValidIssuer": "",+ "ValidateAudience": false,+ "ValidAudience": "",+ "ValidateLifetime": true,+ "ValidateIssuerSigningKey": true,+ "ExpiryInMinutes": 1440,+ "RefreshTokenExpiryInMinutes": 1440+ },+ //api for admin+ "Api": {+ "Enabled": false,+ "UseSwagger": false,+ "SecretKey": "your private secret key", //at least 16 characters+ "ValidateIssuer": false,+ "ValidIssuer": "",+ "ValidateAudience": false,+ "ValidAudience": "",+ "ValidateLifetime": true,+ "ValidateIssuerSigningKey": true,+ "ExpiryInMinutes": 1440,+ //generate system model+ "SystemModel": true+ },+ "Serilog": {+ "Using": [ "Serilog.Sinks.File" ]+ //,+ //"MinimumLevel": {+ // "Default": "Warning"+ // }+ //,+ //"WriteTo": [+ // {+ // "Name": "File",+ // "Args": { "path": "logs/log.txt" }+ // }+ // ]+ }+ }\ No newline at end of filediff --git a/src/Web/Grand.Web/Controllers/InstallController.cs b/src/Web/Grand.Web/Controllers/InstallController.csindex cbdcf3845..ee16d3aa3 100644--- a/src/Web/Grand.Web/Controllers/InstallController.cs+++ b/src/Web/Grand.Web/Controllers/InstallController.cs@@ -5,6 +5,7 @@ using Grand.Business.System.Commands.Models.Security;using Grand.Business.System.Interfaces.Installation;using Grand.Domain.Data;using Grand.Infrastructure.Caching;+using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Extensions;using Grand.Infrastructure.Migrations;using Grand.Infrastructure.Plugins;@@ -27,6 +28,7 @@ namespace Grand.Web.Controllersprivate readonly IServiceProvider _serviceProvider;private readonly IHostApplicationLifetime _applicationLifetime;private readonly IMediator _mediator;+ private readonly LiteDbConfig _litedbConfig;/// <summary>/// Cookie name to language for the installation page@@ -41,12 +43,14 @@ namespace Grand.Web.ControllersICacheBase cacheBase,IHostApplicationLifetime applicationLifetime,IServiceProvider serviceProvider,- IMediator mediator)+ IMediator mediator,+ LiteDbConfig litedbConfig){_cacheBase = cacheBase;_applicationLifetime = applicationLifetime;_serviceProvider = serviceProvider;_mediator = mediator;+ _litedbConfig = litedbConfig;}#endregion@@ -135,7 +139,7 @@ namespace Grand.Web.Controllers{var connectionString = "";- if (model.ConnectionInfo)+ if (model.ConnectionInfo && model.DataProvider != DbProvider.LiteDB){if (string.IsNullOrEmpty(model.DatabaseConnectionString))ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "ConnectionStringRequired"));@@ -144,38 +148,62 @@ namespace Grand.Web.Controllers}else{- if (string.IsNullOrEmpty(model.MongoDBDatabaseName))- ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "DatabaseNameRequired"));- if (string.IsNullOrEmpty(model.MongoDBServerName))- ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "MongoDBServerNameRequired"));+ if (model.DataProvider != DbProvider.LiteDB)+ {+ if (string.IsNullOrEmpty(model.MongoDBDatabaseName))+ ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "DatabaseNameRequired"));+ if (string.IsNullOrEmpty(model.MongoDBServerName))+ ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "MongoDBServerNameRequired"));++ var userNameandPassword = "";+ if (!(string.IsNullOrEmpty(model.MongoDBUsername)))+ userNameandPassword = model.MongoDBUsername + ":" + model.MongoDBPassword + "@";++ connectionString = "mongodb://" + userNameandPassword + model.MongoDBServerName + "/" + model.MongoDBDatabaseName;+ }+ else+ {+ if (!_litedbConfig.UseLiteDb)+ ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "InfoLiteDb"));- var userNameandPassword = "";- if (!(string.IsNullOrEmpty(model.MongoDBUsername)))- userNameandPassword = model.MongoDBUsername + ":" + model.MongoDBPassword + "@";+ if (string.IsNullOrEmpty(_litedbConfig.LiteDbConnectionString))+ ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "InfoLiteDbConnectionString"));- connectionString = "mongodb://" + userNameandPassword + model.MongoDBServerName + "/" + model.MongoDBDatabaseName;+ connectionString = _litedbConfig.LiteDbConnectionString;+ }}return connectionString;}protected async Task CheckConnectionString(IInstallationLocalizedService locService, string connectionString, InstallModel model){+ if (!_litedbConfig.UseLiteDb && model.DataProvider == DbProvider.LiteDB)+ {+ ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "UseLiteDbEnable"));+ }+ if (_litedbConfig.UseLiteDb && model.DataProvider != DbProvider.LiteDB)+ {+ ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "UseLiteDbDisable"));+ }+if (ModelState.IsValid && !string.IsNullOrEmpty(connectionString)){try{- var mdb = _serviceProvider.GetRequiredService<IDatabaseContext>();- mdb.SetConnection(connectionString);- if (await mdb.DatabaseExist())- ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "AlreadyInstalled"));+ if (model.DataProvider != DbProvider.LiteDB)+ {+ var mdb = _serviceProvider.GetRequiredService<IDatabaseContext>();+ mdb.SetConnection(connectionString);+ if (await mdb.DatabaseExist())+ ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "AlreadyInstalled"));+ }}catch (Exception ex){ModelState.AddModelError("", ex.InnerException != null ? ex.InnerException.Message : ex.Message);}}- else- ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "ConnectionStringRequired"));+ else if(string.IsNullOrEmpty(connectionString)) ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "ConnectionStringRequired"));}@@ -203,7 +231,9 @@ namespace Grand.Web.ControllersConnectionString = connectionString,DbProvider = model.DataProvider};+await DataSettingsManager.SaveSettings(settings);+ DataSettingsManager.LoadSettings(reloadSettings: true);var installationService = _serviceProvider.GetRequiredService<IInstallationService>();await installationService.InstallData(diff --git a/src/Web/Grand.Web/wwwroot/assets/install/install.js b/src/Web/Grand.Web/wwwroot/assets/install/install.jsindex 0c2942070..e769cf0ef 100644--- a/src/Web/Grand.Web/wwwroot/assets/install/install.js+++ b/src/Web/Grand.Web/wwwroot/assets/install/install.js@@ -4,6 +4,10 @@document.getElementById('DBSampleData').style.display = "none";var child = document.getElementById('collation');document.getElementById('DatabaseConnectionString').appendChild(child);+ let dataProvider = document.getElementById('DataProvider');+ if (dataProvider.value == 3) {+ document.getElementById('DatabaseConnectionString').style.display = "none";+ }} else {document.getElementById('DatabaseConnectionString').style.display = "none";document.getElementById('DBSampleData').style.display = "block";@@ -13,7 +17,7 @@let dataProvider = document.getElementById('DataProvider');if (dataProvider.value != "0") {dataProvider.value = 0;- }+ }}}function DataProviderChange(provider) {@@ -22,6 +26,12 @@ function DataProviderChange(provider) {if (!elm.checked) {elm.click();}+ if (provider == 3) {+ document.getElementById('DatabaseConnectionString').style.display = "none";+ }+ else {+ document.getElementById('DatabaseConnectionString').style.display = "flex";+ }}else {var elm = document.getElementById('ConnectionInfo');