diff --git a/Nop.Plugin.Api/ApiAuthentication.cs b/Nop.Plugin.Api/ApiAuthentication.cs deleted file mode 100644 index 7194c90..0000000 --- a/Nop.Plugin.Api/ApiAuthentication.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace Nop.Plugin.Api -{ - using System.Collections.Generic; - using System.Linq; - using System.Security.Cryptography.X509Certificates; - using IdentityModel; - using Microsoft.AspNetCore.Authentication; - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.IdentityModel.Tokens; - using Nop.Plugin.Api.Helpers; - using Nop.Services.Authentication.External; - using Org.BouncyCastle.Asn1.X509.Qualified; - - public class ApiAuthentication : IExternalAuthenticationRegistrar - { - public void Configure(AuthenticationBuilder builder) - { - RsaSecurityKey signingKey = CryptoHelper.CreateRsaSecurityKey(); - - builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwt => - { - jwt.Audience = "nop_api"; - jwt.TokenValidationParameters = new TokenValidationParameters - { - ValidateActor = false, - ValidateIssuer = false, - NameClaimType = JwtClaimTypes.Name, - RoleClaimType = JwtClaimTypes.Role, - // Uncomment this if you are using an certificate to sign your tokens. - // IssuerSigningKey = new X509SecurityKey(cert), - IssuerSigningKeyResolver = (string token, SecurityToken securityToken, string kid, - TokenValidationParameters validationParameters) => - new List { signingKey } - }; - }); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/ApiMapperConfiguration.cs b/Nop.Plugin.Api/ApiMapperConfiguration.cs deleted file mode 100644 index e933ae5..0000000 --- a/Nop.Plugin.Api/ApiMapperConfiguration.cs +++ /dev/null @@ -1,202 +0,0 @@ -using AutoMapper; -using IdentityServer4.EntityFramework.Entities; -using Nop.Core.Domain.Catalog; -using Nop.Core.Domain.Common; -using Nop.Core.Domain.Customers; -using Nop.Core.Domain.Directory; -using Nop.Core.Domain.Localization; -using Nop.Core.Domain.Messages; -using Nop.Core.Domain.Orders; -using Nop.Core.Domain.Stores; -using Nop.Core.Infrastructure.Mapper; -using Nop.Plugin.Api.AutoMapper; -using Nop.Plugin.Api.Domain; -using Nop.Plugin.Api.DTOs; -using Nop.Plugin.Api.DTOs.Categories; -using Nop.Plugin.Api.DTOs.CustomerRoles; -using Nop.Plugin.Api.DTOs.Customers; -using Nop.Plugin.Api.DTOs.Languages; -using Nop.Plugin.Api.DTOs.Manufacturers; -using Nop.Plugin.Api.DTOs.OrderItems; -using Nop.Plugin.Api.DTOs.Orders; -using Nop.Plugin.Api.DTOs.ProductAttributes; -using Nop.Plugin.Api.DTOs.ProductCategoryMappings; -using Nop.Plugin.Api.DTOs.ProductManufacturerMappings; -using Nop.Plugin.Api.DTOs.Products; -using Nop.Plugin.Api.DTOs.ShoppingCarts; -using Nop.Plugin.Api.DTOs.SpecificationAttributes; -using Nop.Plugin.Api.DTOs.Stores; -using Nop.Plugin.Api.MappingExtensions; -using Nop.Plugin.Api.Models; -using System.Collections.Generic; -using System.Linq; -using System.Net; - -namespace Nop.Plugin.Api -{ - public class ApiMapperConfiguration : Profile, IOrderedMapperProfile - { - public ApiMapperConfiguration() - { - CreateMap(); - CreateMap(); - - CreateMap(); - CreateMap(); - - CreateMap(); - - CreateMap(); - - CreateMap(); - - CreateMap(); - - CreateMap(); - - CreateMap(); - - CreateClientToClientApiModelMap(); - - CreateAddressMap(); - CreateAddressDtoToEntityMap(); - CreateShoppingCartItemMap(); - - CreateCustomerToDTOMap(); - CreateCustomerToOrderCustomerDTOMap(); - CreateCustomerDTOToOrderCustomerDTOMap(); - CreateCustomerForShoppingCartItemMapFromCustomer(); - - CreateMap(); - CreateOrderEntityToOrderDtoMap(); - - CreateProductMap(); - - CreateMap(); - - CreateMap(); - - CreateMap(); - - CreateMap(); - CreateMap(); - - CreateMap(); - CreateMap(); - } - - public int Order => 0; - - private new static void CreateMap() - { - AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() - .IgnoreAllNonExisting(); - } - - private static void CreateClientToClientApiModelMap() - { - AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() - .ForMember(x => x.ClientSecret, y => y.MapFrom(src => src.ClientSecrets.FirstOrDefault().Description)) - .ForMember(x => x.RedirectUrl, y => y.MapFrom(src => src.RedirectUris.FirstOrDefault().RedirectUri)) - .ForMember(x => x.AccessTokenLifetime, y => y.MapFrom(src => src.AccessTokenLifetime)) - .ForMember(x => x.RefreshTokenLifetime, y => y.MapFrom(src => src.AbsoluteRefreshTokenLifetime)); - } - - private void CreateOrderEntityToOrderDtoMap() - { - AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() - .IgnoreAllNonExisting() - .ForMember(x => x.Id, y => y.MapFrom(src => src.Id)) - .ForMember(x => x.OrderItems, y => y.MapFrom(src => src.OrderItems.Select(x => x.ToDto()))); - } - - private void CreateAddressMap() - { - AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() - .IgnoreAllNonExisting() - .ForMember(x => x.Id, y => y.MapFrom(src => src.Id)) - .ForMember(x => x.CountryName, - y => y.MapFrom(src => src.Country.GetWithDefault(x => x, new Country()).Name)) - .ForMember(x => x.StateProvinceName, - y => y.MapFrom(src => src.StateProvince.GetWithDefault(x => x, new StateProvince()).Name)); - } - - private void CreateAddressDtoToEntityMap() - { - AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() - .IgnoreAllNonExisting() - .ForMember(x => x.Id, y => y.MapFrom(src => src.Id)); - } - - private void CreateCustomerForShoppingCartItemMapFromCustomer() - { - AutoMapperApiConfiguration.MapperConfigurationExpression - .CreateMap() - .IgnoreAllNonExisting() - .ForMember(x => x.Id, y => y.MapFrom(src => src.Id)) - .ForMember(x => x.BillingAddress, - y => y.MapFrom(src => src.BillingAddress.GetWithDefault(x => x, new Address()).ToDto())) - .ForMember(x => x.ShippingAddress, - y => y.MapFrom(src => src.ShippingAddress.GetWithDefault(x => x, new Address()).ToDto())) - .ForMember(x => x.Addresses, - y => y.MapFrom(src => - src.Addresses.GetWithDefault(x => x, new List
()).Select(address => address.ToDto()))); - } - - private void CreateCustomerToDTOMap() - { - AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() - .IgnoreAllNonExisting() - .ForMember(x => x.Id, y => y.MapFrom(src => src.Id)) - .ForMember(x => x.BillingAddress, - y => y.MapFrom(src => src.BillingAddress.GetWithDefault(x => x, new Address()).ToDto())) - .ForMember(x => x.ShippingAddress, - y => y.MapFrom(src => src.ShippingAddress.GetWithDefault(x => x, new Address()).ToDto())) - .ForMember(x => x.Addresses, - y => - y.MapFrom( - src => - src.Addresses.GetWithDefault(x => x, new List
()) - .Select(address => address.ToDto()))) - .ForMember(x => x.ShoppingCartItems, - y => - y.MapFrom( - src => - src.ShoppingCartItems.GetWithDefault(x => x, new List()) - .Select(item => item.ToDto()))) - .ForMember(x => x.RoleIds, y => y.MapFrom(src => src.CustomerRoles.Select(z => z.Id))); - } - - private void CreateCustomerToOrderCustomerDTOMap() - { - AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() - .IgnoreAllNonExisting(); - } - - private void CreateCustomerDTOToOrderCustomerDTOMap() - { - AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() - .IgnoreAllNonExisting(); - } - - private void CreateShoppingCartItemMap() - { - AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() - .IgnoreAllNonExisting() - .ForMember(x => x.CustomerDto, - y => y.MapFrom(src => - src.Customer.GetWithDefault(x => x, new Customer()).ToCustomerForShoppingCartItemDto())) - .ForMember(x => x.ProductDto, - y => y.MapFrom(src => src.Product.GetWithDefault(x => x, new Product()).ToDto())); - } - - private void CreateProductMap() - { - AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() - .IgnoreAllNonExisting() - .ForMember(x => x.FullDescription, y => y.MapFrom(src => WebUtility.HtmlEncode(src.FullDescription))) - .ForMember(x => x.Tags, - y => y.MapFrom(src => src.ProductProductTagMappings.Select(x => x.ProductTag.Name))); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/ApiPlugin.cs b/Nop.Plugin.Api/ApiPlugin.cs deleted file mode 100644 index 100dc6b..0000000 --- a/Nop.Plugin.Api/ApiPlugin.cs +++ /dev/null @@ -1,244 +0,0 @@ -namespace Nop.Plugin.Api -{ - using IdentityServer4.EntityFramework.DbContexts; - using Microsoft.EntityFrameworkCore.Infrastructure; - using Microsoft.EntityFrameworkCore.Migrations; - using Nop.Core; - using Nop.Core.Infrastructure; - using Nop.Plugin.Api.Data; - using Nop.Plugin.Api.Domain; - using Nop.Plugin.Api.Helpers; - using Nop.Services.Configuration; - using Nop.Services.Localization; - using Nop.Services.Plugins; - using Nop.Web.Framework.Menu; - - public class ApiPlugin : BasePlugin, IAdminMenuPlugin - { - //private readonly IWebConfigMangerHelper _webConfigMangerHelper; - private readonly ApiObjectContext _objectContext; - private readonly ISettingService _settingService; - private readonly IWorkContext _workContext; - private readonly IWebHelper _webHelper; - private readonly ILocalizationService _localizationService; - - public ApiPlugin(ApiObjectContext objectContext,/*IWebConfigMangerHelper webConfigMangerHelper,*/ ISettingService settingService, IWorkContext workContext, - ILocalizationService localizationService, IWebHelper webHelper -/*, IConfiguration configuration*/) - { - _objectContext = objectContext; - //_webConfigMangerHelper = webConfigMangerHelper; - _settingService = settingService; - _workContext = workContext; - _localizationService = localizationService; - _webHelper = webHelper; - //_configuration = configuration; - } - - //private readonly IConfiguration _configuration; - - public override void Install() - { - var configManagerHelper = new NopConfigManagerHelper(); - - // some of third party libaries that we use for WebHooks and Swagger use older versions - // of certain assemblies so we need to redirect them to the those that nopCommerce uses - // TODO: Upgrade 4.1. check this! - //configManagerHelper.AddBindingRedirects(); - - // required by the WebHooks support - // TODO: Upgrade 4.1. check this! - //configManagerHelper.AddConnectionString(); - - _objectContext.Install(); - - //locales - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api", "Api plugin"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Menu.ManageClients", "Manage Api Clients"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Configure", "Configure Web Api"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.GeneralSettings", "General Settings"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.EnableApi", "Enable Api"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.EnableApi.Hint", "By checking this settings you can Enable/Disable the Web Api"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.AllowRequestsFromSwagger", "Allow Requests From Swagger"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.AllowRequestsFromSwagger.Hint", "Swagger is the documentation generation tool used for the API (/Swagger). It has a client that enables it to make GET requests to the API endpoints. By enabling this option you will allow all requests from the swagger client. Do Not Enable on live site, it is only for demo sites or local testing!!!"); - - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Menu.Title","API"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Menu.Settings.Title","Settings"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Menu.Clients.Title", "Clients"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Menu.Docs.Title", "Docs"); - - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Page.Settings.Title", "Api Settings"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Page.Clients.Title", "Api Clients"); - - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Page.Clients.Create.Title", "Add a new Api client"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Page.Clients.Edit.Title", "Edit Api client"); - - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.Name", "Name"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.Name.Hint", "Name Hint"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.ClientId", "Client Id"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.ClientId.Hint", "The id of the client"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.ClientSecret", "Client Secret"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.ClientSecret.Hint", "The client secret is used during the authentication for obtaining the Access Token"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.CallbackUrl", "Callback Url"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.CallbackUrl.Hint", "The url where the Authorization code will be send"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.IsActive", "Is Active"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.IsActive.Hint", "You can use it to enable/disable the access to your store for the client"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.AddNew", "Add New Client"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.Edit", "Edit"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.Created", "Created"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.Deleted", "Deleted"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Entities.Client.FieldValidationMessages.Name", "Name is required"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Entities.Client.FieldValidationMessages.ClientId", "Client Id is required"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Entities.Client.FieldValidationMessages.ClientSecret", "Client Secret is required"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Entities.Client.FieldValidationMessages.CallbackUrl", "Callback Url is required"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Settings.GeneralSettingsTitle", "General Settings"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Edit", "Edit"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Client.BackToList", "Back To List"); - - _localizationService.AddOrUpdatePluginLocaleResource("Api.Categories.Fields.Id.Invalid", "Id is invalid"); - _localizationService.AddOrUpdatePluginLocaleResource("Api.InvalidPropertyType", "Invalid Property Type"); - _localizationService.AddOrUpdatePluginLocaleResource("Api.InvalidType", "Invalid {0} type"); - _localizationService.AddOrUpdatePluginLocaleResource("Api.InvalidRequest", "Invalid request"); - _localizationService.AddOrUpdatePluginLocaleResource("Api.InvalidRootProperty", "Invalid root property"); - _localizationService.AddOrUpdatePluginLocaleResource("Api.NoJsonProvided", "No Json provided"); - _localizationService.AddOrUpdatePluginLocaleResource("Api.InvalidJsonFormat", "Json format is invalid"); - _localizationService.AddOrUpdatePluginLocaleResource("Api.Category.InvalidImageAttachmentFormat", "Invalid image attachment base64 format"); - _localizationService.AddOrUpdatePluginLocaleResource("Api.Category.InvalidImageSrc", "Invalid image source"); - _localizationService.AddOrUpdatePluginLocaleResource("Api.Category.InvalidImageSrcType", "You have provided an invalid image source/attachment "); - - _localizationService.AddOrUpdatePluginLocaleResource("Api.WebHooks.CouldNotRegisterWebhook", "Could not register WebHook due to error: {0}"); - _localizationService.AddOrUpdatePluginLocaleResource("Api.WebHooks.CouldNotRegisterDuplicateWebhook", "Could not register WebHook because a webhook with the same URI and Filters is already registered."); - _localizationService.AddOrUpdatePluginLocaleResource("Api.WebHooks.CouldNotUpdateWebhook", "Could not update WebHook due to error: {0}"); - _localizationService.AddOrUpdatePluginLocaleResource("Api.WebHooks.CouldNotDeleteWebhook", "Could not delete WebHook due to error: {0}"); - _localizationService.AddOrUpdatePluginLocaleResource("Api.WebHooks.CouldNotDeleteWebhooks", "Could not delete WebHooks due to error: {0}"); - _localizationService.AddOrUpdatePluginLocaleResource("Api.WebHooks.InvalidFilters", "The following filters are not valid: '{0}'. A list of valid filters can be obtained from the path '{1}'."); - - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.EnableLogging", "Enable Logging"); - _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.EnableLogging.Hint", "By enable logging you will see webhook messages in the Log. These messages are needed ONLY for diagnostic purposes. NOTE: A restart is required when changing this setting in order to take effect"); - - ApiSettings settings = new ApiSettings - { - EnableApi = true, - AllowRequestsFromSwagger = false - }; - - _settingService.SaveSetting(settings); - - base.Install(); - - // Changes to Web.Config trigger application restart. - // This doesn't appear to affect the Install function, but just to be safe we will made web.config changes after the plugin was installed. - //_webConfigMangerHelper.AddConfiguration(); - } - - public override void Uninstall() - { - _objectContext.Uninstall(); - - var persistedGrantMigrator = EngineContext.Current.Resolve().GetService(); - persistedGrantMigrator.Migrate("0"); - - var configurationMigrator = EngineContext.Current.Resolve().GetService(); - configurationMigrator.Migrate("0"); - - // TODO: Delete all resources - //locales - _localizationService.DeletePluginLocaleResource("Plugins.Api"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Menu.ManageClients"); - - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Menu.Title"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Menu.Settings.Title"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Menu.Clients.Title"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Menu.Docs.Title"); - - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Configure"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.GeneralSettings"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.EnableApi"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.EnableApi.Hint"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.AllowRequestsFromSwagger"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.AllowRequestsFromSwagger.Hint"); - - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Client.Name"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Client.ClientId"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Client.ClientSecret"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Client.CallbackUrl"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Client.IsActive"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Client.AddNew"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Client.Edit"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Client.Created"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Client.Deleted"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Entities.Client.FieldValidationMessages.Name"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Entities.Client.FieldValidationMessages.ClientId"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Entities.Client.FieldValidationMessages.ClientSecret"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Entities.Client.FieldValidationMessages.CallbackUrl"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Settings.GeneralSettingsTitle"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Edit"); - _localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Client.BackToList"); - - _localizationService.DeletePluginLocaleResource("Api.WebHooks.CouldNotRegisterWebhook"); - _localizationService.DeletePluginLocaleResource("Api.WebHooks.CouldNotRegisterDuplicateWebhook"); - _localizationService.DeletePluginLocaleResource("Api.WebHooks.CouldNotUpdateWebhook"); - _localizationService.DeletePluginLocaleResource("Api.WebHooks.CouldNotDeleteWebhook"); - _localizationService.DeletePluginLocaleResource("Api.WebHooks.CouldNotDeleteWebhooks"); - _localizationService.DeletePluginLocaleResource("Api.WebHooks.InvalidFilters"); - - base.Uninstall(); - - // Changes to Web.Config trigger application restart. - // This doesn't appear to affect the uninstall function, but just to be safe we will made web.config changes after the plugin was uninstalled. - //_webConfigMangerHelper.RemoveConfiguration(); - } - - public void ManageSiteMap(SiteMapNode rootNode) - { - string pluginMenuName = _localizationService.GetResource("Plugins.Api.Admin.Menu.Title",languageId: _workContext.WorkingLanguage.Id, defaultValue: "API"); - - string settingsMenuName = _localizationService.GetResource("Plugins.Api.Admin.Menu.Settings.Title", languageId: _workContext.WorkingLanguage.Id, defaultValue: "API"); - - string manageClientsMenuName = _localizationService.GetResource("Plugins.Api.Admin.Menu.Clients.Title", languageId: _workContext.WorkingLanguage.Id, defaultValue: "API"); - - const string adminUrlPart = "Admin/"; - - var pluginMainMenu = new SiteMapNode - { - Title = pluginMenuName, - Visible = true, - SystemName = "Api-Main-Menu", - IconClass = "fa-genderless" - }; - - pluginMainMenu.ChildNodes.Add(new SiteMapNode - { - Title = settingsMenuName, - Url = _webHelper.GetStoreLocation() + adminUrlPart + "ApiAdmin/Settings", - Visible = true, - SystemName = "Api-Settings-Menu", - IconClass = "fa-genderless" - }); - - pluginMainMenu.ChildNodes.Add(new SiteMapNode - { - Title = manageClientsMenuName, - Url = _webHelper.GetStoreLocation() + adminUrlPart + "ManageClientsAdmin/List", - Visible = true, - SystemName = "Api-Clients-Menu", - IconClass = "fa-genderless" - }); - - - string pluginDocumentationUrl = "https://github.com/SevenSpikes/api-plugin-for-nopcommerce"; - - pluginMainMenu.ChildNodes.Add(new SiteMapNode - { - Title = _localizationService.GetResource("Plugins.Api.Admin.Menu.Docs.Title"), - Url = pluginDocumentationUrl, - Visible = true, - SystemName = "Api-Docs-Menu", - IconClass = "fa-genderless" - });//TODO: target="_blank" - - - rootNode.ChildNodes.Add(pluginMainMenu); - } - } -} diff --git a/Nop.Plugin.Api/ApiStartup.cs b/Nop.Plugin.Api/ApiStartup.cs deleted file mode 100644 index 33eb334..0000000 --- a/Nop.Plugin.Api/ApiStartup.cs +++ /dev/null @@ -1,315 +0,0 @@ -using Nop.Plugin.Api.Data; -using Nop.Web.Framework.Infrastructure.Extensions; - -namespace Nop.Plugin.Api -{ - using IdentityServer4.EntityFramework; - using IdentityServer4.EntityFramework.DbContexts; - using IdentityServer4.EntityFramework.Entities; - using IdentityServer4.Hosting; - using IdentityServer4.Models; - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Rewrite; - using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.IdentityModel.Tokens; - using Nop.Core.Data; - using Nop.Core.Infrastructure; - using Nop.Plugin.Api.Authorization.Policies; - using Nop.Plugin.Api.Authorization.Requirements; - using Nop.Plugin.Api.Constants; - using Nop.Plugin.Api.Helpers; - using Nop.Plugin.Api.IdentityServer.Endpoints; - using Nop.Plugin.Api.IdentityServer.Generators; - using Nop.Plugin.Api.IdentityServer.Middlewares; - using Nop.Web.Framework.Infrastructure; - using System; - using System.Collections.Generic; - using System.Globalization; - using System.IdentityModel.Tokens.Jwt; - using System.IO; - using System.Linq; - using System.Linq.Dynamic.Core; - using System.Reflection; - using ApiResource = IdentityServer4.EntityFramework.Entities.ApiResource; - - public class ApiStartup : INopStartup - { - private const string ObjectContextName = "nop_object_context_web_api"; - - // TODO: extract all methods into extensions. - public void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - services.AddDbContext(optionsBuilder => - { - optionsBuilder.UseSqlServerWithLazyLoading(services); - }); - - AddRequiredConfiguration(); - - AddBindingRedirectsFallbacks(); - - JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); - - AddTokenGenerationPipeline(services); - - AddAuthorizationPipeline(services); - } - - public void Configure(IApplicationBuilder app) - { - // During a clean install we should not register any middlewares i.e IdentityServer as it won't be able to create its - // tables without a connection string and will throw an exception - var dataSettings = DataSettingsManager.LoadSettings(); - if (!dataSettings?.IsValid ?? true) - return; - - // The default route templates for the Swagger docs and swagger - ui are "swagger/docs/{apiVersion}" and "swagger/ui/index#/{assetPath}" respectively. - //app.UseSwagger(); - //app.UseSwaggerUI(options => - // { - // //var currentAssembly = Assembly.GetAssembly(this.GetType()); - // //var currentAssemblyName = currentAssembly.GetName().Name; - - // //Needeed for removing the "Try It Out" button from the post and put methods. - // //http://stackoverflow.com/questions/36772032/swagger-5-2-3-supportedsubmitmethods-removed/36780806#36780806 - - // //options.InjectOnCompleteJavaScript($"{currentAssemblyName}.Scripts.swaggerPostPutTryItOutButtonsRemoval.js"); - - // options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); - // } - //); - - // This needs to be called here because in the plugin install method identity server is not yet registered. - ApplyIdentityServerMigrations(app); - - SeedData(app); - - - var rewriteOptions = new RewriteOptions() - .AddRewrite("oauth/(.*)", "connect/$1", true) - .AddRewrite("api/token", "connect/token", true); - - app.UseRewriter(rewriteOptions); - - app.UseMiddleware(); - - ////uncomment only if the client is an angular application that directly calls the oauth endpoint - //// app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); - UseIdentityServer(app); - - //need to enable rewind so we can read the request body multiple times (this should eventually be refactored, but both JsonModelBinder and all of the DTO validators need to read this stream) - app.Use(async (context, next) => - { - context.Request.EnableBuffering(); - await next(); - }); - } - - private void UseIdentityServer(IApplicationBuilder app) - { - // The code below is a copy of app.UseIdentityServer(); - // but the nopCommerce AuthenticationMiddleware is added by nopCommmerce and - // it has a try catch for the non-configured properly external authentication providers i.e Facebook - // So there is no need to call UseAuthentication again and thus not being able to catch exceptions thrown by Facebook - - //app.Validate(); - UseMiddlewareExtensions.UseMiddleware(app); - app.ConfigureCors(); - //app.UseAuthentication(); - UseMiddlewareExtensions.UseMiddleware(app); - } - - private void AddRequiredConfiguration() - { - var configManagerHelper = new NopConfigManagerHelper(); - - // some of third party libaries that we use for WebHooks and Swagger use older versions - // of certain assemblies so we need to redirect them to the once that nopCommerce uses - //TODO: Upgrade 4.10 check this! - //configManagerHelper.AddBindingRedirects(); - - // required by the WebHooks support - //TODO: Upgrade 4.10 check this! - //configManagerHelper.AddConnectionString(); - - // This is required only in development. - // It it is required only when you want to send a web hook to an https address with an invalid SSL certificate. (self-signed) - // The code marks all certificates as valid. - // We may want to extract this as a setting in the future. - - // NOTE: If this code is commented the certificates will be validated. - System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; - } - - private void AddAuthorizationPipeline(IServiceCollection services) - { - services.AddAuthorization(options => - { - options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, - policy => - { - policy.Requirements.Add(new ActiveApiPluginRequirement()); - policy.Requirements.Add(new AuthorizationSchemeRequirement()); - policy.Requirements.Add(new ActiveClientRequirement()); - policy.Requirements.Add(new RequestFromSwaggerOptional()); - policy.RequireAuthenticatedUser(); - }); - }); - - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - } - - private void AddTokenGenerationPipeline(IServiceCollection services) - { - RsaSecurityKey signingKey = CryptoHelper.CreateRsaSecurityKey(); - - DataSettings dataSettings = DataSettingsManager.LoadSettings(); - if (!dataSettings?.IsValid ?? true) - return; - - string connectionStringFromNop = dataSettings.DataConnectionString; - - var migrationsAssembly = typeof(ApiStartup).GetTypeInfo().Assembly.GetName().Name; - - services.AddIdentityServer(options => options.UserInteraction.LoginUrl = "/login") - .AddSigningCredential(signingKey) - .AddConfigurationStore(options => - { - options.ConfigureDbContext = builder => - builder.UseSqlServer(connectionStringFromNop, - sql => sql.MigrationsAssembly(migrationsAssembly)); - }) - .AddOperationalStore(options => - { - options.ConfigureDbContext = builder => - builder.UseSqlServer(connectionStringFromNop, - sql => sql.MigrationsAssembly(migrationsAssembly)); - }) - .AddAuthorizeInteractionResponseGenerator() - .AddEndpoint("Authorize", "/oauth/authorize/callback") - .AddEndpoint("Authorize", "/oauth/authorize") - .AddEndpoint("Token", "/oauth/token"); - } - - private void ApplyIdentityServerMigrations(IApplicationBuilder app) - { - using (var serviceScope = app.ApplicationServices.GetService().CreateScope()) - { - // the database.Migrate command will apply all pending migrations and will create the database if it is not created already. - var persistedGrantContext = serviceScope.ServiceProvider.GetRequiredService(); - persistedGrantContext.Database.Migrate(); - - var configurationContext = serviceScope.ServiceProvider.GetRequiredService(); - configurationContext.Database.Migrate(); - } - } - - private void SeedData(IApplicationBuilder app) - { - using (var serviceScope = app.ApplicationServices.GetService().CreateScope()) - { - var configurationContext = serviceScope.ServiceProvider.GetRequiredService(); - - if (!configurationContext.ApiResources.Any()) - { - // In the simple case an API has exactly one scope. But there are cases where you might want to sub-divide the functionality of an API, and give different clients access to different parts. - configurationContext.ApiResources.Add(new ApiResource() - { - Enabled = true, - Scopes = new List() - { - new ApiScope() - { - Name = "nop_api", - DisplayName = "nop_api" - } - }, - Name = "nop_api" - }); - - configurationContext.SaveChanges(); - - TryRunUpgradeScript(configurationContext); - } - } - } - - private string LoadUpgradeScript() - { - var fileProvider = EngineContext.Current.Resolve(); - string path = fileProvider.MapPath("~/Plugins/Nop.Plugin.Api/upgrade_script.sql"); - string script = File.ReadAllText(path); - - return script; - } - - private void TryRunUpgradeScript(ConfigurationDbContext configurationContext) - { - try - { - // If there are no api resources we can assume that this is the first start after the upgrade and run the upgrade script. - string upgradeScript = LoadUpgradeScript(); - configurationContext.Database.ExecuteSqlCommand(upgradeScript); - - // All client secrets must be hashed otherwise the identity server validation will fail. - var allClients = - Enumerable.ToList(configurationContext.Clients.Include(client => client.ClientSecrets)); - foreach (var client in allClients) - { - foreach (var clientSecret in client.ClientSecrets) - { - clientSecret.Value = HashExtensions.Sha256(clientSecret.Value); - } - - client.AccessTokenLifetime = Configurations.DefaultAccessTokenExpiration; - client.AbsoluteRefreshTokenLifetime = Configurations.DefaultRefreshTokenExpiration; - } - - configurationContext.SaveChanges(); - } - catch (Exception ex) - { - // Probably the upgrade script was already executed and we don't need to do anything. - } - } - - public void AddBindingRedirectsFallbacks() - { - // If no binding redirects are present in the config file then this will perform the binding redirect - RedirectAssembly("Microsoft.AspNetCore.DataProtection.Abstractions", new Version(2, 0, 0, 0), "adb9793829ddae60"); - } - - ///Adds an AssemblyResolve handler to redirect all attempts to load a specific assembly name to the specified version. - public static void RedirectAssembly(string shortName, Version targetVersion, string publicKeyToken) - { - ResolveEventHandler handler = null; - - handler = (sender, args) => - { - // Use latest strong name & version when trying to load SDK assemblies - var requestedAssembly = new AssemblyName(args.Name); - if (requestedAssembly.Name != shortName) - return null; - - requestedAssembly.Version = targetVersion; - requestedAssembly.SetPublicKeyToken(new AssemblyName("x, PublicKeyToken=" + publicKeyToken).GetPublicKeyToken()); - requestedAssembly.CultureInfo = CultureInfo.InvariantCulture; - - AppDomain.CurrentDomain.AssemblyResolve -= handler; - - return Assembly.Load(requestedAssembly); - }; - AppDomain.CurrentDomain.AssemblyResolve += handler; - } - - public int Order => new AuthenticationStartup().Order + 1; - } -} diff --git a/Nop.Plugin.Api/Controllers/Admin/ApiAdminController.cs b/Nop.Plugin.Api/Areas/Admin/Controllers/ApiAdminController.cs similarity index 64% rename from Nop.Plugin.Api/Controllers/Admin/ApiAdminController.cs rename to Nop.Plugin.Api/Areas/Admin/Controllers/ApiAdminController.cs index 8ab5e3f..b41df4e 100644 --- a/Nop.Plugin.Api/Controllers/Admin/ApiAdminController.cs +++ b/Nop.Plugin.Api/Areas/Admin/Controllers/ApiAdminController.cs @@ -1,92 +1,88 @@ -namespace Nop.Plugin.Api.Controllers.Admin -{ - using Constants; - using Core; - using Domain; - using MappingExtensions; - using Microsoft.AspNetCore.Mvc; - using Models; - using Nop.Services.Configuration; - using Nop.Services.Localization; - using Nop.Services.Logging; - using Nop.Services.Messages; - using Nop.Web.Framework.Controllers; - using Web.Framework; - using Web.Framework.Mvc.Filters; - - [AuthorizeAdmin] - [Area(AreaNames.Admin)] - public class ApiAdminController : BasePluginController - { - private readonly IStoreContext _storeContext; - private readonly ISettingService _settingService; - private readonly ICustomerActivityService _customerActivityService; - private readonly ILocalizationService _localizationService; - private readonly INotificationService _notificationService; - - public ApiAdminController( - IStoreContext storeContext, - ISettingService settingService, - ICustomerActivityService customerActivityService, - ILocalizationService localizationService, - INotificationService notificationService) - { - _storeContext = storeContext; - _settingService = settingService; - _customerActivityService = customerActivityService; - _localizationService = localizationService; - _notificationService = notificationService; - } - - [HttpGet] - public ActionResult Settings() - { - - var storeScope = _storeContext.ActiveStoreScopeConfiguration; - - var apiSettings = _settingService.LoadSetting(storeScope); - - var model = apiSettings.ToModel(); - - // Store Settings - model.ActiveStoreScopeConfiguration = storeScope; - - if (model.EnableApi_OverrideForStore || storeScope == 0) - _settingService.SaveSetting(apiSettings, x => x.EnableApi, storeScope, false); - if (model.AllowRequestsFromSwagger_OverrideForStore || storeScope == 0) - _settingService.SaveSetting(apiSettings, x => x.AllowRequestsFromSwagger, storeScope, false); - - //now clear settings cache - _settingService.ClearCache(); - - return View(ViewNames.AdminApiSettings, model); - } - - [HttpPost] - public ActionResult Settings(ConfigurationModel configurationModel) - { - //load settings for a chosen store scope - var storeScope = _storeContext.ActiveStoreScopeConfiguration; - - var settings = configurationModel.ToEntity(); - - /* We do not clear cache after each setting update. - * This behavior can increase performance because cached settings will not be cleared - * and loaded from database after each update */ - - if (configurationModel.EnableApi_OverrideForStore || storeScope == 0) - _settingService.SaveSetting(settings, x => x.EnableApi, storeScope, false); - if (configurationModel.AllowRequestsFromSwagger_OverrideForStore || storeScope == 0) - _settingService.SaveSetting(settings, x => x.AllowRequestsFromSwagger, storeScope, false); - - //now clear settings cache - _settingService.ClearCache(); - - _customerActivityService.InsertActivity("EditApiSettings", "Edit Api Settings"); - - _notificationService.SuccessNotification(_localizationService.GetResource("Admin.Plugins.Saved")); - - return View(ViewNames.AdminApiSettings, configurationModel); - } - } -} \ No newline at end of file +using Microsoft.AspNetCore.Mvc; +using Nop.Core; +using Nop.Plugin.Api.Areas.Admin.Models; +using Nop.Plugin.Api.Domain; +using Nop.Plugin.Api.MappingExtensions; +using Nop.Services.Configuration; +using Nop.Services.Localization; +using Nop.Services.Logging; +using Nop.Services.Messages; +using Nop.Web.Framework; +using Nop.Web.Framework.Controllers; +using Nop.Web.Framework.Mvc.Filters; + +namespace Nop.Plugin.Api.Areas.Admin.Controllers +{ + [AuthorizeAdmin] + [Area(AreaNames.Admin)] + public class ApiAdminController : BasePluginController + { + private readonly ICustomerActivityService _customerActivityService; + private readonly ILocalizationService _localizationService; + private readonly INotificationService _notificationService; + private readonly ISettingService _settingService; + private readonly IStoreContext _storeContext; + + public ApiAdminController( + IStoreContext storeContext, + ISettingService settingService, + ICustomerActivityService customerActivityService, + ILocalizationService localizationService, + INotificationService notificationService) + { + _storeContext = storeContext; + _settingService = settingService; + _customerActivityService = customerActivityService; + _localizationService = localizationService; + _notificationService = notificationService; + } + + [HttpGet] + public IActionResult Settings() + { + var storeScope = _storeContext.ActiveStoreScopeConfiguration; + var apiSettings = _settingService.LoadSetting(storeScope); + var model = apiSettings.ToModel(); + + // Store Settings + model.ActiveStoreScopeConfiguration = storeScope; + + if (model.EnableApi_OverrideForStore || storeScope == 0) + { + _settingService.SaveSetting(apiSettings, x => x.EnableApi, storeScope, false); + } + + //now clear settings cache + _settingService.ClearCache(); + + return View($"~/Plugins/Nop.Plugin.Api/Areas/Admin/Views/ApiAdmin/Settings.cshtml", model); + } + + [HttpPost] + public IActionResult Settings(ConfigurationModel model) + { + //load settings for a chosen store scope + var storeScope = _storeContext.ActiveStoreScopeConfiguration; + + var settings = model.ToEntity(); + + /* We do not clear cache after each setting update. + * This behavior can increase performance because cached settings will not be cleared + * and loaded from database after each update */ + + if (model.EnableApi_OverrideForStore || storeScope == 0) + { + _settingService.SaveSetting(settings, x => x.EnableApi, storeScope, false); + } + + //now clear settings cache + _settingService.ClearCache(); + + _customerActivityService.InsertActivity("EditApiSettings", "Edit Api Settings"); + + _notificationService.SuccessNotification(_localizationService.GetResource("Admin.Plugins.Saved")); + + return View($"~/Plugins/Nop.Plugin.Api/Areas/Admin/Views/ApiAdmin/Settings.cshtml", model); + } + } +} diff --git a/Nop.Plugin.Api/Models/ConfigurationModel.cs b/Nop.Plugin.Api/Areas/Admin/Models/ConfigurationModel.cs similarity index 87% rename from Nop.Plugin.Api/Models/ConfigurationModel.cs rename to Nop.Plugin.Api/Areas/Admin/Models/ConfigurationModel.cs index b71c6ae..40b885d 100644 --- a/Nop.Plugin.Api/Models/ConfigurationModel.cs +++ b/Nop.Plugin.Api/Areas/Admin/Models/ConfigurationModel.cs @@ -1,21 +1,24 @@ -namespace Nop.Plugin.Api.Models -{ - using Nop.Web.Framework.Mvc.ModelBinding; +using Nop.Web.Framework.Mvc.ModelBinding; +namespace Nop.Plugin.Api.Areas.Admin.Models +{ public class ConfigurationModel { [NopResourceDisplayName("Plugins.Api.Admin.EnableApi")] public bool EnableApi { get; set; } + public bool EnableApi_OverrideForStore { get; set; } [NopResourceDisplayName("Plugins.Api.Admin.AllowRequestsFromSwagger")] public bool AllowRequestsFromSwagger { get; set; } + public bool AllowRequestsFromSwagger_OverrideForStore { get; set; } [NopResourceDisplayName("Plugins.Api.Admin.EnableLogging")] public bool EnableLogging { get; set; } + public bool EnableLogging_OverrideForStore { get; set; } public int ActiveStoreScopeConfiguration { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Views/Settings.cshtml b/Nop.Plugin.Api/Areas/Admin/Views/ApiAdmin/Settings.cshtml similarity index 53% rename from Nop.Plugin.Api/Views/Settings.cshtml rename to Nop.Plugin.Api/Areas/Admin/Views/ApiAdmin/Settings.cshtml index 27fbca1..334b0e9 100644 --- a/Nop.Plugin.Api/Views/Settings.cshtml +++ b/Nop.Plugin.Api/Areas/Admin/Views/ApiAdmin/Settings.cshtml @@ -1,7 +1,8 @@ -@model ConfigurationModel +@using Nop.Plugin.Api.Infrastructure +@model Nop.Plugin.Api.Areas.Admin.Models.ConfigurationModel @{ - Layout = ViewNames.AdminLayout; + Layout = Constants.ViewNames.AdminLayout; //page title ViewBag.Title = T("Plugins.Api.Admin.Page.Settings.Title").Text; @@ -28,7 +29,6 @@
@await Component.InvokeAsync("StoreScopeConfiguration") - @await Component.InvokeAsync("SettingMode") @Html.ValidationSummary(false)
@@ -44,26 +44,6 @@
-
-
- - -
-
- - -
-
-
-
- - -
-
- - -
-
diff --git a/Nop.Plugin.Api/Views/_ViewImports.cshtml b/Nop.Plugin.Api/Areas/Admin/Views/_ViewImports.cshtml similarity index 66% rename from Nop.Plugin.Api/Views/_ViewImports.cshtml rename to Nop.Plugin.Api/Areas/Admin/Views/_ViewImports.cshtml index 3a80be5..48841e6 100644 --- a/Nop.Plugin.Api/Views/_ViewImports.cshtml +++ b/Nop.Plugin.Api/Areas/Admin/Views/_ViewImports.cshtml @@ -2,7 +2,5 @@ @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, Nop.Web.Framework -@using Nop.Plugin.Api.Constants @using Nop.Web.Framework.UI -@using Nop.Plugin.Api.Models; -@using IdentityServer4.Models; \ No newline at end of file +@using Nop.Plugin.Api.Models diff --git a/Nop.Plugin.Api/Attributes/ApiAuthorize.cs b/Nop.Plugin.Api/Attributes/ApiAuthorize.cs deleted file mode 100644 index f034fb0..0000000 --- a/Nop.Plugin.Api/Attributes/ApiAuthorize.cs +++ /dev/null @@ -1,43 +0,0 @@ -using Nop.Core.Infrastructure; -using Nop.Services.Plugins; - -namespace Nop.Plugin.Api.Attributes -{ - using Microsoft.AspNetCore.Authorization; - - // We need the ApiAuthorize attribute because when the api plugin assembly is loaded in memory by PluginManager - // all of its attributes are being initialized by the .NetFramework. - // The authorize attribute of the api plugin is marked with the Bearer authentication scheme, but the scheme is registered in the ApiStartup class, - // which is called on plugin install. - // If the plugin is not installed the authorize attribute will still be initialized when the assembly is loaded in memory, but the scheme won't be registered, - // which will cause an exception. - // That is why we need to make sure that the plugin is installed before setting the scheme. - public class ApiAuthorize : AuthorizeAttribute - { - public new string Policy - { - get => base.AuthenticationSchemes; - set => base.AuthenticationSchemes = GetAuthenticationSchemeName(value); - } - - public new string AuthenticationSchemes - { - get => base.AuthenticationSchemes; - set => base.AuthenticationSchemes = GetAuthenticationSchemeName(value); - } - - private static string GetAuthenticationSchemeName(string value) - { - var pluginService = EngineContext.Current.Resolve(); - var pluginDescriptor = pluginService.GetPluginDescriptorBySystemName(Nop.Plugin.Api.Constants.Plugin.SystemName); - bool pluginInstalled = pluginDescriptor != null && pluginDescriptor.Installed; - - if (pluginInstalled) - { - return value; - } - - return default(string); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Attributes/BaseAttributeInvoker.cs b/Nop.Plugin.Api/Attributes/BaseAttributeInvoker.cs index 556e3d4..b9b2aa6 100644 --- a/Nop.Plugin.Api/Attributes/BaseAttributeInvoker.cs +++ b/Nop.Plugin.Api/Attributes/BaseAttributeInvoker.cs @@ -6,6 +6,6 @@ namespace Nop.Plugin.Api.Attributes public abstract class BaseValidationAttribute : Attribute { public abstract void Validate(object instance); - public abstract Dictionary GetErrors(); + public abstract Dictionary GetErrors(); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Attributes/DoNotMap.cs b/Nop.Plugin.Api/Attributes/DoNotMap.cs index 2842097..a3459a9 100644 --- a/Nop.Plugin.Api/Attributes/DoNotMap.cs +++ b/Nop.Plugin.Api/Attributes/DoNotMap.cs @@ -4,6 +4,6 @@ namespace Nop.Plugin.Api.Attributes { public class DoNotMapAttribute : Attribute { - // just a marker + // just a marker } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Attributes/GetRequestsErrorInterceptorActionFilter.cs b/Nop.Plugin.Api/Attributes/GetRequestsErrorInterceptorActionFilter.cs index 161a089..f53fcdc 100644 --- a/Nop.Plugin.Api/Attributes/GetRequestsErrorInterceptorActionFilter.cs +++ b/Nop.Plugin.Api/Attributes/GetRequestsErrorInterceptorActionFilter.cs @@ -1,10 +1,11 @@ using System.Collections.Generic; using System.IO; using System.Net; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Newtonsoft.Json; using Nop.Core.Infrastructure; -using Nop.Plugin.Api.DTOs.Errors; +using Nop.Plugin.Api.DTO.Errors; using Nop.Plugin.Api.JSON.ActionResults; using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.Models; @@ -25,7 +26,10 @@ public override void OnActionExecuted(ActionExecutedContext actionExecutedContex if (actionExecutedContext.Exception != null && !actionExecutedContext.ExceptionHandled) { var error = new KeyValuePair>("internal_server_error", - new List {"please, contact the store owner"}); + new List + { + "please, contact the store owner" + }); actionExecutedContext.Exception = null; actionExecutedContext.ExceptionHandled = true; @@ -41,17 +45,20 @@ public override void OnActionExecuted(ActionExecutedContext actionExecutedContex responseBody = streamReader.ReadToEnd(); } - // reset reader possition. + // reset reader position. actionExecutedContext.HttpContext.Response.Body.Position = 0; - var defaultWebApiErrorsModel = JsonConvert.DeserializeObject(responseBody); + var defaultWebApiErrorsModel = JsonConvert.DeserializeObject(responseBody); // If both are null this means that it is not the default web api error format, // which means that it the error is formatted by our standard and we don't need to do anything. if (!string.IsNullOrEmpty(defaultWebApiErrorsModel.Message) && !string.IsNullOrEmpty(defaultWebApiErrorsModel.MessageDetail)) { - var error = new KeyValuePair>("lookup_error", new List {"not found"}); + var error = new KeyValuePair>("lookup_error", new List + { + "not found" + }); SetError(actionExecutedContext, error); } @@ -62,16 +69,25 @@ public override void OnActionExecuted(ActionExecutedContext actionExecutedContex private void SetError(ActionExecutedContext actionExecutedContext, KeyValuePair> error) { - var bindingError = new Dictionary> {{error.Key, error.Value}}; + var bindingError = new Dictionary> + { + { + error.Key, error.Value + } + }; var errorsRootObject = new ErrorsRootObject - { - Errors = bindingError - }; + { + Errors = bindingError + }; var errorJson = _jsonFieldsSerializer.Serialize(errorsRootObject, null); - - actionExecutedContext.Result = new ErrorActionResult(errorJson, HttpStatusCode.BadRequest); + var response = new ContentResult(); + response.Content = errorJson; + response.ContentType = "application/json"; + response.StatusCode = (int)HttpStatusCode.InternalServerError; + actionExecutedContext.Result = response; + } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Attributes/ImageAttribute.cs b/Nop.Plugin.Api/Attributes/ImageAttribute.cs index 764c7a2..38bea5a 100644 --- a/Nop.Plugin.Api/Attributes/ImageAttribute.cs +++ b/Nop.Plugin.Api/Attributes/ImageAttribute.cs @@ -1,20 +1,20 @@ -using System.Collections.Generic; -using System.Net; -using Nop.Plugin.Api.DTOs.Images; -using System; +using System; +using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; +using System.Net; using System.Text.RegularExpressions; using Nop.Core.Infrastructure; +using Nop.Plugin.Api.DTO.Images; using Nop.Services.Media; namespace Nop.Plugin.Api.Attributes { public class ImageValidationAttribute : BaseValidationAttribute { - private Dictionary _errors; + private readonly Dictionary _errors; private readonly IPictureService _pictureService; public ImageValidationAttribute() @@ -29,7 +29,7 @@ public override void Validate(object instance) var imageSrcSet = imageDto != null && !string.IsNullOrEmpty(imageDto.Src); var imageAttachmentSet = imageDto != null && !string.IsNullOrEmpty(imageDto.Attachment); - + if (imageSrcSet || imageAttachmentSet) { byte[] imageBytes = null; @@ -56,7 +56,7 @@ public override void Validate(object instance) if (_errors.Count == 0) { ConvertAttachmentToByteArray(imageDto.Attachment, ref imageBytes, - ref mimeType); + ref mimeType); } } } @@ -84,14 +84,14 @@ private void CheckIfBothImageSourceTypesAreSet(bool imageSrcSet, bool imageAttac if (imageSrcSet && imageAttachmentSet) { - var key = string.Format("{0} type", "image"); - _errors.Add(key, "Image src and Attachment are both set"); + const string Key = "image type"; + _errors.Add(Key, "Image src and Attachment are both set"); } } private void DownloadFromSrc(string imageSrc, ref byte[] imageBytes, ref string mimeType) { - var key = string.Format("{0} type", "image"); + const string Key = "image type"; // TODO: discuss if we need our own web client so we can set a custom tmeout - this one's timeout is 100 sec. var client = new WebClient(); @@ -103,14 +103,14 @@ private void DownloadFromSrc(string imageSrc, ref byte[] imageBytes, ref string if (imageBytes == null) { - _errors.Add(key, "src is invalid"); + _errors.Add(Key, "src is invalid"); } } catch (Exception ex) { - var message = string.Format("{0} - {1}", "src is invalid", ex.Message); + var message = $"{"src is invalid"} - {ex.Message}"; - _errors.Add(key, message); + _errors.Add(Key, message); } } @@ -121,12 +121,12 @@ private void ValidateAttachmentFormat(string attachment) var isMatch = validBase64Pattern.IsMatch(attachment); if (!isMatch) { - var key = string.Format("{0} type", "image"); - _errors.Add(key, "attachment format is invalid"); + const string Key = "image type"; + _errors.Add(Key, "attachment format is invalid"); } } - private void ConvertAttachmentToByteArray(string attachment, ref byte[] imageBytes, ref string mimeType) + private static void ConvertAttachmentToByteArray(string attachment, ref byte[] imageBytes, ref string mimeType) { imageBytes = Convert.FromBase64String(attachment); mimeType = GetMimeTypeFromByteArray(imageBytes); @@ -151,8 +151,8 @@ private void ValidatePictureBiteArray(byte[] imageBytes, string mimeType) } catch (Exception ex) { - var key = string.Format("{0} invalid", "image"); - var message = string.Format("{0} - {1}", "source is invalid", ex.Message); + var key = "image invalid"; + var message = $"source is invalid - {ex.Message}"; _errors.Add(key, message); } @@ -160,11 +160,11 @@ private void ValidatePictureBiteArray(byte[] imageBytes, string mimeType) if (imageBytes == null) { - var key = string.Format("{0} invalid", "image"); + var key = "image invalid"; var message = "You have provided an invalid image source/attachment"; _errors.Add(key, message); } } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Attributes/ImageCollectionAttribute.cs b/Nop.Plugin.Api/Attributes/ImageCollectionAttribute.cs index eefe1d7..c8ea0e4 100644 --- a/Nop.Plugin.Api/Attributes/ImageCollectionAttribute.cs +++ b/Nop.Plugin.Api/Attributes/ImageCollectionAttribute.cs @@ -1,5 +1,5 @@ using System.Collections.Generic; -using Nop.Plugin.Api.DTOs.Images; +using Nop.Plugin.Api.DTO.Images; namespace Nop.Plugin.Api.Attributes { @@ -11,23 +11,22 @@ public override void Validate(object instance) { // Images are not required so they could be null // and there is nothing to validate in this case - if (instance == null) - return; - var imagesCollection = instance as ICollection; - - foreach (var image in imagesCollection) + if (instance is ICollection imagesCollection) { - var imageValidationAttribute = new ImageValidationAttribute(); + foreach (var image in imagesCollection) + { + var imageValidationAttribute = new ImageValidationAttribute(); - imageValidationAttribute.Validate(image); + imageValidationAttribute.Validate(image); - var errorsForImage = imageValidationAttribute.GetErrors(); + var errorsForImage = imageValidationAttribute.GetErrors(); - if (errorsForImage.Count > 0) - { - _errors = errorsForImage; - break; + if (errorsForImage.Count > 0) + { + _errors = errorsForImage; + break; + } } } } @@ -37,4 +36,4 @@ public override Dictionary GetErrors() return _errors; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Attributes/ProductTypeValidationAttribute.cs b/Nop.Plugin.Api/Attributes/ProductTypeValidationAttribute.cs index 4cc2b67..522e846 100644 --- a/Nop.Plugin.Api/Attributes/ProductTypeValidationAttribute.cs +++ b/Nop.Plugin.Api/Attributes/ProductTypeValidationAttribute.cs @@ -13,13 +13,15 @@ public override void Validate(object instance) // Product Type is not required so it could be null // and there is nothing to validate in this case if (instance == null) + { return; + } var isDefined = Enum.IsDefined(typeof(ProductType), instance); if (!isDefined) - { - _errors.Add("ProductType","Invalid product type"); + { + _errors.Add("ProductType", "Invalid product type"); } } @@ -28,4 +30,4 @@ public override Dictionary GetErrors() return _errors; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Attributes/ValidateVendor.cs b/Nop.Plugin.Api/Attributes/ValidateVendor.cs index 3cebcad..7673cce 100644 --- a/Nop.Plugin.Api/Attributes/ValidateVendor.cs +++ b/Nop.Plugin.Api/Attributes/ValidateVendor.cs @@ -6,33 +6,20 @@ namespace Nop.Plugin.Api.Attributes { public class ValidateVendor : BaseValidationAttribute { - private Dictionary _errors; + private readonly Dictionary _errors; private IVendorService _vendorService; - private IVendorService VendorService - { - get - { - if (_vendorService == null) - { - _vendorService = EngineContext.Current.Resolve(); - } - - return _vendorService; - } - } - public ValidateVendor() { _errors = new Dictionary(); } + private IVendorService VendorService => _vendorService ?? (_vendorService = EngineContext.Current.Resolve()); + public override void Validate(object instance) { - var vendorId = 0; - - if (instance != null && int.TryParse(instance.ToString(), out vendorId)) + if (instance != null && int.TryParse(instance.ToString(), out var vendorId)) { if (vendorId > 0) { @@ -51,4 +38,4 @@ public override Dictionary GetErrors() return _errors; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Authorization/Policies/ActiveApiPluginAuthorizationPolicy.cs b/Nop.Plugin.Api/Authorization/Policies/ActiveApiPluginAuthorizationPolicy.cs index 7e20c82..b97e4b7 100644 --- a/Nop.Plugin.Api/Authorization/Policies/ActiveApiPluginAuthorizationPolicy.cs +++ b/Nop.Plugin.Api/Authorization/Policies/ActiveApiPluginAuthorizationPolicy.cs @@ -1,9 +1,9 @@ -namespace Nop.Plugin.Api.Authorization.Policies -{ - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Nop.Plugin.Api.Authorization.Requirements; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Nop.Plugin.Api.Authorization.Requirements; +namespace Nop.Plugin.Api.Authorization.Policies +{ public class ActiveApiPluginAuthorizationPolicy : AuthorizationHandler { protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ActiveApiPluginRequirement requirement) @@ -20,4 +20,4 @@ protected override Task HandleRequirementAsync(AuthorizationHandlerContext conte return Task.CompletedTask; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Authorization/Policies/ActiveClientAuthorizationPolicy.cs b/Nop.Plugin.Api/Authorization/Policies/ActiveClientAuthorizationPolicy.cs deleted file mode 100644 index 882ac78..0000000 --- a/Nop.Plugin.Api/Authorization/Policies/ActiveClientAuthorizationPolicy.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace Nop.Plugin.Api.Authorization.Policies -{ - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Nop.Plugin.Api.Authorization.Requirements; - - public class ActiveClientAuthorizationPolicy : AuthorizationHandler - { - protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ActiveClientRequirement requirement) - { - if (requirement.IsClientActive()) - { - context.Succeed(requirement); - } - else - { - context.Fail(); - } - - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Authorization/Policies/CustomerRoleAuthorizationPolicy.cs b/Nop.Plugin.Api/Authorization/Policies/CustomerRoleAuthorizationPolicy.cs new file mode 100644 index 0000000..bf02bfc --- /dev/null +++ b/Nop.Plugin.Api/Authorization/Policies/CustomerRoleAuthorizationPolicy.cs @@ -0,0 +1,23 @@ +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Nop.Plugin.Api.Authorization.Requirements; + +namespace Nop.Plugin.Api.Authorization.Policies +{ + public class CustomerRoleAuthorizationPolicy : AuthorizationHandler + { + protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomerRoleRequirement requirement) + { + if (requirement.IsCustomerInRole()) + { + context.Succeed(requirement); + } + else + { + context.Fail(); + } + + return Task.CompletedTask; + } + } +} diff --git a/Nop.Plugin.Api/Authorization/Policies/RequestsFromSwaggerAuthorizationPolicy.cs b/Nop.Plugin.Api/Authorization/Policies/RequestsFromSwaggerAuthorizationPolicy.cs deleted file mode 100644 index 143872e..0000000 --- a/Nop.Plugin.Api/Authorization/Policies/RequestsFromSwaggerAuthorizationPolicy.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace Nop.Plugin.Api.Authorization.Policies -{ - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Nop.Plugin.Api.Authorization.Requirements; - - public class RequestsFromSwaggerAuthorizationPolicy : AuthorizationHandler - { - protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RequestFromSwaggerOptional requirement) - { - if (requirement.AllowRequestsFromSwagger()) - { - if (requirement.IsRequestFromSwagger(context.Resource as string)) - { - context.Succeed(requirement); - } - else - { - context.Fail(); - } - } - else - { - context.Succeed(requirement); - } - - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Authorization/Policies/ValidSchemeAuthorizationPolicy.cs b/Nop.Plugin.Api/Authorization/Policies/ValidSchemeAuthorizationPolicy.cs index 9eacd77..02a9e66 100644 --- a/Nop.Plugin.Api/Authorization/Policies/ValidSchemeAuthorizationPolicy.cs +++ b/Nop.Plugin.Api/Authorization/Policies/ValidSchemeAuthorizationPolicy.cs @@ -1,17 +1,32 @@ -namespace Nop.Plugin.Api.Authorization.Policies -{ - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authorization; - using Nop.Plugin.Api.Authorization.Requirements; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.Filters; +using Nop.Plugin.Api.Authorization.Requirements; +namespace Nop.Plugin.Api.Authorization.Policies +{ public class ValidSchemeAuthorizationPolicy : AuthorizationHandler { + IHttpContextAccessor _httpContextAccessor = null; + public ValidSchemeAuthorizationPolicy(IHttpContextAccessor httpContextAccessor) + { + _httpContextAccessor = httpContextAccessor; + } protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AuthorizationSchemeRequirement requirement) { - var mvcContext = context.Resource as - Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext; + //var mvcContext = context.Resource as + // AuthorizationFilterContext; + //if (requirement.IsValid(mvcContext?.HttpContext.Request.Headers)) + //{ + // context.Succeed(requirement); + //} + //else + //{ + // context.Fail(); + //} - if (requirement.IsValid(mvcContext?.HttpContext.Request.Headers)) + if (requirement.IsValid(_httpContextAccessor?.HttpContext.Request.Headers)) { context.Succeed(requirement); } @@ -23,4 +38,4 @@ protected override Task HandleRequirementAsync(AuthorizationHandlerContext conte return Task.CompletedTask; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Authorization/Requirements/ActiveApiPluginRequirement.cs b/Nop.Plugin.Api/Authorization/Requirements/ActiveApiPluginRequirement.cs index 7ac1fce..c933839 100644 --- a/Nop.Plugin.Api/Authorization/Requirements/ActiveApiPluginRequirement.cs +++ b/Nop.Plugin.Api/Authorization/Requirements/ActiveApiPluginRequirement.cs @@ -1,9 +1,9 @@ -namespace Nop.Plugin.Api.Authorization.Requirements -{ - using Microsoft.AspNetCore.Authorization; - using Nop.Core.Infrastructure; - using Nop.Plugin.Api.Domain; +using Microsoft.AspNetCore.Authorization; +using Nop.Core.Infrastructure; +using Nop.Plugin.Api.Domain; +namespace Nop.Plugin.Api.Authorization.Requirements +{ public class ActiveApiPluginRequirement : IAuthorizationRequirement { public bool IsActive() @@ -18,4 +18,4 @@ public bool IsActive() return false; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Authorization/Requirements/ActiveClientRequirement.cs b/Nop.Plugin.Api/Authorization/Requirements/ActiveClientRequirement.cs deleted file mode 100644 index bb2117f..0000000 --- a/Nop.Plugin.Api/Authorization/Requirements/ActiveClientRequirement.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace Nop.Plugin.Api.Authorization.Requirements -{ - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Http; - using Nop.Core.Infrastructure; - using Nop.Plugin.Api.Services; - - public class ActiveClientRequirement : IAuthorizationRequirement - { - public bool IsClientActive() - { - if (!ClientExistsAndActive()) - { - // don't authorize if any of the above is not true - return false; - } - - return true; - } - - private bool ClientExistsAndActive() - { - var httpContextAccessor = EngineContext.Current.Resolve(); - - var clientId = - httpContextAccessor.HttpContext.User.FindFirst("client_id")?.Value; - - if (clientId != null) - { - var clientService = EngineContext.Current.Resolve(); - var client = clientService.FindClientByClientId(clientId); - - if (client != null && client.Enabled) - { - return true; - } - } - - return false; - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Authorization/Requirements/AuthorizationSchemeRequirement.cs b/Nop.Plugin.Api/Authorization/Requirements/AuthorizationSchemeRequirement.cs index dd1d6f6..2431655 100644 --- a/Nop.Plugin.Api/Authorization/Requirements/AuthorizationSchemeRequirement.cs +++ b/Nop.Plugin.Api/Authorization/Requirements/AuthorizationSchemeRequirement.cs @@ -1,15 +1,15 @@ -namespace Nop.Plugin.Api.Authorization.Requirements -{ - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +namespace Nop.Plugin.Api.Authorization.Requirements +{ public class AuthorizationSchemeRequirement : IAuthorizationRequirement { public bool IsValid(IHeaderDictionary requestHeaders) { - if (requestHeaders != null && - requestHeaders.ContainsKey("Authorization") && + if (requestHeaders != null && + requestHeaders.ContainsKey("Authorization") && requestHeaders["Authorization"].ToString().Contains(JwtBearerDefaults.AuthenticationScheme)) { return true; @@ -18,4 +18,4 @@ public bool IsValid(IHeaderDictionary requestHeaders) return false; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Authorization/Requirements/CustomerRoleRequirement.cs b/Nop.Plugin.Api/Authorization/Requirements/CustomerRoleRequirement.cs new file mode 100644 index 0000000..10deccc --- /dev/null +++ b/Nop.Plugin.Api/Authorization/Requirements/CustomerRoleRequirement.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Nop.Core.Domain.Customers; +using Nop.Core.Infrastructure; +using Nop.Plugin.Api.Infrastructure; +using Nop.Services.Customers; + +namespace Nop.Plugin.Api.Authorization.Requirements +{ + public class CustomerRoleRequirement : IAuthorizationRequirement + { + public bool IsCustomerInRole() + { + try + { + var httpContextAccessor = EngineContext.Current.Resolve(); + + var customerIdClaim = httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(m => m.Type == ClaimTypes.NameIdentifier); + + if (customerIdClaim != null && Guid.TryParse(customerIdClaim.Value, out var customerGuid)) + { + var customerService = EngineContext.Current.Resolve(); + + var customer = customerService.GetCustomerByGuid(customerGuid); + + if (customer != null) + { + var customerRoles = customerService.GetCustomerRoles(customer); + return IsInApiRole(customerRoles); + } + } + } + catch + { + // best effort + } + + return false; + } + + private static bool IsInApiRole(IEnumerable customerRoles) + { + return customerRoles.FirstOrDefault(cr => cr.SystemName == Constants.Roles.ApiRoleSystemName) != null; + } + } +} diff --git a/Nop.Plugin.Api/Authorization/Requirements/RequestFromSwaggerOptional.cs b/Nop.Plugin.Api/Authorization/Requirements/RequestFromSwaggerOptional.cs deleted file mode 100644 index f1b7357..0000000 --- a/Nop.Plugin.Api/Authorization/Requirements/RequestFromSwaggerOptional.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace Nop.Plugin.Api.Authorization.Requirements -{ - using Microsoft.AspNetCore.Authorization; - using Nop.Core.Infrastructure; - using Nop.Plugin.Api.Domain; - - public class RequestFromSwaggerOptional : IAuthorizationRequirement - { - public bool IsRequestFromSwagger(string requestReferrer) - { - // Swagger client does not support BearerToken authentication. - // That is why we don't check for Bearer token authentication but check only 2 things: - // 1. The store owner explicitly has allowed Swagger to make requests to the API - // 2. Check if the request really comes from Swagger documentation page. Since Swagger documentation page is located on /swagger/index we simply check that the Refferer contains "swagger" - if (requestReferrer != null && requestReferrer.Contains("swagger")) - { - return true; - } - - return true; - } - - public bool AllowRequestsFromSwagger() - { - var settings = EngineContext.Current.Resolve(); - - return settings.AllowRequestsFromSwagger; - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/AutoMapper/ApiMapperConfiguration.cs b/Nop.Plugin.Api/AutoMapper/ApiMapperConfiguration.cs new file mode 100644 index 0000000..eb68aeb --- /dev/null +++ b/Nop.Plugin.Api/AutoMapper/ApiMapperConfiguration.cs @@ -0,0 +1,201 @@ +using System.Collections.Generic; +using System.Linq; +using System.Net; +using AutoMapper; +using Nop.Core.Domain.Catalog; +using Nop.Core.Domain.Common; +using Nop.Core.Domain.Customers; +using Nop.Core.Domain.Directory; +using Nop.Core.Domain.Localization; +using Nop.Core.Domain.Messages; +using Nop.Core.Domain.Orders; +using Nop.Core.Domain.Stores; +using Nop.Core.Infrastructure.Mapper; +using Nop.Plugin.Api.Areas.Admin.Models; +using Nop.Plugin.Api.Domain; +using Nop.Plugin.Api.DTO; +using Nop.Plugin.Api.DTO.Categories; +using Nop.Plugin.Api.DTO.CustomerRoles; +using Nop.Plugin.Api.DTO.Customers; +using Nop.Plugin.Api.DTO.Languages; +using Nop.Plugin.Api.DTO.Manufacturers; +using Nop.Plugin.Api.DTO.NewsLetterSubscriptions; +using Nop.Plugin.Api.DTO.OrderItems; +using Nop.Plugin.Api.DTO.Orders; +using Nop.Plugin.Api.DTO.ProductAttributes; +using Nop.Plugin.Api.DTO.ProductCategoryMappings; +using Nop.Plugin.Api.DTO.ProductManufacturerMappings; +using Nop.Plugin.Api.DTO.Products; +using Nop.Plugin.Api.DTO.ShoppingCarts; +using Nop.Plugin.Api.DTO.SpecificationAttributes; +using Nop.Plugin.Api.DTO.Stores; +using Nop.Plugin.Api.MappingExtensions; + +namespace Nop.Plugin.Api.AutoMapper +{ + public class ApiMapperConfiguration : Profile, IOrderedMapperProfile + { + public ApiMapperConfiguration() + { + CreateMap(); + CreateMap(); + + CreateMap(); + CreateMap(); + + CreateMap(); + + CreateMap(); + + CreateMap(); + + CreateMap(); + + CreateMap(); + + CreateMap(); + + CreateClientToClientApiModelMap(); + + CreateAddressMap(); + CreateAddressDtoToEntityMap(); + CreateShoppingCartItemMap(); + + CreateCustomerToDTOMap(); + CreateCustomerToOrderCustomerDTOMap(); + CreateCustomerDTOToOrderCustomerDTOMap(); + CreateCustomerForShoppingCartItemMapFromCustomer(); + + CreateMap(); + CreateOrderEntityToOrderDtoMap(); + + CreateProductMap(); + + CreateMap(); + + CreateMap(); + + CreateMap(); + + CreateMap(); + CreateMap(); + + CreateMap(); + CreateMap(); + } + + public int Order => 0; + + private new static void CreateMap() + { + AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() + .IgnoreAllNonExisting(); + } + + private static void CreateClientToClientApiModelMap() + { + //AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() + // .ForMember(x => x.ClientSecret, y => y.MapFrom(src => src.ClientSecrets.FirstOrDefault().Description)) + // .ForMember(x => x.RedirectUrl, y => y.MapFrom(src => src.RedirectUris.FirstOrDefault().RedirectUri)) + // .ForMember(x => x.AccessTokenLifetime, y => y.MapFrom(src => src.AccessTokenLifetime)) + // .ForMember(x => x.RefreshTokenLifetime, y => y.MapFrom(src => src.AbsoluteRefreshTokenLifetime)); + } + + private void CreateOrderEntityToOrderDtoMap() + { + AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() + .IgnoreAllNonExisting() + .ForMember(x => x.Id, y => y.MapFrom(src => src.Id)); + //.ForMember(x => x.OrderItems, y => y.MapFrom(src => src.OrderItems.Select(x => x.ToDto()))); + } + + private void CreateAddressMap() + { + AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() + .IgnoreAllNonExisting() + .ForMember(x => x.Id, y => y.MapFrom(src => src.Id)); + //.ForMember(x => x.CountryName, + // y => y.MapFrom(src => src.Country.GetWithDefault(x => x, new Country()).Name)) + //.ForMember(x => x.StateProvinceName, + // y => y.MapFrom(src => src.StateProvince.GetWithDefault(x => x, new StateProvince()).Name)); + } + + private void CreateAddressDtoToEntityMap() + { + AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() + .IgnoreAllNonExisting() + .ForMember(x => x.Id, y => y.MapFrom(src => src.Id)); + } + + private void CreateCustomerForShoppingCartItemMapFromCustomer() + { + AutoMapperApiConfiguration.MapperConfigurationExpression + .CreateMap() + .IgnoreAllNonExisting() + .ForMember(x => x.Id, y => y.MapFrom(src => src.Id)); + //.ForMember(x => x.BillingAddress, + // y => y.MapFrom(src => src.BillingAddress.GetWithDefault(x => x, new Address()).ToDto())) + //.ForMember(x => x.ShippingAddress, + // y => y.MapFrom(src => src.ShippingAddress.GetWithDefault(x => x, new Address()).ToDto())) + //.ForMember(x => x.Addresses, + // y => y.MapFrom(src => + // src.Addresses.GetWithDefault(x => x, new List
()).Select(address => address.ToDto()))); + } + + private void CreateCustomerToDTOMap() + { + AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() + .IgnoreAllNonExisting() + .ForMember(x => x.Id, y => y.MapFrom(src => src.Id)); + //.ForMember(x => x.BillingAddress, + // y => y.MapFrom(src => src.BillingAddress.GetWithDefault(x => x, new Address()).ToDto())) + //.ForMember(x => x.ShippingAddress, + // y => y.MapFrom(src => src.ShippingAddress.GetWithDefault(x => x, new Address()).ToDto())) + //.ForMember(x => x.Addresses, + // y => + // y.MapFrom( + // src => + // src.Addresses.GetWithDefault(x => x, new List
()) + // .Select(address => address.ToDto()))) + //.ForMember(x => x.ShoppingCartItems, + // y => + // y.MapFrom( + // src => + // src.ShoppingCartItems.GetWithDefault(x => x, new List()) + // .Select(item => item.ToDto()))) + //.ForMember(x => x.RoleIds, y => y.MapFrom(src => src.CustomerRoles.Select(z => z.Id))); + } + + private void CreateCustomerToOrderCustomerDTOMap() + { + AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() + .IgnoreAllNonExisting(); + } + + private void CreateCustomerDTOToOrderCustomerDTOMap() + { + AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() + .IgnoreAllNonExisting(); + } + + private void CreateShoppingCartItemMap() + { + AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() + .IgnoreAllNonExisting(); + //.ForMember(x => x.CustomerDto, + // y => y.MapFrom(src => + // src.Customer.GetWithDefault(x => x, new Customer()).ToCustomerForShoppingCartItemDto())) + //.ForMember(x => x.ProductDto, + // y => y.MapFrom(src => src.Product.GetWithDefault(x => x, new Product()).ToDto())); + } + + private void CreateProductMap() + { + AutoMapperApiConfiguration.MapperConfigurationExpression.CreateMap() + .IgnoreAllNonExisting(); + //.ForMember(x => x.FullDescription, y => y.MapFrom(src => WebUtility.HtmlEncode(src.FullDescription))) + //.ForMember(x => x.Tags, + // y => y.MapFrom(src => src.ProductProductTagMappings.Select(x => x.ProductTag.Name))); + } + } +} diff --git a/Nop.Plugin.Api/AutoMapper/AutoMapperApiConfiguration.cs b/Nop.Plugin.Api/AutoMapper/AutoMapperApiConfiguration.cs index 93291b5..a0071e8 100644 --- a/Nop.Plugin.Api/AutoMapper/AutoMapperApiConfiguration.cs +++ b/Nop.Plugin.Api/AutoMapper/AutoMapperApiConfiguration.cs @@ -9,8 +9,9 @@ public static class AutoMapperApiConfiguration private static IMapper s_mapper; private static readonly object s_mapperLockObject = new object(); - public static MapperConfigurationExpression MapperConfigurationExpression => s_mapperConfigurationExpression ?? - (s_mapperConfigurationExpression = new MapperConfigurationExpression()); + public static MapperConfigurationExpression MapperConfigurationExpression => + s_mapperConfigurationExpression ?? + (s_mapperConfigurationExpression = new MapperConfigurationExpression()); public static IMapper Mapper { @@ -43,4 +44,4 @@ public static TDestination MapTo(this TSource source, TDe return Mapper.Map(source, destination); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Configuration/ApiConfiguration.cs b/Nop.Plugin.Api/Configuration/ApiConfiguration.cs new file mode 100644 index 0000000..546ceda --- /dev/null +++ b/Nop.Plugin.Api/Configuration/ApiConfiguration.cs @@ -0,0 +1,9 @@ +namespace Nop.Plugin.Api.Configuration +{ + public class ApiConfiguration + { + public int AllowedClockSkewInMinutes { get; set; } = 5; + + public string SecurityKey { get; set; } = "NowIsTheTimeForAllGoodMenToComeToTheAideOfTheirCountry"; + } +} diff --git a/Nop.Plugin.Api/Configuration/ApplicationPartsLogger.cs b/Nop.Plugin.Api/Configuration/ApplicationPartsLogger.cs new file mode 100644 index 0000000..d27c751 --- /dev/null +++ b/Nop.Plugin.Api/Configuration/ApplicationPartsLogger.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.ApplicationParts; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Nop.Plugin.Api.Configuration +{ + public class ApplicationPartsLogger : IHostedService + { + private readonly ILogger _logger; + private readonly ApplicationPartManager _partManager; + + public ApplicationPartsLogger(ILogger logger, ApplicationPartManager partManager) + { + _logger = logger; + _partManager = partManager; + } + + public Task StartAsync(CancellationToken cancellationToken) + { + // Get the names of all the application parts. This is the short assembly name for AssemblyParts + var applicationParts = _partManager.ApplicationParts.Select(x => x.Name); + + // Create a controller feature, and populate it from the application parts + var controllerFeature = new ControllerFeature(); + _partManager.PopulateFeature(controllerFeature); + + // Get the names of all of the controllers + var controllers = controllerFeature.Controllers.Select(x => x.Name); + + // Log the application parts and controllers + _logger.LogInformation("Found the following application parts: '{ApplicationParts}' with the following controllers: '{Controllers}'", + string.Join(", ", applicationParts), string.Join(", ", controllers)); + + return Task.CompletedTask; + } + + // Required by the interface + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + } +} diff --git a/Nop.Plugin.Api/Constants/Configurations.cs b/Nop.Plugin.Api/Constants/Configurations.cs deleted file mode 100644 index 2c3300d..0000000 --- a/Nop.Plugin.Api/Constants/Configurations.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace Nop.Plugin.Api.Constants -{ - public class Configurations - { - // time is in seconds (10 years = 315360000 seconds) and should not exceed 2038 year - // https://stackoverflow.com/questions/43593074/jwt-validation-fails/43605820 - public const int DefaultAccessTokenExpiration = 315360000; - public const int DefaultRefreshTokenExpiration = int.MaxValue; - public const int DefaultLimit = 50; - public const int DefaultPageValue = 1; - public const int DefaultSinceId = 0; - public const int DefaultCustomerId = 0; - public const string DefaultOrder = "Id"; - public const int MaxLimit = 250; - public const int MinLimit = 1; - public const string PublishedStatus = "published"; - public const string UnpublishedStatus = "unpublished"; - public const string AnyStatus = "any"; - public const string JsonTypeMapsPattern = "json.maps"; - - public const string NEWSLETTER_SUBSCRIBERS_KEY = "Nop.api.newslettersubscribers"; - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Constants/Plugin.cs b/Nop.Plugin.Api/Constants/Plugin.cs deleted file mode 100644 index 6850942..0000000 --- a/Nop.Plugin.Api/Constants/Plugin.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Nop.Plugin.Api.Constants -{ - public class Plugin - { - public const string SystemName = "Nop.Plugin.Api"; - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Constants/ViewNames.cs b/Nop.Plugin.Api/Constants/ViewNames.cs deleted file mode 100644 index 326d2b1..0000000 --- a/Nop.Plugin.Api/Constants/ViewNames.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Nop.Plugin.Api.Constants -{ - public class ViewNames - { - public const string AdminApiSettings = "~/Plugins/Nop.Plugin.Api/Views/Settings.cshtml"; - public const string AdminApiClientsCreateOrUpdate = "~/Plugins/Nop.Plugin.Api/Views/Clients/CreateOrUpdate.cshtml"; - public const string AdminApiClientsSettings = "~/Plugins/Nop.Plugin.Api/Views/Clients/ClientSettings.cshtml"; - public const string AdminApiClientsList = "~/Plugins/Nop.Plugin.Api/Views/Clients/List.cshtml"; - public const string AdminApiClientsCreate = "~/Plugins/Nop.Plugin.Api/Views/Clients/Create.cshtml"; - public const string AdminApiClientsEdit = "~/Plugins/Nop.Plugin.Api/Views/Clients/Edit.cshtml"; - public const string AdminLayout = "_AdminLayout"; - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Constants/WebHookNames.cs b/Nop.Plugin.Api/Constants/WebHookNames.cs deleted file mode 100644 index 9738e94..0000000 --- a/Nop.Plugin.Api/Constants/WebHookNames.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace Nop.Plugin.Api.Constants -{ - public static class WebHookNames - { - public const string FiltersGetAction = "FiltersGetAction"; - - public const string GetWebhookByIdAction = "GetWebHookByIdAction"; - - public const string CustomersCreate = "customers/create"; - public const string CustomersUpdate = "customers/update"; - public const string CustomersDelete = "customers/delete"; - - public const string ProductsCreate = "products/create"; - public const string ProductsUpdate = "products/update"; - public const string ProductsDelete = "products/delete"; - public const string ProductsUnmap = "products/unmap"; - - public const string CategoriesCreate = "categories/create"; - public const string CategoriesUpdate = "categories/update"; - public const string CategoriesDelete = "categories/delete"; - public const string CategoriesUnmap = "categories/unmap"; - - public const string OrdersCreate = "orders/create"; - public const string OrdersUpdate = "orders/update"; - public const string OrdersDelete = "orders/delete"; - - public const string ProductCategoryMapsCreate = "product_category_maps/create"; - public const string ProductCategoryMapsUpdate = "product_category_maps/update"; - public const string ProductCategoryMapsDelete = "product_category_maps/delete"; - - public const string StoresUpdate = "stores/update"; - - public const string LanguagesCreate = "languages/create"; - public const string LanguagesUpdate = "languages/update"; - public const string LanguagesDelete = "languages/delete"; - - public const string NewsLetterSubscriptionCreate = "news_letter_subscription/create"; - public const string NewsLetterSubscriptionUpdate = "news_letter_subscription/update"; - public const string NewsLetterSubscriptionDelete = "news_letter_subscription/delete"; - } -} diff --git a/Nop.Plugin.Api/Controllers/Admin/ManageClientsAdminController.cs b/Nop.Plugin.Api/Controllers/Admin/ManageClientsAdminController.cs deleted file mode 100644 index dff0215..0000000 --- a/Nop.Plugin.Api/Controllers/Admin/ManageClientsAdminController.cs +++ /dev/null @@ -1,123 +0,0 @@ -using Nop.Services.Messages; - -namespace Nop.Plugin.Api.Controllers.Admin -{ - using System.Linq; - using Microsoft.AspNetCore.Mvc; - using Constants; - using Nop.Services.Localization; - using Web.Framework; - using Nop.Web.Framework.Controllers; - using Web.Framework.Mvc.Filters; - using Models; - using Services; - using System; - using Nop.Plugin.Api.Kendoui; - - [AuthorizeAdmin] - [Area(AreaNames.Admin)] - [Route("admin/manageClientsAdmin/")] - public class ManageClientsAdminController : BasePluginController - { - private readonly IClientService _clientService; - private readonly ILocalizationService _localizationService; - private readonly INotificationService _notificationService; - - public ManageClientsAdminController(ILocalizationService localizationService, IClientService clientService, INotificationService notificationService) - { - _localizationService = localizationService; - _clientService = clientService; - _notificationService = notificationService; - } - - [HttpGet] - [Route("list")] - public ActionResult List() - { - return View(ViewNames.AdminApiClientsList); - } - - [HttpPost] - [Route("list")] - public ActionResult List(DataSourceRequest command) - { - var gridModel = _clientService.GetAllClients(); - - var grids = new DataSourceResult() - { - Data = gridModel, - Total = gridModel.Count() - }; - - return Json(grids); - } - - [HttpGet] - [Route("create")] - public ActionResult Create() - { - var clientModel = new ClientApiModel - { - Enabled = true, - ClientSecret = Guid.NewGuid().ToString(), - ClientId = Guid.NewGuid().ToString(), - AccessTokenLifetime = Configurations.DefaultAccessTokenExpiration, - RefreshTokenLifetime = Configurations.DefaultRefreshTokenExpiration - }; - - return View(ViewNames.AdminApiClientsCreate, clientModel); - } - - [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")] - [Route("create")] - public ActionResult Create(ClientApiModel model, bool continueEditing) - { - if (ModelState.IsValid) - { - var clientId = _clientService.InsertClient(model); - - _notificationService.SuccessNotification(_localizationService.GetResource("Plugins.Api.Admin.Client.Created")); - - return continueEditing ? RedirectToAction("Edit", new { id = clientId }) : RedirectToAction("List"); - } - - return RedirectToAction("List"); - } - - [HttpGet] - [Route("edit/{id}")] - public IActionResult Edit(int id) - { - var clientModel = _clientService.FindClientByIdAsync(id); - - return View(ViewNames.AdminApiClientsEdit, clientModel); - } - - [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")] - [Route("edit/{id}")] - public IActionResult Edit(ClientApiModel model, bool continueEditing) - { - if (ModelState.IsValid) - { - _clientService.UpdateClient(model); - - _notificationService.SuccessNotification(_localizationService.GetResource("Plugins.Api.Admin.Client.Edit")); - - return continueEditing ? RedirectToAction("Edit", new { id = model.Id }) : RedirectToAction("List"); - } - - return RedirectToAction("List"); - } - - [HttpPost, ActionName("Delete")] - [Route("delete/{id}")] - public IActionResult DeleteConfirmed(int id) - { - _clientService.DeleteClient(id); - - _notificationService.SuccessNotification(_localizationService.GetResource("Plugins.Api.Admin.Client.Deleted")); - - return RedirectToAction("List"); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Controllers/BaseApiController.cs b/Nop.Plugin.Api/Controllers/BaseApiController.cs index 85ed195..0692d36 100644 --- a/Nop.Plugin.Api/Controllers/BaseApiController.cs +++ b/Nop.Plugin.Api/Controllers/BaseApiController.cs @@ -1,11 +1,15 @@ using System.Collections.Generic; using System.Linq; using System.Net; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; using Nop.Core; using Nop.Core.Domain.Security; using Nop.Core.Domain.Stores; -using Nop.Plugin.Api.DTOs.Errors; +using Nop.Plugin.Api.DTO.Errors; using Nop.Plugin.Api.JSON.ActionResults; +using Nop.Plugin.Api.JSON.Serializers; using Nop.Services.Customers; using Nop.Services.Discounts; using Nop.Services.Localization; @@ -13,31 +17,32 @@ using Nop.Services.Media; using Nop.Services.Security; using Nop.Services.Stores; -using Microsoft.AspNetCore.Mvc; +using Nop.Web.Framework.Controllers; namespace Nop.Plugin.Api.Controllers { - using JSON.Serializers; - + [Authorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] + [ApiController] public class BaseApiController : Controller { - protected readonly IJsonFieldsSerializer JsonFieldsSerializer; protected readonly IAclService AclService; + protected readonly ICustomerActivityService CustomerActivityService; protected readonly ICustomerService CustomerService; - protected readonly IStoreMappingService StoreMappingService; - protected readonly IStoreService StoreService; protected readonly IDiscountService DiscountService; - protected readonly ICustomerActivityService CustomerActivityService; + protected readonly IJsonFieldsSerializer JsonFieldsSerializer; protected readonly ILocalizationService LocalizationService; protected readonly IPictureService PictureService; + protected readonly IStoreMappingService StoreMappingService; + protected readonly IStoreService StoreService; - public BaseApiController(IJsonFieldsSerializer jsonFieldsSerializer, - IAclService aclService, - ICustomerService customerService, - IStoreMappingService storeMappingService, - IStoreService storeService, - IDiscountService discountService, - ICustomerActivityService customerActivityService, + public BaseApiController( + IJsonFieldsSerializer jsonFieldsSerializer, + IAclService aclService, + ICustomerService customerService, + IStoreMappingService storeMappingService, + IStoreService storeService, + IDiscountService discountService, + ICustomerActivityService customerActivityService, ILocalizationService localizationService, IPictureService pictureService) { @@ -52,16 +57,20 @@ public BaseApiController(IJsonFieldsSerializer jsonFieldsSerializer, PictureService = pictureService; } - protected IActionResult Error(HttpStatusCode statusCode = (HttpStatusCode)422, string propertyKey = "", string errorMessage = "") + [Route("/api/error/{statusCode}/{errorMessage}")] + public IActionResult Error(HttpStatusCode statusCode = (HttpStatusCode)422, string propertyKey = "", string errorMessage = "") { var errors = new Dictionary>(); if (!string.IsNullOrEmpty(errorMessage) && !string.IsNullOrEmpty(propertyKey)) { - var errorsList = new List() {errorMessage}; + var errorsList = new List + { + errorMessage + }; errors.Add(propertyKey, errorsList); } - + foreach (var item in ModelState) { var errorMessages = item.Value.Errors.Select(x => x.ErrorMessage); @@ -69,7 +78,7 @@ protected IActionResult Error(HttpStatusCode statusCode = (HttpStatusCode)422, s var validErrorMessages = new List(); validErrorMessages.AddRange(errorMessages.Where(message => !string.IsNullOrEmpty(message))); - + if (validErrorMessages.Count > 0) { if (errors.ContainsKey(item.Key)) @@ -83,7 +92,7 @@ protected IActionResult Error(HttpStatusCode statusCode = (HttpStatusCode)422, s } } - var errorsRootObject = new ErrorsRootObject() + var errorsRootObject = new ErrorsRootObject { Errors = errors }; @@ -93,7 +102,7 @@ protected IActionResult Error(HttpStatusCode statusCode = (HttpStatusCode)422, s return new ErrorActionResult(errorsJson, statusCode); } - protected void UpdateAclRoles(TEntity entity, List passedRoleIds) where TEntity: BaseEntity, IAclSupported + protected void UpdateAclRoles(TEntity entity, List passedRoleIds) where TEntity : BaseEntity, IAclSupported { if (passedRoleIds == null) { @@ -110,22 +119,28 @@ protected void UpdateAclRoles(TEntity entity, List passedRoleIds) { //new role if (existingAclRecords.Count(acl => acl.CustomerRoleId == customerRole.Id) == 0) + { AclService.InsertAclRecord(entity, customerRole.Id); + } } else { //remove role var aclRecordToDelete = existingAclRecords.FirstOrDefault(acl => acl.CustomerRoleId == customerRole.Id); if (aclRecordToDelete != null) + { AclService.DeleteAclRecord(aclRecordToDelete); + } } } } protected void UpdateStoreMappings(TEntity entity, List passedStoreIds) where TEntity : BaseEntity, IStoreMappingSupported { - if(passedStoreIds == null) + if (passedStoreIds == null) + { return; + } entity.LimitedToStores = passedStoreIds.Any(); @@ -137,16 +152,20 @@ protected void UpdateStoreMappings(TEntity entity, List passedStor { //new store if (existingStoreMappings.Count(sm => sm.StoreId == store.Id) == 0) + { StoreMappingService.InsertStoreMapping(entity, store.Id); + } } else { //remove store var storeMappingToDelete = existingStoreMappings.FirstOrDefault(sm => sm.StoreId == store.Id); if (storeMappingToDelete != null) + { StoreMappingService.DeleteStoreMapping(storeMappingToDelete); + } } } } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Controllers/CategoriesController.cs b/Nop.Plugin.Api/Controllers/CategoriesController.cs index 32e0870..b0b839e 100644 --- a/Nop.Plugin.Api/Controllers/CategoriesController.cs +++ b/Nop.Plugin.Api/Controllers/CategoriesController.cs @@ -2,47 +2,45 @@ using System.Collections.Generic; using System.Linq; using System.Net; +using Microsoft.AspNetCore.Mvc; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Discounts; using Nop.Core.Domain.Media; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; -using Nop.Plugin.Api.DTOs.Categories; -using Nop.Plugin.Api.Models.CategoriesParameters; -using Nop.Plugin.Api.Services; -using Nop.Services.Catalog; -using Nop.Services.Localization; -using Nop.Services.Logging; -using Nop.Services.Seo; using Nop.Plugin.Api.Delta; -using Nop.Plugin.Api.DTOs.Images; +using Nop.Plugin.Api.DTO.Categories; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.Images; using Nop.Plugin.Api.Factories; +using Nop.Plugin.Api.Helpers; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.JSON.ActionResults; +using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.ModelBinders; +using Nop.Plugin.Api.Models.CategoriesParameters; +using Nop.Plugin.Api.Services; +using Nop.Services.Catalog; using Nop.Services.Customers; using Nop.Services.Discounts; +using Nop.Services.Localization; +using Nop.Services.Logging; using Nop.Services.Media; using Nop.Services.Security; +using Nop.Services.Seo; using Nop.Services.Stores; -using Nop.Plugin.Api.Helpers; -using Microsoft.AspNetCore.Mvc; namespace Nop.Plugin.Api.Controllers { - using Microsoft.AspNetCore.Authentication.JwtBearer; - using DTOs.Errors; - using JSON.Serializers; - - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class CategoriesController : BaseApiController { private readonly ICategoryApiService _categoryApiService; private readonly ICategoryService _categoryService; - private readonly IUrlRecordService _urlRecordService; - private readonly IFactory _factory; private readonly IDTOHelper _dtoHelper; + private readonly IFactory _factory; + private readonly IUrlRecordService _urlRecordService; - public CategoriesController(ICategoryApiService categoryApiService, + public CategoriesController( + ICategoryApiService categoryApiService, IJsonFieldsSerializer jsonFieldsSerializer, ICategoryService categoryService, IUrlRecordService urlRecordService, @@ -55,7 +53,8 @@ public CategoriesController(ICategoryApiService categoryApiService, IAclService aclService, ICustomerService customerService, IFactory factory, - IDTOHelper dtoHelper) : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, localizationService,pictureService) + IDTOHelper dtoHelper) : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, + customerActivityService, localizationService, pictureService) { _categoryApiService = categoryApiService; _categoryService = categoryService; @@ -65,44 +64,40 @@ public CategoriesController(ICategoryApiService categoryApiService, } /// - /// Receive a list of all Categories + /// Receive a list of all Categories /// /// OK /// Bad Request /// Unauthorized [HttpGet] - [Route("/api/categories")] - [ProducesResponseType(typeof(CategoriesRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [Route("/api/categories")] + [ProducesResponseType(typeof(CategoriesRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetCategories(CategoriesParametersModel parameters) { - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "limit", "Invalid limit parameter"); } - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "Invalid page parameter"); } var allCategories = _categoryApiService.GetCategories(parameters.Ids, parameters.CreatedAtMin, parameters.CreatedAtMax, - parameters.UpdatedAtMin, parameters.UpdatedAtMax, - parameters.Limit, parameters.Page, parameters.SinceId, - parameters.ProductId, parameters.PublishedStatus) + parameters.UpdatedAtMin, parameters.UpdatedAtMax, + parameters.Limit, parameters.Page, parameters.SinceId, + parameters.ProductId, parameters.PublishedStatus) .Where(c => StoreMappingService.Authorize(c)); - IList categoriesAsDtos = allCategories.Select(category => - { - return _dtoHelper.PrepareCategoryDTO(category); - - }).ToList(); + IList categoriesAsDtos = allCategories.Select(category => _dtoHelper.PrepareCategoryDTO(category)).ToList(); - var categoriesRootObject = new CategoriesRootObject() - { - Categories = categoriesAsDtos - }; + var categoriesRootObject = new CategoriesRootObject + { + Categories = categoriesAsDtos + }; var json = JsonFieldsSerializer.Serialize(categoriesRootObject, parameters.Fields); @@ -110,15 +105,15 @@ public IActionResult GetCategories(CategoriesParametersModel parameters) } /// - /// Receive a count of all Categories + /// Receive a count of all Categories /// /// OK /// Unauthorized [HttpGet] [Route("/api/categories/count")] - [ProducesResponseType(typeof(CategoriesCountRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(CategoriesCountRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetCategoriesCount(CategoriesCountParametersModel parameters) { @@ -126,16 +121,16 @@ public IActionResult GetCategoriesCount(CategoriesCountParametersModel parameter parameters.UpdatedAtMin, parameters.UpdatedAtMax, parameters.PublishedStatus, parameters.ProductId); - var categoriesCountRootObject = new CategoriesCountRootObject() - { - Count = allCategoriesCount - }; + var categoriesCountRootObject = new CategoriesCountRootObject + { + Count = allCategoriesCount + }; return Ok(categoriesCountRootObject); } /// - /// Retrieve category by spcified id + /// Retrieve category by specified id /// /// Id of the category /// Fields from the category you want your json to contain @@ -144,9 +139,9 @@ public IActionResult GetCategoriesCount(CategoriesCountParametersModel parameter /// Unauthorized [HttpGet] [Route("/api/categories/{id}")] - [ProducesResponseType(typeof(CategoriesRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(CategoriesRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetCategoryById(int id, string fields = "") { @@ -172,14 +167,16 @@ public IActionResult GetCategoryById(int id, string fields = "") return new RawJsonActionResult(json); } - + [HttpPost] [Route("/api/categories")] - [ProducesResponseType(typeof(CategoriesRootObject), (int)HttpStatusCode.OK)] + [ProducesResponseType(typeof(CategoriesRootObject), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - public IActionResult CreateCategory([ModelBinder(typeof(JsonModelBinder))] Delta categoryDelta) + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + public IActionResult CreateCategory( + [ModelBinder(typeof(JsonModelBinder))] + Delta categoryDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -192,7 +189,7 @@ public IActionResult CreateCategory([ModelBinder(typeof(JsonModelBinder))] Delta categoryDelta) + [ModelBinder(typeof(JsonModelBinder))] + Delta categoryDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -277,7 +275,6 @@ public IActionResult UpdateCategory( //search engine name if (categoryDelta.Dto.SeName != null) { - var seName = _urlRecordService.ValidateSeName(category, categoryDelta.Dto.SeName, category.Name, true); _urlRecordService.SaveSlug(category, seName, 0); } @@ -285,7 +282,7 @@ public IActionResult UpdateCategory( _categoryService.UpdateCategory(category); CustomerActivityService.InsertActivity("UpdateCategory", - LocalizationService.GetResource("ActivityLog.UpdateCategory"), category); + LocalizationService.GetResource("ActivityLog.UpdateCategory"), category); var categoryDto = _dtoHelper.PrepareCategoryDTO(category); @@ -300,10 +297,10 @@ public IActionResult UpdateCategory( [HttpDelete] [Route("/api/categories/{id}")] - [ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(void), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] [GetRequestsErrorInterceptorActionFilter] public IActionResult DeleteCategory(int id) { @@ -331,7 +328,9 @@ private void UpdatePicture(Category categoryEntityToUpdate, ImageDto imageDto) { // no image specified then do nothing if (imageDto == null) + { return; + } Picture updatedPicture; var currentCategoryPicture = PictureService.GetPictureById(categoryEntityToUpdate.PictureId); @@ -365,26 +364,33 @@ private void UpdatePicture(Category categoryEntityToUpdate, ImageDto imageDto) private void UpdateDiscounts(Category category, List passedDiscountIds) { - if(passedDiscountIds == null) + if (passedDiscountIds == null) + { return; + } var allDiscounts = DiscountService.GetAllDiscounts(DiscountType.AssignedToCategories, showHidden: true); + var appliedCategoryDiscount = DiscountService.GetAppliedDiscounts(category); foreach (var discount in allDiscounts) { if (passedDiscountIds.Contains(discount.Id)) { //new discount - if (category.AppliedDiscounts.Count(d => d.Id == discount.Id) == 0) - category.AppliedDiscounts.Add(discount); + if (appliedCategoryDiscount.Count(d => d.Id == discount.Id) == 0) + { + appliedCategoryDiscount.Add(discount); + } } else { //remove discount - if (category.AppliedDiscounts.Count(d => d.Id == discount.Id) > 0) - category.AppliedDiscounts.Remove(discount); + if (appliedCategoryDiscount.Count(d => d.Id == discount.Id) > 0) + { + appliedCategoryDiscount.Remove(discount); + } } } _categoryService.UpdateCategory(category); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Controllers/CustomerRolesController.cs b/Nop.Plugin.Api/Controllers/CustomerRolesController.cs index 1c054db..aa5dd1e 100644 --- a/Nop.Plugin.Api/Controllers/CustomerRolesController.cs +++ b/Nop.Plugin.Api/Controllers/CustomerRolesController.cs @@ -1,8 +1,12 @@ using System.Collections.Generic; using System.Linq; +using System.Net; +using Microsoft.AspNetCore.Mvc; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.DTOs.CustomerRoles; +using Nop.Plugin.Api.DTO.CustomerRoles; +using Nop.Plugin.Api.DTO.Errors; using Nop.Plugin.Api.JSON.ActionResults; +using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.MappingExtensions; using Nop.Services.Customers; using Nop.Services.Discounts; @@ -14,48 +18,41 @@ namespace Nop.Plugin.Api.Controllers { - using System.Net; - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Mvc; - using DTOs.Errors; - using JSON.Serializers; - - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class CustomerRolesController : BaseApiController { public CustomerRolesController( IJsonFieldsSerializer jsonFieldsSerializer, - IAclService aclService, - ICustomerService customerService, - IStoreMappingService storeMappingService, - IStoreService storeService, + IAclService aclService, + ICustomerService customerService, + IStoreMappingService storeMappingService, + IStoreService storeService, IDiscountService discountService, - ICustomerActivityService customerActivityService, + ICustomerActivityService customerActivityService, ILocalizationService localizationService, - IPictureService pictureService) - : base(jsonFieldsSerializer, - aclService, - customerService, - storeMappingService, - storeService, - discountService, - customerActivityService, - localizationService, - pictureService) + IPictureService pictureService) + : base(jsonFieldsSerializer, + aclService, + customerService, + storeMappingService, + storeService, + discountService, + customerActivityService, + localizationService, + pictureService) { } /// - /// Retrieve all customer roles + /// Retrieve all customer roles /// /// Fields from the customer role you want your json to contain /// OK /// Unauthorized [HttpGet] [Route("/api/customer_roles")] - [ProducesResponseType(typeof(CustomerRolesRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(CustomerRolesRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetAllCustomerRoles(string fields = "") { @@ -63,10 +60,10 @@ public IActionResult GetAllCustomerRoles(string fields = "") IList customerRolesAsDto = allCustomerRoles.Select(role => role.ToDto()).ToList(); - var customerRolesRootObject = new CustomerRolesRootObject() - { - CustomerRoles = customerRolesAsDto - }; + var customerRolesRootObject = new CustomerRolesRootObject + { + CustomerRoles = customerRolesAsDto + }; var json = JsonFieldsSerializer.Serialize(customerRolesRootObject, fields); diff --git a/Nop.Plugin.Api/Controllers/CustomersController.cs b/Nop.Plugin.Api/Controllers/CustomersController.cs index 0b9a81c..83b0a7c 100644 --- a/Nop.Plugin.Api/Controllers/CustomersController.cs +++ b/Nop.Plugin.Api/Controllers/CustomersController.cs @@ -1,17 +1,19 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Net; +using Microsoft.AspNetCore.Mvc; using Nop.Core.Domain.Customers; using Nop.Core.Infrastructure; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.Delta; -using Nop.Plugin.Api.DTOs; -using Nop.Plugin.Api.DTOs.Customers; +using Nop.Plugin.Api.DTO; +using Nop.Plugin.Api.DTO.Customers; +using Nop.Plugin.Api.DTO.Errors; using Nop.Plugin.Api.Factories; using Nop.Plugin.Api.Helpers; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.JSON.ActionResults; +using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.MappingExtensions; using Nop.Plugin.Api.ModelBinders; using Nop.Plugin.Api.Models.CustomersParameters; @@ -29,43 +31,24 @@ namespace Nop.Plugin.Api.Controllers { - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Mvc; - using DTOs.Errors; - using JSON.Serializers; - - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class CustomersController : BaseApiController { + private readonly ICountryService _countryService; private readonly ICustomerApiService _customerApiService; private readonly ICustomerRolesHelper _customerRolesHelper; - private readonly IGenericAttributeService _genericAttributeService; private readonly IEncryptionService _encryptionService; - private readonly ICountryService _countryService; + private readonly IFactory _factory; + private readonly IGenericAttributeService _genericAttributeService; + private readonly ILanguageService _languageService; private readonly IMappingHelper _mappingHelper; private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService; - private readonly ILanguageService _languageService; - private readonly IFactory _factory; // We resolve the customer settings this way because of the tests. // The auto mocking does not support concreate types as dependencies. It supports only interfaces. private CustomerSettings _customerSettings; - private CustomerSettings CustomerSettings - { - get - { - if (_customerSettings == null) - { - _customerSettings = EngineContext.Current.Resolve(); - } - - return _customerSettings; - } - } - public CustomersController( - ICustomerApiService customerApiService, + ICustomerApiService customerApiService, IJsonFieldsSerializer jsonFieldsSerializer, IAclService aclService, ICustomerService customerService, @@ -77,12 +60,13 @@ public CustomersController( ICustomerRolesHelper customerRolesHelper, IGenericAttributeService genericAttributeService, IEncryptionService encryptionService, - IFactory factory, - ICountryService countryService, - IMappingHelper mappingHelper, + IFactory factory, + ICountryService countryService, + IMappingHelper mappingHelper, INewsLetterSubscriptionService newsLetterSubscriptionService, - IPictureService pictureService, ILanguageService languageService) : - base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, localizationService,pictureService) + IPictureService pictureService, ILanguageService languageService) : + base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, + localizationService, pictureService) { _customerApiService = customerApiService; _factory = factory; @@ -95,8 +79,21 @@ public CustomersController( _customerRolesHelper = customerRolesHelper; } + private CustomerSettings CustomerSettings + { + get + { + if (_customerSettings == null) + { + _customerSettings = EngineContext.Current.Resolve(); + } + + return _customerSettings; + } + } + /// - /// Retrieve all customers of a shop + /// Retrieve all customers of a shop /// /// OK /// Bad request @@ -109,19 +106,22 @@ public CustomersController( [GetRequestsErrorInterceptorActionFilter] public IActionResult GetCustomers(CustomersParametersModel parameters) { - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "limit", "Invalid limit parameter"); } - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "Invalid request parameters"); } - var allCustomers = _customerApiService.GetCustomersDtos(parameters.CreatedAtMin, parameters.CreatedAtMax, parameters.Limit, parameters.Page, parameters.SinceId); + var allCustomers = + + _customerApiService.GetCustomersDtos(parameters.CreatedAtMin, parameters.CreatedAtMax, parameters.Limit, parameters.Page, parameters.SinceId); - var customersRootObject = new CustomersRootObject() + + var customersRootObject = new CustomersRootObject { Customers = allCustomers }; @@ -132,7 +132,7 @@ public IActionResult GetCustomers(CustomersParametersModel parameters) } /// - /// Retrieve customer by spcified id + /// Retrieve customer by spcified id /// /// Id of the customer /// Fields from the customer you want your json to contain @@ -159,7 +159,7 @@ public IActionResult GetCustomerById(int id, string fields = "") { return Error(HttpStatusCode.NotFound, "customer", "not found"); } - + var customersRootObject = new CustomersRootObject(); customersRootObject.Customers.Add(customer); @@ -170,7 +170,7 @@ public IActionResult GetCustomerById(int id, string fields = "") /// - /// Get a count of all customers + /// Get a count of all customers /// /// OK /// Unauthorized @@ -183,7 +183,7 @@ public IActionResult GetCustomersCount() { var allCustomersCount = _customerApiService.GetCustomersCount(); - var customersCountRootObject = new CustomersCountRootObject() + var customersCountRootObject = new CustomersCountRootObject { Count = allCustomersCount }; @@ -192,7 +192,7 @@ public IActionResult GetCustomersCount() } /// - /// Search for customers matching supplied query + /// Search for customers matching supplied query /// /// OK /// Bad Request @@ -204,19 +204,19 @@ public IActionResult GetCustomersCount() [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] public IActionResult Search(CustomersSearchParametersModel parameters) { - if (parameters.Limit <= Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit <= Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { - return Error(HttpStatusCode.BadRequest, "limit" ,"Invalid limit parameter"); + return Error(HttpStatusCode.BadRequest, "limit", "Invalid limit parameter"); } if (parameters.Page <= 0) { return Error(HttpStatusCode.BadRequest, "page", "Invalid page parameter"); } - + var customersDto = _customerApiService.Search(parameters.Query, parameters.Order, parameters.Page, parameters.Limit); - var customersRootObject = new CustomersRootObject() + var customersRootObject = new CustomersRootObject { Customers = customersDto }; @@ -226,13 +226,27 @@ public IActionResult Search(CustomersSearchParametersModel parameters) return new RawJsonActionResult(json); } + [HttpPost] + [Route("/api/customers2")] + [ProducesResponseType(typeof(CustomersRootObject), (int)HttpStatusCode.OK)] + [ProducesResponseType(typeof(ErrorsRootObject), 422)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + public IActionResult CreateCustomer1() + { + return Ok(); + } + + [HttpPost] [Route("/api/customers")] [ProducesResponseType(typeof(CustomersRootObject), (int)HttpStatusCode.OK)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - public IActionResult CreateCustomer([ModelBinder(typeof(JsonModelBinder))] Delta customerDelta) + public IActionResult CreateCustomer( + [ModelBinder(typeof(JsonModelBinder))] + Delta customerDelta) { + // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { @@ -253,15 +267,16 @@ public IActionResult CreateCustomer([ModelBinder(typeof(JsonModelBinder))] Delta customerDelta) + public IActionResult UpdateCustomer( + [ModelBinder(typeof(JsonModelBinder))] + Delta customerDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -339,7 +356,7 @@ public IActionResult UpdateCustomer([ModelBinder(typeof(JsonModelBinder 0) { - var currentCustomerAddresses = currentCustomer.Addresses.ToDictionary(address => address.Id, address => address); + var currentCustomerAddresses = CustomerService.GetAddressesByCustomerId(currentCustomer.Id).ToDictionary(address => address.Id, address => address); foreach (var passedAddress in customerDelta.Dto.Addresses) { @@ -351,7 +368,7 @@ public IActionResult UpdateCustomer([ModelBinder(typeof(JsonModelBinder x.Key == "FirstName"); + .FirstOrDefault(x => x.Key == "FirstName"); if (firstNameGenericAttribute != null) { @@ -394,7 +411,7 @@ public IActionResult UpdateCustomer([ModelBinder(typeof(JsonModelBinder x.Key == "LastName"); + .FirstOrDefault(x => x.Key == "LastName"); if (lastNameGenericAttribute != null) { @@ -402,7 +419,7 @@ public IActionResult UpdateCustomer([ModelBinder(typeof(JsonModelBinder x.Key == "LanguageId"); + .FirstOrDefault(x => x.Key == "LanguageId"); if (languageIdGenericAttribute != null) { @@ -449,12 +466,14 @@ public IActionResult DeleteCustomer(int id) { var subscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, store.Id); if (subscription != null) + { _newsLetterSubscriptionService.DeleteNewsLetterSubscription(subscription); + } } //activity log CustomerActivityService.InsertActivity("DeleteCustomer", LocalizationService.GetResource("ActivityLog.DeleteCustomer"), customer); - + return new RawJsonActionResult("{}"); } @@ -480,15 +499,16 @@ private void AddValidRoles(Delta customerDelta, Customer currentCus if (customerDelta.Dto.RoleIds.Contains(customerRole.Id)) { //new role - if (currentCustomer.CustomerCustomerRoleMappings.Count(mapping => mapping.CustomerRoleId == customerRole.Id) == 0) - currentCustomer.CustomerCustomerRoleMappings.Add(new CustomerCustomerRoleMapping { CustomerRole = customerRole }); + if (!CustomerService.IsInCustomerRole(currentCustomer, customerRole.Name)) + { + CustomerService.InsertCustomerRole(customerRole); + } } else { - if (currentCustomer.CustomerCustomerRoleMappings.Count(mapping => mapping.CustomerRoleId == customerRole.Id) > 0) + if (CustomerService.IsInCustomerRole(currentCustomer, customerRole.Name)) { - currentCustomer.CustomerCustomerRoleMappings - .Remove(currentCustomer.CustomerCustomerRoleMappings.FirstOrDefault(mapping => mapping.CustomerRoleId == customerRole.Id)); + CustomerService.DeleteCustomerRole(customerRole); } } } @@ -526,7 +546,7 @@ private void AddPassword(string newPassword, Customer customer) // TODO: call this method before inserting the customer. var customerPassword = new CustomerPassword { - Customer = customer, + CustomerId = customer.Id, PasswordFormat = CustomerSettings.DefaultPasswordFormat, CreatedOnUtc = DateTime.UtcNow }; @@ -554,8 +574,7 @@ private void AddPassword(string newPassword, Customer customer) CustomerService.InsertCustomerPassword(customerPassword); - // TODO: remove this. CustomerService.UpdateCustomer(customer); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Controllers/LanguagesController.cs b/Nop.Plugin.Api/Controllers/LanguagesController.cs index 98f6bd9..fbb0505 100644 --- a/Nop.Plugin.Api/Controllers/LanguagesController.cs +++ b/Nop.Plugin.Api/Controllers/LanguagesController.cs @@ -1,9 +1,13 @@ using System.Collections.Generic; using System.Linq; +using System.Net; +using Microsoft.AspNetCore.Mvc; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.DTOs.Languages; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.Languages; using Nop.Plugin.Api.Helpers; using Nop.Plugin.Api.JSON.ActionResults; +using Nop.Plugin.Api.JSON.Serializers; using Nop.Services.Customers; using Nop.Services.Discounts; using Nop.Services.Localization; @@ -14,19 +18,13 @@ namespace Nop.Plugin.Api.Controllers { - using System.Net; - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Mvc; - using DTOs.Errors; - using JSON.Serializers; - - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class LanguagesController : BaseApiController { - private ILanguageService _languageService; private readonly IDTOHelper _dtoHelper; + private readonly ILanguageService _languageService; - public LanguagesController(IJsonFieldsSerializer jsonFieldsSerializer, + public LanguagesController( + IJsonFieldsSerializer jsonFieldsSerializer, IAclService aclService, ICustomerService customerService, IStoreMappingService storeMappingService, @@ -38,41 +36,41 @@ public LanguagesController(IJsonFieldsSerializer jsonFieldsSerializer, ILanguageService languageService, IDTOHelper dtoHelper) : base(jsonFieldsSerializer, - aclService, - customerService, - storeMappingService, - storeService, - discountService, - customerActivityService, - localizationService, - pictureService) + aclService, + customerService, + storeMappingService, + storeService, + discountService, + customerActivityService, + localizationService, + pictureService) { _languageService = languageService; _dtoHelper = dtoHelper; } /// - /// Retrieve all languages + /// Retrieve all languages /// /// Fields from the language you want your json to contain /// OK /// Unauthorized [HttpGet] [Route("/api/languages")] - [ProducesResponseType(typeof(LanguagesRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(LanguagesRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetAllLanguages(string fields = "") { var allLanguages = _languageService.GetAllLanguages(); - IList languagesAsDto = allLanguages.Select(language => _dtoHelper.PrepateLanguageDto(language)).ToList(); + IList languagesAsDto = allLanguages.Select(language => _dtoHelper.PrepareLanguageDto(language)).ToList(); - var languagesRootObject = new LanguagesRootObject() - { - Languages = languagesAsDto - }; + var languagesRootObject = new LanguagesRootObject + { + Languages = languagesAsDto + }; var json = JsonFieldsSerializer.Serialize(languagesRootObject, fields); diff --git a/Nop.Plugin.Api/Controllers/ManufacturersController.cs b/Nop.Plugin.Api/Controllers/ManufacturersController.cs index d552b00..c1f0f9a 100644 --- a/Nop.Plugin.Api/Controllers/ManufacturersController.cs +++ b/Nop.Plugin.Api/Controllers/ManufacturersController.cs @@ -1,16 +1,19 @@ -using Microsoft.AspNetCore.Authentication.JwtBearer; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; using Microsoft.AspNetCore.Mvc; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Discounts; using Nop.Core.Domain.Media; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.Delta; -using Nop.Plugin.Api.DTOs.Errors; -using Nop.Plugin.Api.DTOs.Images; -using Nop.Plugin.Api.DTOs.Manufacturers; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.Images; +using Nop.Plugin.Api.DTO.Manufacturers; using Nop.Plugin.Api.Factories; using Nop.Plugin.Api.Helpers; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.JSON.ActionResults; using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.ModelBinders; @@ -25,37 +28,34 @@ using Nop.Services.Security; using Nop.Services.Seo; using Nop.Services.Stores; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; namespace Nop.Plugin.Api.Controllers { - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class ManufacturersController : BaseApiController { - private readonly IFactory _factory; private readonly IDTOHelper _dtoHelper; - private readonly IManufacturerService _manufacturerService; + private readonly IFactory _factory; private readonly IManufacturerApiService _manufacturerApiService; - private readonly IUrlRecordService _urlRecordService; + private readonly IManufacturerService _manufacturerService; + private readonly IUrlRecordService _urlRecordService; - public ManufacturersController(IJsonFieldsSerializer jsonFieldsSerializer, + public ManufacturersController( + IJsonFieldsSerializer jsonFieldsSerializer, IAclService aclService, - ICustomerService customerService, + ICustomerService customerService, IStoreMappingService storeMappingService, IStoreService storeService, IDiscountService discountService, ICustomerActivityService customerActivityService, ILocalizationService localizationService, - IPictureService pictureService, - IDTOHelper dtoHelper, + IPictureService pictureService, + IDTOHelper dtoHelper, IManufacturerService manufacturerService, IManufacturerApiService manufacturerApiService, IUrlRecordService urlRecordService, - IFactory factory) - : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, localizationService, pictureService) + IFactory factory) + : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, + localizationService, pictureService) { _dtoHelper = dtoHelper; _manufacturerService = manufacturerService; @@ -65,7 +65,7 @@ public ManufacturersController(IJsonFieldsSerializer jsonFieldsSerializer, } /// - /// Receive a list of all manufacturers + /// Receive a list of all manufacturers /// /// OK /// Bad Request @@ -77,25 +77,25 @@ public ManufacturersController(IJsonFieldsSerializer jsonFieldsSerializer, [GetRequestsErrorInterceptorActionFilter] public IActionResult GetManufacturers(ManufacturersParametersModel parameters) { - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "limit", "Invalid limit parameter"); } - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "Invalid page parameter"); } var allManufacturers = _manufacturerApiService.GetManufacturers(parameters.Ids, parameters.CreatedAtMin, parameters.CreatedAtMax, - parameters.UpdatedAtMin, parameters.UpdatedAtMax, - parameters.Limit, parameters.Page, parameters.SinceId, - parameters.ProductId, parameters.PublishedStatus, parameters.LanguageId) - .Where(c => StoreMappingService.Authorize(c)); + parameters.UpdatedAtMin, parameters.UpdatedAtMax, + parameters.Limit, parameters.Page, parameters.SinceId, + parameters.ProductId, parameters.PublishedStatus, parameters.LanguageId) + .Where(c => StoreMappingService.Authorize(c)); IList manufacturersAsDtos = allManufacturers.Select(manufacturer => _dtoHelper.PrepareManufacturerDto(manufacturer)).ToList(); - var manufacturersRootObject = new ManufacturersRootObject() + var manufacturersRootObject = new ManufacturersRootObject { Manufacturers = manufacturersAsDtos }; @@ -106,7 +106,7 @@ public IActionResult GetManufacturers(ManufacturersParametersModel parameters) } /// - /// Receive a count of all Manufacturers + /// Receive a count of all Manufacturers /// /// OK /// Unauthorized @@ -119,10 +119,10 @@ public IActionResult GetManufacturers(ManufacturersParametersModel parameters) public IActionResult GetManufacturersCount(ManufacturersCountParametersModel parameters) { var allManufacturersCount = _manufacturerApiService.GetManufacturersCount(parameters.CreatedAtMin, parameters.CreatedAtMax, - parameters.UpdatedAtMin, parameters.UpdatedAtMax, - parameters.PublishedStatus, parameters.ProductId); + parameters.UpdatedAtMin, parameters.UpdatedAtMax, + parameters.PublishedStatus, parameters.ProductId); - var manufacturersCountRootObject = new ManufacturersCountRootObject() + var manufacturersCountRootObject = new ManufacturersCountRootObject { Count = allManufacturersCount }; @@ -131,7 +131,7 @@ public IActionResult GetManufacturersCount(ManufacturersCountParametersModel par } /// - /// Retrieve manufacturer by spcified id + /// Retrieve manufacturer by spcified id /// /// Id of the manufacturer /// Fields from the manufacturer you want your json to contain @@ -175,7 +175,9 @@ public IActionResult GetManufacturerById(int id, string fields = "") [ProducesResponseType(typeof(ErrorsRootObject), 422)] [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - public IActionResult CreateManufacturer([ModelBinder(typeof(JsonModelBinder))] Delta manufacturerDelta) + public IActionResult CreateManufacturer( + [ModelBinder(typeof(JsonModelBinder))] + Delta manufacturerDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -188,7 +190,7 @@ public IActionResult CreateManufacturer([ModelBinder(typeof(JsonModelBinder))] Delta manufacturerDelta) + public IActionResult UpdateManufacturer( + [ModelBinder(typeof(JsonModelBinder))] + Delta manufacturerDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -272,7 +276,6 @@ public IActionResult UpdateManufacturer([ModelBinder(typeof(JsonModelBinder passedDiscountIds) { if (passedDiscountIds == null) + { return; + } var allDiscounts = DiscountService.GetAllDiscounts(DiscountType.AssignedToManufacturers, showHidden: true); foreach (var discount in allDiscounts) { + var appliedDiscounts = DiscountService.GetAppliedDiscounts(manufacturer); if (passedDiscountIds.Contains(discount.Id)) { //new discount - if (manufacturer.AppliedDiscounts.Count(d => d.Id == discount.Id) == 0) - manufacturer.AppliedDiscounts.Add(discount); + if (appliedDiscounts.Count(d => d.Id == discount.Id) == 0) + { + _manufacturerService.InsertDiscountManufacturerMapping( + new DiscountManufacturerMapping + { + DiscountId = discount.Id, + EntityId = manufacturer.Id + }); + } } else { //remove discount - if (manufacturer.AppliedDiscounts.Count(d => d.Id == discount.Id) > 0) - manufacturer.AppliedDiscounts.Remove(discount); + if (appliedDiscounts.Count(d => d.Id == discount.Id) > 0) + { + _manufacturerService.DeleteDiscountManufacturerMapping( + new DiscountManufacturerMapping + { + DiscountId = discount.Id, + EntityId = manufacturer.Id + }); + + } } } _manufacturerService.UpdateManufacturer(manufacturer); diff --git a/Nop.Plugin.Api/Controllers/NewsLetterSubscriptionController.cs b/Nop.Plugin.Api/Controllers/NewsLetterSubscriptionController.cs index 14fff2f..b74e460 100644 --- a/Nop.Plugin.Api/Controllers/NewsLetterSubscriptionController.cs +++ b/Nop.Plugin.Api/Controllers/NewsLetterSubscriptionController.cs @@ -1,16 +1,15 @@ using System.Linq; using System.Net; -using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Mvc; using Nop.Core; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; -using Nop.Plugin.Api.DTOs.Categories; -using Nop.Plugin.Api.DTOs.Errors; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.NewsLetterSubscriptions; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.JSON.ActionResults; using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.MappingExtensions; -using Nop.Plugin.Api.Models.CustomersParameters; +using Nop.Plugin.Api.Models.NewsLetterSubscriptionsParameters; using Nop.Plugin.Api.Services; using Nop.Services.Customers; using Nop.Services.Discounts; @@ -23,14 +22,14 @@ namespace Nop.Plugin.Api.Controllers { - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class NewsLetterSubscriptionController : BaseApiController { private readonly INewsLetterSubscriptionApiService _newsLetterSubscriptionApiService; - private readonly IStoreContext _storeContext; private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService; + private readonly IStoreContext _storeContext; - public NewsLetterSubscriptionController(IJsonFieldsSerializer jsonFieldsSerializer, + public NewsLetterSubscriptionController( + IJsonFieldsSerializer jsonFieldsSerializer, IAclService aclService, ICustomerService customerService, IStoreMappingService storeMappingService, @@ -41,7 +40,9 @@ public NewsLetterSubscriptionController(IJsonFieldsSerializer jsonFieldsSerializ IPictureService pictureService, INewsLetterSubscriptionApiService newsLetterSubscriptionApiService, IStoreContext storeContext, - INewsLetterSubscriptionService newsLetterSubscriptionService) : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, localizationService, pictureService) + INewsLetterSubscriptionService newsLetterSubscriptionService) : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, + storeService, discountService, customerActivityService, localizationService, + pictureService) { _newsLetterSubscriptionApiService = newsLetterSubscriptionApiService; _storeContext = storeContext; @@ -49,38 +50,38 @@ public NewsLetterSubscriptionController(IJsonFieldsSerializer jsonFieldsSerializ } /// - /// Receive a list of all NewsLetters + /// Receive a list of all NewsLetters /// /// OK /// Bad Request /// Unauthorized [HttpGet] [Route("/api/news_letter_subscriptions")] - [ProducesResponseType(typeof(NewsLetterSubscriptionsRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(NewsLetterSubscriptionsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetNewsLetterSubscriptions(NewsLetterSubscriptionsParametersModel parameters) { - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "limit", "Invalid limit parameter"); } - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "Invalid page parameter"); } var newsLetterSubscriptions = _newsLetterSubscriptionApiService.GetNewsLetterSubscriptions(parameters.CreatedAtMin, parameters.CreatedAtMax, - parameters.Limit, parameters.Page, parameters.SinceId, - parameters.OnlyActive); + parameters.Limit, parameters.Page, parameters.SinceId, + parameters.OnlyActive); var newsLetterSubscriptionsDtos = newsLetterSubscriptions.Select(nls => nls.ToDto()).ToList(); - var newsLetterSubscriptionsRootObject = new NewsLetterSubscriptionsRootObject() - { - NewsLetterSubscriptions = newsLetterSubscriptionsDtos - }; + var newsLetterSubscriptionsRootObject = new NewsLetterSubscriptionsRootObject + { + NewsLetterSubscriptions = newsLetterSubscriptionsDtos + }; var json = JsonFieldsSerializer.Serialize(newsLetterSubscriptionsRootObject, parameters.Fields); @@ -88,16 +89,16 @@ public IActionResult GetNewsLetterSubscriptions(NewsLetterSubscriptionsParameter } /// - /// Deactivate a NewsLetter subscriber by email + /// Deactivate a NewsLetter subscriber by email /// /// OK /// Bad Request /// Unauthorized [HttpPost] [Route("/api/news_letter_subscriptions/{email}/deactivate")] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.OK)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] public IActionResult DeactivateNewsLetterSubscription(string email) { if (string.IsNullOrEmpty(email)) diff --git a/Nop.Plugin.Api/Controllers/OrderItemsController.cs b/Nop.Plugin.Api/Controllers/OrderItemsController.cs index e4b42b4..b6818e9 100644 --- a/Nop.Plugin.Api/Controllers/OrderItemsController.cs +++ b/Nop.Plugin.Api/Controllers/OrderItemsController.cs @@ -2,16 +2,15 @@ using System.Collections.Generic; using System.Linq; using System.Net; -using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Mvc; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Orders; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.Delta; -using Nop.Plugin.Api.DTOs.Errors; -using Nop.Plugin.Api.DTOs.OrderItems; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.OrderItems; using Nop.Plugin.Api.Helpers; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.JSON.ActionResults; using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.MappingExtensions; @@ -31,8 +30,6 @@ namespace Nop.Plugin.Api.Controllers { - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, - AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class OrderItemsController : BaseApiController { private readonly IDTOHelper _dtoHelper; @@ -43,7 +40,8 @@ public class OrderItemsController : BaseApiController private readonly IProductApiService _productApiService; private readonly ITaxService _taxService; - public OrderItemsController(IJsonFieldsSerializer jsonFieldsSerializer, + public OrderItemsController( + IJsonFieldsSerializer jsonFieldsSerializer, IAclService aclService, ICustomerService customerService, IStoreMappingService storeMappingService, @@ -59,14 +57,14 @@ public OrderItemsController(IJsonFieldsSerializer jsonFieldsSerializer, ITaxService taxService, IPictureService pictureService, IDTOHelper dtoHelper) : base(jsonFieldsSerializer, - aclService, - customerService, - storeMappingService, - storeService, - discountService, - customerActivityService, - localizationService, - pictureService) + aclService, + customerService, + storeMappingService, + storeService, + discountService, + customerActivityService, + localizationService, + pictureService) { _orderItemApiService = orderItemApiService; _orderApiService = orderApiService; @@ -79,19 +77,19 @@ public OrderItemsController(IJsonFieldsSerializer jsonFieldsSerializer, [HttpGet] [Route("/api/orders/{orderId}/items")] - [ProducesResponseType(typeof(OrderItemsRootObject), (int) HttpStatusCode.OK)] - [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(OrderItemsRootObject), (int)HttpStatusCode.OK)] + [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetOrderItems(int orderId, OrderItemsParametersModel parameters) { - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "limit", "Invalid limit parameter"); } - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "Invalid request parameters"); } @@ -105,7 +103,7 @@ public IActionResult GetOrderItems(int orderId, OrderItemsParametersModel parame var allOrderItemsForOrder = _orderItemApiService.GetOrderItemsForOrder(order, parameters.Limit, parameters.Page, - parameters.SinceId); + parameters.SinceId); var orderItemsRootObject = new OrderItemsRootObject { @@ -119,10 +117,10 @@ public IActionResult GetOrderItems(int orderId, OrderItemsParametersModel parame [HttpGet] [Route("/api/orders/{orderId}/items/count")] - [ProducesResponseType(typeof(OrderItemsCountRootObject), (int) HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(OrderItemsCountRootObject), (int)HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetOrderItemsCount(int orderId) { @@ -145,10 +143,10 @@ public IActionResult GetOrderItemsCount(int orderId) [HttpGet] [Route("/api/orders/{orderId}/items/{orderItemId}")] - [ProducesResponseType(typeof(OrderItemsRootObject), (int) HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(OrderItemsRootObject), (int)HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetOrderItemByIdForOrder(int orderId, int orderItemId, string fields = "") { @@ -166,7 +164,10 @@ public IActionResult GetOrderItemByIdForOrder(int orderId, int orderItemId, stri return Error(HttpStatusCode.NotFound, "order_item", "not found"); } - var orderItemDtos = new List {_dtoHelper.PrepareOrderItemDTO(orderItem)}; + var orderItemDtos = new List + { + _dtoHelper.PrepareOrderItemDTO(orderItem) + }; var orderItemsRootObject = new OrderItemsRootObject { @@ -180,12 +181,13 @@ public IActionResult GetOrderItemByIdForOrder(int orderId, int orderItemId, stri [HttpPost] [Route("/api/orders/{orderId}/items")] - [ProducesResponseType(typeof(OrderItemsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(OrderItemsRootObject), (int)HttpStatusCode.OK)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] - public IActionResult CreateOrderItem(int orderId, + [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + public IActionResult CreateOrderItem( + int orderId, [ModelBinder(typeof(JsonModelBinder))] Delta orderItemDelta) { @@ -224,7 +226,7 @@ public IActionResult CreateOrderItem(int orderId, if (orderItemDelta.Dto.RentalStartDateUtc > orderItemDelta.Dto.RentalEndDateUtc) { return Error(HttpStatusCode.BadRequest, "rental_start_date_utc", - "should be before rental_end_date_utc"); + "should be before rental_end_date_utc"); } if (orderItemDelta.Dto.RentalStartDateUtc < DateTime.UtcNow) @@ -235,13 +237,12 @@ public IActionResult CreateOrderItem(int orderId, var newOrderItem = PrepareDefaultOrderItemFromProduct(order, product); orderItemDelta.Merge(newOrderItem); - - order.OrderItems.Add(newOrderItem); + _orderService.InsertOrderItem(newOrderItem); _orderService.UpdateOrder(order); CustomerActivityService.InsertActivity("AddNewOrderItem", - LocalizationService.GetResource("ActivityLog.AddNewOrderItem"), newOrderItem); + LocalizationService.GetResource("ActivityLog.AddNewOrderItem"), newOrderItem); var orderItemsRootObject = new OrderItemsRootObject(); @@ -254,12 +255,13 @@ public IActionResult CreateOrderItem(int orderId, [HttpPut] [Route("/api/orders/{orderId}/items/{orderItemId}")] - [ProducesResponseType(typeof(OrderItemsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(OrderItemsRootObject), (int)HttpStatusCode.OK)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] - public IActionResult UpdateOrderItem(int orderId, int orderItemId, + [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + public IActionResult UpdateOrderItem( + int orderId, int orderItemId, [ModelBinder(typeof(JsonModelBinder))] Delta orderItemDelta) { @@ -290,14 +292,14 @@ public IActionResult UpdateOrderItem(int orderId, int orderItemId, orderItemDelta.Merge(orderItemToUpdate); - orderItemToUpdate.ProductId = (int) productId; + orderItemToUpdate.ProductId = (int)productId; orderItemToUpdate.RentalStartDateUtc = rentalStartDate; orderItemToUpdate.RentalEndDateUtc = rentalEndDate; _orderService.UpdateOrder(order); CustomerActivityService.InsertActivity("UpdateOrderItem", - LocalizationService.GetResource("ActivityLog.UpdateOrderItem"), orderItemToUpdate); + LocalizationService.GetResource("ActivityLog.UpdateOrderItem"), orderItemToUpdate); var orderItemsRootObject = new OrderItemsRootObject(); @@ -310,10 +312,10 @@ public IActionResult UpdateOrderItem(int orderId, int orderItemId, [HttpDelete] [Route("/api/orders/{orderId}/items/{orderItemId}")] - [ProducesResponseType(typeof(void), (int) HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult DeleteOrderItemById(int orderId, int orderItemId) { @@ -332,10 +334,10 @@ public IActionResult DeleteOrderItemById(int orderId, int orderItemId) [HttpDelete] [Route("/api/orders/{orderId}/items")] - [ProducesResponseType(typeof(void), (int) HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] - [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult DeleteAllOrderItemsForOrder(int orderId) { @@ -346,7 +348,7 @@ public IActionResult DeleteAllOrderItemsForOrder(int orderId) return Error(HttpStatusCode.NotFound, "order", "not found"); } - var orderItemsList = order.OrderItems.ToList(); + var orderItemsList = _orderService.GetOrderItems(order.Id).ToList(); foreach (var t in orderItemsList) { @@ -372,14 +374,15 @@ private Product GetProduct(int? productId) private OrderItem PrepareDefaultOrderItemFromProduct(Order order, Product product) { + var customer = CustomerService.GetCustomerById(order.CustomerId); var presetQty = 1; var presetPrice = - _priceCalculationService.GetFinalPrice(product, order.Customer, decimal.Zero, true, presetQty); + _priceCalculationService.GetFinalPrice(product, customer, decimal.Zero, true, presetQty); var presetPriceInclTax = - _taxService.GetProductPrice(product, presetPrice, true, order.Customer, out _); + _taxService.GetProductPrice(product, presetPrice, true, customer, out _); var presetPriceExclTax = - _taxService.GetProductPrice(product, presetPrice, false, order.Customer, out _); + _taxService.GetProductPrice(product, presetPrice, false, customer, out _); var orderItem = new OrderItem { @@ -390,11 +393,11 @@ private OrderItem PrepareDefaultOrderItemFromProduct(Order order, Product produc PriceExclTax = presetPriceExclTax, OriginalProductCost = _priceCalculationService.GetProductCost(product, null), Quantity = presetQty, - Product = product, - Order = order + ProductId = product.Id, + OrderId = order.Id }; return orderItem; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Controllers/OrdersController.cs b/Nop.Plugin.Api/Controllers/OrdersController.cs index 0348d21..2e0a3af 100644 --- a/Nop.Plugin.Api/Controllers/OrdersController.cs +++ b/Nop.Plugin.Api/Controllers/OrdersController.cs @@ -2,23 +2,24 @@ using System.Collections.Generic; using System.Linq; using System.Net; +using Microsoft.AspNetCore.Mvc; using Nop.Core; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Orders; using Nop.Core.Infrastructure; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.Delta; -using Nop.Plugin.Api.DTOs; -using Nop.Plugin.Api.DTOs.OrderItems; -using Nop.Plugin.Api.DTOs.Orders; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.OrderItems; +using Nop.Plugin.Api.DTO.Orders; using Nop.Plugin.Api.Factories; using Nop.Plugin.Api.Helpers; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.JSON.ActionResults; +using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.ModelBinders; using Nop.Plugin.Api.Models.OrdersParameters; using Nop.Plugin.Api.Services; -using Nop.Plugin.Api.Validators; using Nop.Services.Catalog; using Nop.Services.Common; using Nop.Services.Customers; @@ -31,36 +32,29 @@ using Nop.Services.Security; using Nop.Services.Shipping; using Nop.Services.Stores; -using Microsoft.AspNetCore.Mvc; namespace Nop.Plugin.Api.Controllers { - using Microsoft.AspNetCore.Authentication.JwtBearer; - using DTOs.Errors; - using JSON.Serializers; - - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class OrdersController : BaseApiController { + private readonly IDTOHelper _dtoHelper; + private readonly IFactory _factory; + private readonly IGenericAttributeService _genericAttributeService; private readonly IOrderApiService _orderApiService; - private readonly IProductService _productService; private readonly IOrderProcessingService _orderProcessingService; private readonly IOrderService _orderService; - private readonly IShoppingCartService _shoppingCartService; - private readonly IGenericAttributeService _genericAttributeService; - private readonly IShippingService _shippingService; - private readonly IDTOHelper _dtoHelper; private readonly IProductAttributeConverter _productAttributeConverter; + private readonly IProductService _productService; + private readonly IShippingService _shippingService; + private readonly IShoppingCartService _shoppingCartService; private readonly IStoreContext _storeContext; - private readonly IFactory _factory; // We resolve the order settings this way because of the tests. // The auto mocking does not support concreate types as dependencies. It supports only interfaces. private OrderSettings _orderSettings; - private OrderSettings OrderSettings => _orderSettings ?? (_orderSettings = EngineContext.Current.Resolve()); - - public OrdersController(IOrderApiService orderApiService, + public OrdersController( + IOrderApiService orderApiService, IJsonFieldsSerializer jsonFieldsSerializer, IAclService aclService, ICustomerService customerService, @@ -81,7 +75,7 @@ public OrdersController(IOrderApiService orderApiService, IDTOHelper dtoHelper, IProductAttributeConverter productAttributeConverter) : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, - storeService, discountService, customerActivityService, localizationService,pictureService) + storeService, discountService, customerActivityService, localizationService, pictureService) { _orderApiService = orderApiService; _factory = factory; @@ -96,26 +90,28 @@ public OrdersController(IOrderApiService orderApiService, _productAttributeConverter = productAttributeConverter; } + private OrderSettings OrderSettings => _orderSettings ?? (_orderSettings = EngineContext.Current.Resolve()); + /// - /// Receive a list of all Orders + /// Receive a list of all Orders /// /// OK /// Bad Request /// Unauthorized [HttpGet] [Route("/api/orders")] - [ProducesResponseType(typeof(OrdersRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(OrdersRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetOrders(OrdersParametersModel parameters) { - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "Invalid page parameter"); } - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "page", "Invalid limit parameter"); } @@ -123,17 +119,17 @@ public IActionResult GetOrders(OrdersParametersModel parameters) var storeId = _storeContext.CurrentStore.Id; var orders = _orderApiService.GetOrders(parameters.Ids, parameters.CreatedAtMin, - parameters.CreatedAtMax, - parameters.Limit, parameters.Page, parameters.SinceId, - parameters.Status, parameters.PaymentStatus, parameters.ShippingStatus, - parameters.CustomerId, storeId); + parameters.CreatedAtMax, + parameters.Limit, parameters.Page, parameters.SinceId, + parameters.Status, parameters.PaymentStatus, parameters.ShippingStatus, + parameters.CustomerId, storeId); IList ordersAsDtos = orders.Select(x => _dtoHelper.PrepareOrderDTO(x)).ToList(); - var ordersRootObject = new OrdersRootObject() - { - Orders = ordersAsDtos - }; + var ordersRootObject = new OrdersRootObject + { + Orders = ordersAsDtos + }; var json = JsonFieldsSerializer.Serialize(ordersRootObject, parameters.Fields); @@ -141,15 +137,15 @@ public IActionResult GetOrders(OrdersParametersModel parameters) } /// - /// Receive a count of all Orders + /// Receive a count of all Orders /// /// OK /// Unauthorized [HttpGet] [Route("/api/orders/count")] - [ProducesResponseType(typeof(OrdersCountRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(OrdersCountRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetOrdersCount(OrdersCountParametersModel parameters) { @@ -158,28 +154,29 @@ public IActionResult GetOrdersCount(OrdersCountParametersModel parameters) var ordersCount = _orderApiService.GetOrdersCount(parameters.CreatedAtMin, parameters.CreatedAtMax, parameters.Status, parameters.PaymentStatus, parameters.ShippingStatus, parameters.CustomerId, storeId); - var ordersCountRootObject = new OrdersCountRootObject() - { - Count = ordersCount - }; + var ordersCountRootObject = new OrdersCountRootObject + { + Count = ordersCount + }; return Ok(ordersCountRootObject); } /// - /// Retrieve order by spcified id + /// Retrieve order by spcified id /// - /// /// Id of the order + /// /// + /// Id of the order /// Fields from the order you want your json to contain /// OK /// Not Found /// Unauthorized [HttpGet] [Route("/api/orders/{id}")] - [ProducesResponseType(typeof(OrdersRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(OrdersRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetOrderById(int id, string fields = "") { @@ -206,36 +203,38 @@ public IActionResult GetOrderById(int id, string fields = "") } /// - /// Retrieve all orders for customer + /// Retrieve all orders for customer /// /// Id of the customer whoes orders you want to get /// OK /// Unauthorized [HttpGet] [Route("/api/orders/customer/{customer_id}")] - [ProducesResponseType(typeof(OrdersRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(OrdersRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetOrdersByCustomerId(int customerId) { IList ordersForCustomer = _orderApiService.GetOrdersByCustomerId(customerId).Select(x => _dtoHelper.PrepareOrderDTO(x)).ToList(); - var ordersRootObject = new OrdersRootObject() - { - Orders = ordersForCustomer - }; + var ordersRootObject = new OrdersRootObject + { + Orders = ordersForCustomer + }; return Ok(ordersRootObject); } [HttpPost] [Route("/api/orders")] - [ProducesResponseType(typeof(OrdersRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(OrdersRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - public IActionResult CreateOrder([ModelBinder(typeof(JsonModelBinder))] Delta orderDelta) + public IActionResult CreateOrder( + [ModelBinder(typeof(JsonModelBinder))] + Delta orderDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -250,7 +249,7 @@ public IActionResult CreateOrder([ModelBinder(typeof(JsonModelBinder)) // We doesn't have to check for value because this is done by the order validator. var customer = CustomerService.GetCustomerById(orderDelta.Dto.CustomerId.Value); - + if (customer == null) { return Error(HttpStatusCode.NotFound, "customer", "not found"); @@ -274,12 +273,12 @@ public IActionResult CreateOrder([ModelBinder(typeof(JsonModelBinder)) var isValid = true; isValid &= SetShippingOption(orderDelta.Dto.ShippingRateComputationMethodSystemName, - orderDelta.Dto.ShippingMethod, - orderDelta.Dto.StoreId ?? _storeContext.CurrentStore.Id, - customer, - BuildShoppingCartItemsFromOrderItemDtos(orderDelta.Dto.OrderItems.ToList(), - customer.Id, - orderDelta.Dto.StoreId ?? _storeContext.CurrentStore.Id)); + orderDelta.Dto.ShippingMethod, + orderDelta.Dto.StoreId ?? _storeContext.CurrentStore.Id, + customer, + BuildShoppingCartItemsFromOrderItemDtos(orderDelta.Dto.OrderItems.ToList(), + customer.Id, + orderDelta.Dto.StoreId ?? _storeContext.CurrentStore.Id)); if (!isValid) { @@ -290,18 +289,19 @@ public IActionResult CreateOrder([ModelBinder(typeof(JsonModelBinder)) var newOrder = _factory.Initialize(); orderDelta.Merge(newOrder); - customer.BillingAddress = newOrder.BillingAddress; - customer.ShippingAddress = newOrder.ShippingAddress; + customer.BillingAddressId = newOrder.BillingAddressId = orderDelta.Dto.BillingAddress.Id; + customer.ShippingAddressId = newOrder.ShippingAddressId = orderDelta.Dto.ShippingAddress.Id; + // If the customer has something in the cart it will be added too. Should we clear the cart first? - newOrder.Customer = customer; + newOrder.CustomerId = customer.Id; // The default value will be the currentStore.id, but if it isn't passed in the json we need to set it by hand. if (!orderDelta.Dto.StoreId.HasValue) { newOrder.StoreId = _storeContext.CurrentStore.Id; } - + var placeOrderResult = PlaceOrder(newOrder, customer); if (!placeOrderResult.Success) @@ -315,7 +315,7 @@ public IActionResult CreateOrder([ModelBinder(typeof(JsonModelBinder)) } CustomerActivityService.InsertActivity("AddNewOrder", - LocalizationService.GetResource("ActivityLog.AddNewOrder"), newOrder); + LocalizationService.GetResource("ActivityLog.AddNewOrder"), newOrder); var ordersRootObject = new OrdersRootObject(); @@ -330,10 +330,10 @@ public IActionResult CreateOrder([ModelBinder(typeof(JsonModelBinder)) [HttpDelete] [Route("/api/orders/{id}")] - [ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(void), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] [GetRequestsErrorInterceptorActionFilter] public IActionResult DeleteOrder(int id) @@ -342,7 +342,7 @@ public IActionResult DeleteOrder(int id) { return Error(HttpStatusCode.BadRequest, "id", "invalid id"); } - + var orderToDelete = _orderApiService.GetOrderById(id); if (orderToDelete == null) @@ -360,12 +360,14 @@ public IActionResult DeleteOrder(int id) [HttpPut] [Route("/api/orders/{id}")] - [ProducesResponseType(typeof(OrdersRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(OrdersRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - public IActionResult UpdateOrder([ModelBinder(typeof(JsonModelBinder))] Delta orderDelta) + public IActionResult UpdateOrder( + [ModelBinder(typeof(JsonModelBinder))] + Delta orderDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -380,9 +382,9 @@ public IActionResult UpdateOrder([ModelBinder(typeof(JsonModelBinder)) return Error(HttpStatusCode.NotFound, "order", "not found"); } - var customer = currentOrder.Customer; - - var shippingRequired = currentOrder.OrderItems.Any(item => !item.Product.IsFreeShipping); + var customer = CustomerService.GetCustomerById(currentOrder.CustomerId); + + var shippingRequired = _orderService.GetOrderItems(currentOrder.Id).Any(item => !_productService.GetProductById(item.Id).IsFreeShipping); if (shippingRequired) { @@ -394,9 +396,9 @@ public IActionResult UpdateOrder([ModelBinder(typeof(JsonModelBinder)) var storeId = orderDelta.Dto.StoreId ?? _storeContext.CurrentStore.Id; isValid &= SetShippingOption(orderDelta.Dto.ShippingRateComputationMethodSystemName ?? currentOrder.ShippingRateComputationMethodSystemName, - orderDelta.Dto.ShippingMethod, - storeId, - customer, BuildShoppingCartItemsFromOrderItems(currentOrder.OrderItems.ToList(), customer.Id, storeId)); + orderDelta.Dto.ShippingMethod, + storeId, + customer, BuildShoppingCartItemsFromOrderItems(_orderService.GetOrderItems(currentOrder.Id).ToList(), customer.Id, storeId)); } if (isValid) @@ -410,14 +412,15 @@ public IActionResult UpdateOrder([ModelBinder(typeof(JsonModelBinder)) } orderDelta.Merge(currentOrder); - - customer.BillingAddress = currentOrder.BillingAddress; - customer.ShippingAddress = currentOrder.ShippingAddress; + + customer.BillingAddressId = currentOrder.BillingAddressId = orderDelta.Dto.BillingAddress.Id; + customer.ShippingAddressId = currentOrder.ShippingAddressId = orderDelta.Dto.ShippingAddress.Id; + _orderService.UpdateOrder(currentOrder); CustomerActivityService.InsertActivity("UpdateOrder", - LocalizationService.GetResource("ActivityLog.UpdateOrder"), currentOrder); + LocalizationService.GetResource("ActivityLog.UpdateOrder"), currentOrder); var ordersRootObject = new OrdersRootObject(); @@ -431,7 +434,8 @@ public IActionResult UpdateOrder([ModelBinder(typeof(JsonModelBinder)) return new RawJsonActionResult(json); } - private bool SetShippingOption(string shippingRateComputationMethodSystemName, string shippingOptionName, int storeId, Customer customer, List shoppingCartItems) + private bool SetShippingOption( + string shippingRateComputationMethodSystemName, string shippingOptionName, int storeId, Customer customer, List shoppingCartItems) { var isValid = true; @@ -440,7 +444,7 @@ private bool SetShippingOption(string shippingRateComputationMethodSystemName, s isValid = false; ModelState.AddModelError("shipping_rate_computation_method_system_name", - "Please provide shipping_rate_computation_method_system_name"); + "Please provide shipping_rate_computation_method_system_name"); } else if (string.IsNullOrEmpty(shippingOptionName)) { @@ -450,8 +454,8 @@ private bool SetShippingOption(string shippingRateComputationMethodSystemName, s } else { - var shippingOptionResponse = _shippingService.GetShippingOptions(shoppingCartItems, customer.ShippingAddress, customer, - shippingRateComputationMethodSystemName, storeId); + var shippingOptionResponse = _shippingService.GetShippingOptions(shoppingCartItems, CustomerService.GetCustomerShippingAddress(customer), customer, + shippingRateComputationMethodSystemName, storeId); if (shippingOptionResponse.Success) { @@ -459,10 +463,10 @@ private bool SetShippingOption(string shippingRateComputationMethodSystemName, s var shippingOption = shippingOptions .Find(so => !string.IsNullOrEmpty(so.Name) && so.Name.Equals(shippingOptionName, StringComparison.InvariantCultureIgnoreCase)); - + _genericAttributeService.SaveAttribute(customer, - NopCustomerDefaults.SelectedShippingOptionAttribute, - shippingOption, storeId); + NopCustomerDefaults.SelectedShippingOptionAttribute, + shippingOption, storeId); } else { @@ -484,17 +488,16 @@ private List BuildShoppingCartItemsFromOrderItems(List BuildShoppingCartItemsFromOrderItemDtos(List BuildShoppingCartItemsFromOrderItemDtos(List orderItems, Customer orderItem.RentalEndDateUtc = null; } - var attributesXml = _productAttributeConverter.ConvertToXml(orderItem.Attributes.ToList(), product.Id); + var attributesXml = _productAttributeConverter.ConvertToXml(orderItem.Attributes.ToList(), product.Id); var errors = _shoppingCartService.AddToCart(customer, product, - ShoppingCartType.ShoppingCart, storeId,attributesXml, - 0M, orderItem.RentalStartDateUtc, orderItem.RentalEndDateUtc, - orderItem.Quantity ?? 1); + ShoppingCartType.ShoppingCart, storeId, attributesXml, + 0M, orderItem.RentalStartDateUtc, orderItem.RentalEndDateUtc, + orderItem.Quantity ?? 1); if (errors.Count > 0) { @@ -594,5 +596,5 @@ private bool AddOrderItemsToCart(ICollection orderItems, Customer return shouldReturnError; } - } -} \ No newline at end of file + } +} diff --git a/Nop.Plugin.Api/Controllers/ProductAttributesController.cs b/Nop.Plugin.Api/Controllers/ProductAttributesController.cs index 4b95520..77ed673 100644 --- a/Nop.Plugin.Api/Controllers/ProductAttributesController.cs +++ b/Nop.Plugin.Api/Controllers/ProductAttributesController.cs @@ -1,16 +1,18 @@ -using Microsoft.AspNetCore.Authentication.JwtBearer; +using System.Collections.Generic; +using System.Linq; +using System.Net; using Microsoft.AspNetCore.Mvc; using Nop.Core.Domain.Catalog; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.Delta; -using Nop.Plugin.Api.DTOs.Errors; -using Nop.Plugin.Api.DTOs.ProductAttributes; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.ProductAttributes; using Nop.Plugin.Api.Helpers; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.JSON.ActionResults; -using Nop.Plugin.Api.ModelBinders; -using Nop.Plugin.Api.Models.ProductAttributes; using Nop.Plugin.Api.JSON.Serializers; +using Nop.Plugin.Api.ModelBinders; +using Nop.Plugin.Api.Models.ProductAttributesParameters; using Nop.Plugin.Api.Services; using Nop.Services.Catalog; using Nop.Services.Customers; @@ -20,31 +22,29 @@ using Nop.Services.Media; using Nop.Services.Security; using Nop.Services.Stores; -using System.Collections.Generic; -using System.Linq; -using System.Net; namespace Nop.Plugin.Api.Controllers { - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class ProductAttributesController : BaseApiController { - private readonly IProductAttributeService _productAttributeService; - private readonly IProductAttributesApiService _productAttributesApiService; private readonly IDTOHelper _dtoHelper; + private readonly IProductAttributesApiService _productAttributesApiService; + private readonly IProductAttributeService _productAttributeService; - public ProductAttributesController(IJsonFieldsSerializer jsonFieldsSerializer, - ICustomerActivityService customerActivityService, - ILocalizationService localizationService, - IAclService aclService, - IStoreMappingService storeMappingService, - IStoreService storeService, - ICustomerService customerService, - IDiscountService discountService, - IPictureService pictureService, - IProductAttributeService productAttributeService, - IProductAttributesApiService productAttributesApiService, - IDTOHelper dtoHelper) : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, localizationService, pictureService) + public ProductAttributesController( + IJsonFieldsSerializer jsonFieldsSerializer, + ICustomerActivityService customerActivityService, + ILocalizationService localizationService, + IAclService aclService, + IStoreMappingService storeMappingService, + IStoreService storeService, + ICustomerService customerService, + IDiscountService discountService, + IPictureService pictureService, + IProductAttributeService productAttributeService, + IProductAttributesApiService productAttributesApiService, + IDTOHelper dtoHelper) : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, + customerActivityService, localizationService, pictureService) { _productAttributeService = productAttributeService; _productAttributesApiService = productAttributesApiService; @@ -52,37 +52,38 @@ public ProductAttributesController(IJsonFieldsSerializer jsonFieldsSerializer, } /// - /// Receive a list of all product attributes + /// Receive a list of all product attributes /// /// OK /// Bad Request /// Unauthorized [HttpGet] - [Route("/api/productattributes")] - [ProducesResponseType(typeof(ProductAttributesRootObjectDto), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [Route("/api/productattributes")] + [ProducesResponseType(typeof(ProductAttributesRootObjectDto), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetProductAttributes(ProductAttributesParametersModel parameters) { - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "limit", "invalid limit parameter"); } - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "invalid page parameter"); } var allProductAttributes = _productAttributesApiService.GetProductAttributes(parameters.Limit, parameters.Page, parameters.SinceId); - IList productAttributesAsDtos = allProductAttributes.Select(productAttribute => _dtoHelper.PrepareProductAttributeDTO(productAttribute)).ToList(); + IList productAttributesAsDtos = + allProductAttributes.Select(productAttribute => _dtoHelper.PrepareProductAttributeDTO(productAttribute)).ToList(); - var productAttributesRootObject = new ProductAttributesRootObjectDto() - { - ProductAttributes = productAttributesAsDtos - }; + var productAttributesRootObject = new ProductAttributesRootObjectDto + { + ProductAttributes = productAttributesAsDtos + }; var json = JsonFieldsSerializer.Serialize(productAttributesRootObject, parameters.Fields); @@ -90,29 +91,29 @@ public IActionResult GetProductAttributes(ProductAttributesParametersModel param } /// - /// Receive a count of all product attributes + /// Receive a count of all product attributes /// /// OK - /// Unauthorized + /// Unauthorized [HttpGet] [Route("/api/productattributes/count")] - [ProducesResponseType(typeof(ProductAttributesCountRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ProductAttributesCountRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetProductAttributesCount() { var allProductAttributesCount = _productAttributesApiService.GetProductAttributesCount(); - var productAttributesCountRootObject = new ProductAttributesCountRootObject() - { - Count = allProductAttributesCount - }; + var productAttributesCountRootObject = new ProductAttributesCountRootObject + { + Count = allProductAttributesCount + }; return Ok(productAttributesCountRootObject); } /// - /// Retrieve product attribute by spcified id + /// Retrieve product attribute by spcified id /// /// Id of the product attribute /// Fields from the product attribute you want your json to contain @@ -121,9 +122,9 @@ public IActionResult GetProductAttributesCount() /// Unauthorized [HttpGet] [Route("/api/productattributes/{id}")] - [ProducesResponseType(typeof(ProductAttributesRootObjectDto), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ProductAttributesRootObjectDto), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetProductAttributeById(int id, string fields = "") { @@ -152,13 +153,15 @@ public IActionResult GetProductAttributeById(int id, string fields = "") [HttpPost] [Route("/api/productattributes")] - [ProducesResponseType(typeof(ProductAttributesRootObjectDto), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ProductAttributesRootObjectDto), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] [GetRequestsErrorInterceptorActionFilter] - public IActionResult CreateProductAttribute([ModelBinder(typeof(JsonModelBinder))] Delta productAttributeDelta) + public IActionResult CreateProductAttribute( + [ModelBinder(typeof(JsonModelBinder))] + Delta productAttributeDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -170,10 +173,10 @@ public IActionResult CreateProductAttribute([ModelBinder(typeof(JsonModelBinder< var productAttribute = new ProductAttribute(); productAttributeDelta.Merge(productAttribute); - _productAttributeService.InsertProductAttribute(productAttribute); + _productAttributeService.InsertProductAttribute(productAttribute); CustomerActivityService.InsertActivity("AddNewProductAttribute", - LocalizationService.GetResource("ActivityLog.AddNewProductAttribute"), productAttribute); + LocalizationService.GetResource("ActivityLog.AddNewProductAttribute"), productAttribute); // Preparing the result dto of the new product var productAttributeDto = _dtoHelper.PrepareProductAttributeDTO(productAttribute); @@ -189,13 +192,15 @@ public IActionResult CreateProductAttribute([ModelBinder(typeof(JsonModelBinder< [HttpPut] [Route("/api/productattributes/{id}")] - [ProducesResponseType(typeof(ProductAttributesRootObjectDto), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ProductAttributesRootObjectDto), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] [GetRequestsErrorInterceptorActionFilter] - public IActionResult UpdateProductAttribute([ModelBinder(typeof(JsonModelBinder))] Delta productAttributeDelta) + public IActionResult UpdateProductAttribute( + [ModelBinder(typeof(JsonModelBinder))] + Delta productAttributeDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -214,9 +219,9 @@ public IActionResult UpdateProductAttribute([ModelBinder(typeof(JsonModelBinder< _productAttributeService.UpdateProductAttribute(productAttribute); - + CustomerActivityService.InsertActivity("EditProductAttribute", - LocalizationService.GetResource("ActivityLog.EditProductAttribute"), productAttribute); + LocalizationService.GetResource("ActivityLog.EditProductAttribute"), productAttribute); // Preparing the result dto of the new product attribute var productAttributeDto = _dtoHelper.PrepareProductAttributeDTO(productAttribute); @@ -232,10 +237,10 @@ public IActionResult UpdateProductAttribute([ModelBinder(typeof(JsonModelBinder< [HttpDelete] [Route("/api/productattributes/{id}")] - [ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(void), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] [GetRequestsErrorInterceptorActionFilter] public IActionResult DeleteProductAttribute(int id) @@ -255,9 +260,10 @@ public IActionResult DeleteProductAttribute(int id) _productAttributeService.DeleteProductAttribute(productAttribute); //activity log - CustomerActivityService.InsertActivity("DeleteProductAttribute", LocalizationService.GetResource("ActivityLog.DeleteProductAttribute"), productAttribute); + CustomerActivityService.InsertActivity("DeleteProductAttribute", LocalizationService.GetResource("ActivityLog.DeleteProductAttribute"), + productAttribute); return new RawJsonActionResult("{}"); - } + } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Controllers/ProductCategoryMappingsController.cs b/Nop.Plugin.Api/Controllers/ProductCategoryMappingsController.cs index 92c0e42..e9c3803 100644 --- a/Nop.Plugin.Api/Controllers/ProductCategoryMappingsController.cs +++ b/Nop.Plugin.Api/Controllers/ProductCategoryMappingsController.cs @@ -1,12 +1,15 @@ using System.Collections.Generic; using System.Linq; using System.Net; +using Microsoft.AspNetCore.Mvc; using Nop.Core.Domain.Catalog; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.Delta; -using Nop.Plugin.Api.DTOs.ProductCategoryMappings; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.ProductCategoryMappings; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.JSON.ActionResults; +using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.MappingExtensions; using Nop.Plugin.Api.ModelBinders; using Nop.Plugin.Api.Models.ProductCategoryMappingsParameters; @@ -22,20 +25,15 @@ namespace Nop.Plugin.Api.Controllers { - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Mvc; - using DTOs.Errors; - using JSON.Serializers; - - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class ProductCategoryMappingsController : BaseApiController { - private readonly IProductCategoryMappingsApiService _productCategoryMappingsService; - private readonly ICategoryService _categoryService; private readonly ICategoryApiService _categoryApiService; + private readonly ICategoryService _categoryService; private readonly IProductApiService _productApiService; + private readonly IProductCategoryMappingsApiService _productCategoryMappingsService; - public ProductCategoryMappingsController(IProductCategoryMappingsApiService productCategoryMappingsService, + public ProductCategoryMappingsController( + IProductCategoryMappingsApiService productCategoryMappingsService, ICategoryService categoryService, IJsonFieldsSerializer jsonFieldsSerializer, IAclService aclService, @@ -44,11 +42,12 @@ public ProductCategoryMappingsController(IProductCategoryMappingsApiService prod IStoreService storeService, IDiscountService discountService, ICustomerActivityService customerActivityService, - ILocalizationService localizationService, - ICategoryApiService categoryApiService, + ILocalizationService localizationService, + ICategoryApiService categoryApiService, IProductApiService productApiService, IPictureService pictureService) - : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, localizationService,pictureService) + : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, + localizationService, pictureService) { _productCategoryMappingsService = productCategoryMappingsService; _categoryService = categoryService; @@ -57,40 +56,40 @@ public ProductCategoryMappingsController(IProductCategoryMappingsApiService prod } /// - /// Receive a list of all Product-Category mappings + /// Receive a list of all Product-Category mappings /// /// OK /// Bad Request /// Unauthorized [HttpGet] [Route("/api/product_category_mappings")] - [ProducesResponseType(typeof(ProductCategoryMappingsRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(ProductCategoryMappingsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetMappings(ProductCategoryMappingsParametersModel parameters) { - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "limit", "invalid limit parameter"); } - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "invalid page parameter"); } IList mappingsAsDtos = _productCategoryMappingsService.GetMappings(parameters.ProductId, - parameters.CategoryId, - parameters.Limit, - parameters.Page, - parameters.SinceId).Select(x => x.ToDto()).ToList(); + parameters.CategoryId, + parameters.Limit, + parameters.Page, + parameters.SinceId).Select(x => x.ToDto()).ToList(); - var productCategoryMappingRootObject = new ProductCategoryMappingsRootObject() - { - ProductCategoryMappingDtos = mappingsAsDtos - }; + var productCategoryMappingRootObject = new ProductCategoryMappingsRootObject + { + ProductCategoryMappingDtos = mappingsAsDtos + }; var json = JsonFieldsSerializer.Serialize(productCategoryMappingRootObject, parameters.Fields); @@ -98,15 +97,15 @@ public IActionResult GetMappings(ProductCategoryMappingsParametersModel paramete } /// - /// Receive a count of all Product-Category mappings + /// Receive a count of all Product-Category mappings /// /// OK /// Unauthorized [HttpGet] [Route("/api/product_category_mappings/count")] - [ProducesResponseType(typeof(ProductCategoryMappingsCountRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(ProductCategoryMappingsCountRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetMappingsCount(ProductCategoryMappingsCountParametersModel parameters) { @@ -121,30 +120,31 @@ public IActionResult GetMappingsCount(ProductCategoryMappingsCountParametersMode } var mappingsCount = _productCategoryMappingsService.GetMappingsCount(parameters.ProductId, - parameters.CategoryId); + parameters.CategoryId); - var productCategoryMappingsCountRootObject = new ProductCategoryMappingsCountRootObject() - { - Count = mappingsCount - }; + var productCategoryMappingsCountRootObject = new ProductCategoryMappingsCountRootObject + { + Count = mappingsCount + }; return Ok(productCategoryMappingsCountRootObject); } /// - /// Retrieve Product-Category mappings by spcified id + /// Retrieve Product-Category mappings by spcified id /// - /// /// Id of the Product-Category mapping + /// /// + /// Id of the Product-Category mapping /// Fields from the Product-Category mapping you want your json to contain /// OK /// Not Found /// Unauthorized [HttpGet] [Route("/api/product_category_mappings/{id}")] - [ProducesResponseType(typeof(ProductCategoryMappingsRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ProductCategoryMappingsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetMappingById(int id, string fields = "") { @@ -170,12 +170,14 @@ public IActionResult GetMappingById(int id, string fields = "") [HttpPost] [Route("/api/product_category_mappings")] - [ProducesResponseType(typeof(ProductCategoryMappingsRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ProductCategoryMappingsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - public IActionResult CreateProductCategoryMapping([ModelBinder(typeof(JsonModelBinder))] Delta productCategoryDelta) + public IActionResult CreateProductCategoryMapping( + [ModelBinder(typeof(JsonModelBinder))] + Delta productCategoryDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -218,19 +220,22 @@ public IActionResult CreateProductCategoryMapping([ModelBinder(typeof(JsonModelB var json = JsonFieldsSerializer.Serialize(productCategoryMappingsRootObject, string.Empty); //activity log - CustomerActivityService.InsertActivity("AddNewProductCategoryMapping", LocalizationService.GetResource("ActivityLog.AddNewProductCategoryMapping"), newProductCategory); + CustomerActivityService.InsertActivity("AddNewProductCategoryMapping", LocalizationService.GetResource("ActivityLog.AddNewProductCategoryMapping"), + newProductCategory); return new RawJsonActionResult(json); } [HttpPut] [Route("/api/product_category_mappings/{id}")] - [ProducesResponseType(typeof(ProductCategoryMappingsRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ProductCategoryMappingsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - public IActionResult UpdateProductCategoryMapping([ModelBinder(typeof(JsonModelBinder))] Delta productCategoryDelta) + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + public IActionResult UpdateProductCategoryMapping( + [ModelBinder(typeof(JsonModelBinder))] + Delta productCategoryDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -272,7 +277,7 @@ public IActionResult UpdateProductCategoryMapping([ModelBinder(typeof(JsonModelB //activity log CustomerActivityService.InsertActivity("UpdateProdutCategoryMapping", - LocalizationService.GetResource("ActivityLog.UpdateProdutCategoryMapping"), productCategoryEntityToUpdate); + LocalizationService.GetResource("ActivityLog.UpdateProdutCategoryMapping"), productCategoryEntityToUpdate); var updatedProductCategoryDto = productCategoryEntityToUpdate.ToDto(); @@ -287,10 +292,10 @@ public IActionResult UpdateProductCategoryMapping([ModelBinder(typeof(JsonModelB [HttpDelete] [Route("/api/product_category_mappings/{id}")] - [ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(void), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [GetRequestsErrorInterceptorActionFilter] public IActionResult DeleteProductCategoryMapping(int id) { @@ -309,9 +314,10 @@ public IActionResult DeleteProductCategoryMapping(int id) _categoryService.DeleteProductCategory(productCategory); //activity log - CustomerActivityService.InsertActivity("DeleteProductCategoryMapping", LocalizationService.GetResource("ActivityLog.DeleteProductCategoryMapping"), productCategory); + CustomerActivityService.InsertActivity("DeleteProductCategoryMapping", LocalizationService.GetResource("ActivityLog.DeleteProductCategoryMapping"), + productCategory); return new RawJsonActionResult("{}"); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Controllers/ProductManufacturerMappingsController.cs b/Nop.Plugin.Api/Controllers/ProductManufacturerMappingsController.cs index 9af0b75..bbfdf4c 100644 --- a/Nop.Plugin.Api/Controllers/ProductManufacturerMappingsController.cs +++ b/Nop.Plugin.Api/Controllers/ProductManufacturerMappingsController.cs @@ -1,12 +1,15 @@ using System.Collections.Generic; using System.Linq; using System.Net; +using Microsoft.AspNetCore.Mvc; using Nop.Core.Domain.Catalog; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.Delta; -using Nop.Plugin.Api.DTOs.ProductManufacturerMappings; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.ProductManufacturerMappings; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.JSON.ActionResults; +using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.MappingExtensions; using Nop.Plugin.Api.ModelBinders; using Nop.Plugin.Api.Models.ProductManufacturerMappingsParameters; @@ -22,20 +25,15 @@ namespace Nop.Plugin.Api.Controllers { - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Mvc; - using DTOs.Errors; - using JSON.Serializers; - - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class ProductManufacturerMappingsController : BaseApiController { - private readonly IProductManufacturerMappingsApiService _productManufacturerMappingsService; - private readonly IManufacturerService _manufacturerService; private readonly IManufacturerApiService _manufacturerApiService; + private readonly IManufacturerService _manufacturerService; private readonly IProductApiService _productApiService; + private readonly IProductManufacturerMappingsApiService _productManufacturerMappingsService; - public ProductManufacturerMappingsController(IProductManufacturerMappingsApiService productManufacturerMappingsService, + public ProductManufacturerMappingsController( + IProductManufacturerMappingsApiService productManufacturerMappingsService, IManufacturerService manufacturerService, IJsonFieldsSerializer jsonFieldsSerializer, IAclService aclService, @@ -44,11 +42,12 @@ public ProductManufacturerMappingsController(IProductManufacturerMappingsApiServ IStoreService storeService, IDiscountService discountService, ICustomerActivityService customerActivityService, - ILocalizationService localizationService, - IManufacturerApiService manufacturerApiService, + ILocalizationService localizationService, + IManufacturerApiService manufacturerApiService, IProductApiService productApiService, IPictureService pictureService) - : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, localizationService,pictureService) + : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, + localizationService, pictureService) { _productManufacturerMappingsService = productManufacturerMappingsService; _manufacturerService = manufacturerService; @@ -57,40 +56,40 @@ public ProductManufacturerMappingsController(IProductManufacturerMappingsApiServ } /// - /// Receive a list of all Product-Manufacturer mappings + /// Receive a list of all Product-Manufacturer mappings /// /// OK /// Bad Request /// Unauthorized [HttpGet] [Route("/api/product_manufacturer_mappings")] - [ProducesResponseType(typeof(ProductManufacturerMappingsRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(ProductManufacturerMappingsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetMappings(ProductManufacturerMappingsParametersModel parameters) { - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "limit", "invalid limit parameter"); } - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "invalid page parameter"); } IList mappingsAsDtos = _productManufacturerMappingsService.GetMappings(parameters.ProductId, - parameters.ManufacturerId, - parameters.Limit, - parameters.Page, - parameters.SinceId).Select(x => x.ToDto()).ToList(); + parameters.ManufacturerId, + parameters.Limit, + parameters.Page, + parameters.SinceId).Select(x => x.ToDto()).ToList(); - var productManufacturerMappingRootObject = new ProductManufacturerMappingsRootObject() - { - ProductManufacturerMappingsDtos = mappingsAsDtos - }; + var productManufacturerMappingRootObject = new ProductManufacturerMappingsRootObject + { + ProductManufacturerMappingsDtos = mappingsAsDtos + }; var json = JsonFieldsSerializer.Serialize(productManufacturerMappingRootObject, parameters.Fields); @@ -98,15 +97,15 @@ public IActionResult GetMappings(ProductManufacturerMappingsParametersModel para } /// - /// Receive a count of all Product-Manufacturer mappings + /// Receive a count of all Product-Manufacturer mappings /// /// OK /// Unauthorized [HttpGet] [Route("/api/product_manufacturer_mappings/count")] - [ProducesResponseType(typeof(ProductManufacturerMappingsCountRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(ProductManufacturerMappingsCountRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetMappingsCount(ProductManufacturerMappingsCountParametersModel parameters) { @@ -121,30 +120,31 @@ public IActionResult GetMappingsCount(ProductManufacturerMappingsCountParameters } var mappingsCount = _productManufacturerMappingsService.GetMappingsCount(parameters.ProductId, - parameters.ManufacturerId); + parameters.ManufacturerId); - var productManufacturerMappingsCountRootObject = new ProductManufacturerMappingsCountRootObject() - { - Count = mappingsCount - }; + var productManufacturerMappingsCountRootObject = new ProductManufacturerMappingsCountRootObject + { + Count = mappingsCount + }; return Ok(productManufacturerMappingsCountRootObject); } /// - /// Retrieve Product-Manufacturer mappings by spcified id + /// Retrieve Product-Manufacturer mappings by spcified id /// - /// /// Id of the Product-Manufacturer mapping + /// /// + /// Id of the Product-Manufacturer mapping /// Fields from the Product-Manufacturer mapping you want your json to contain /// OK /// Not Found /// Unauthorized [HttpGet] [Route("/api/product_manufacturer_mappings/{id}")] - [ProducesResponseType(typeof(ProductManufacturerMappingsRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ProductManufacturerMappingsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetMappingById(int id, string fields = "") { @@ -170,12 +170,14 @@ public IActionResult GetMappingById(int id, string fields = "") [HttpPost] [Route("/api/product_manufacturer_mappings")] - [ProducesResponseType(typeof(ProductManufacturerMappingsRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ProductManufacturerMappingsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - public IActionResult CreateProductManufacturerMapping([ModelBinder(typeof(JsonModelBinder))] Delta productManufacturerDelta) + public IActionResult CreateProductManufacturerMapping( + [ModelBinder(typeof(JsonModelBinder))] + Delta productManufacturerDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -218,19 +220,22 @@ public IActionResult CreateProductManufacturerMapping([ModelBinder(typeof(JsonMo var json = JsonFieldsSerializer.Serialize(productManufacturerMappingsRootObject, string.Empty); //activity log - CustomerActivityService.InsertActivity("AddNewProductManufacturerMapping", LocalizationService.GetResource("ActivityLog.AddNewProductManufacturerMapping"), newProductManufacturer); + CustomerActivityService.InsertActivity("AddNewProductManufacturerMapping", + LocalizationService.GetResource("ActivityLog.AddNewProductManufacturerMapping"), newProductManufacturer); return new RawJsonActionResult(json); } [HttpPut] [Route("/api/product_manufacturer_mappings/{id}")] - [ProducesResponseType(typeof(ProductManufacturerMappingsRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ProductManufacturerMappingsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - public IActionResult UpdateProductManufacturerMapping([ModelBinder(typeof(JsonModelBinder))] Delta productManufacturerDelta) + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + public IActionResult UpdateProductManufacturerMapping( + [ModelBinder(typeof(JsonModelBinder))] + Delta productManufacturerDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -272,7 +277,8 @@ public IActionResult UpdateProductManufacturerMapping([ModelBinder(typeof(JsonMo //activity log CustomerActivityService.InsertActivity("UpdateProdutManufacturerMapping", - LocalizationService.GetResource("ActivityLog.UpdateProdutManufacturerMapping"), productManufacturerEntityToUpdate); + LocalizationService.GetResource("ActivityLog.UpdateProdutManufacturerMapping"), + productManufacturerEntityToUpdate); var updatedProductManufacturerDto = productManufacturerEntityToUpdate.ToDto(); @@ -287,10 +293,10 @@ public IActionResult UpdateProductManufacturerMapping([ModelBinder(typeof(JsonMo [HttpDelete] [Route("/api/product_manufacturer_mappings/{id}")] - [ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(void), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [GetRequestsErrorInterceptorActionFilter] public IActionResult DeleteProductManufacturerMapping(int id) { @@ -309,9 +315,10 @@ public IActionResult DeleteProductManufacturerMapping(int id) _manufacturerService.DeleteProductManufacturer(productManufacturer); //activity log - CustomerActivityService.InsertActivity("DeleteProductManufacturerMapping", LocalizationService.GetResource("ActivityLog.DeleteProductManufacturerMapping"), productManufacturer); + CustomerActivityService.InsertActivity("DeleteProductManufacturerMapping", + LocalizationService.GetResource("ActivityLog.DeleteProductManufacturerMapping"), productManufacturer); return new RawJsonActionResult("{}"); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Controllers/ProductSpecificationAttributesController.cs b/Nop.Plugin.Api/Controllers/ProductSpecificationAttributesController.cs index f122135..c5964da 100644 --- a/Nop.Plugin.Api/Controllers/ProductSpecificationAttributesController.cs +++ b/Nop.Plugin.Api/Controllers/ProductSpecificationAttributesController.cs @@ -1,16 +1,17 @@ -using Microsoft.AspNetCore.Authentication.JwtBearer; +using System.Linq; +using System.Net; using Microsoft.AspNetCore.Mvc; using Nop.Core.Domain.Catalog; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.Delta; -using Nop.Plugin.Api.DTOs.Errors; -using Nop.Plugin.Api.DTOs.SpecificationAttributes; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.SpecificationAttributes; using Nop.Plugin.Api.Helpers; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.JSON.ActionResults; using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.ModelBinders; -using Nop.Plugin.Api.Models.ProductSpecificationAttributes; +using Nop.Plugin.Api.Models.ProductSpecificationAttributesParameters; using Nop.Plugin.Api.Services; using Nop.Services.Catalog; using Nop.Services.Customers; @@ -20,30 +21,29 @@ using Nop.Services.Media; using Nop.Services.Security; using Nop.Services.Stores; -using System.Linq; -using System.Net; namespace Nop.Plugin.Api.Controllers { - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class ProductSpecificationAttributesController : BaseApiController { - private readonly ISpecificationAttributeService _specificationAttributeService; - private readonly ISpecificationAttributeApiService _specificationAttributeApiService; private readonly IDTOHelper _dtoHelper; + private readonly ISpecificationAttributeApiService _specificationAttributeApiService; + private readonly ISpecificationAttributeService _specificationAttributeService; - public ProductSpecificationAttributesController(IJsonFieldsSerializer jsonFieldsSerializer, - ICustomerActivityService customerActivityService, - ILocalizationService localizationService, - IAclService aclService, - IStoreMappingService storeMappingService, - IStoreService storeService, - ICustomerService customerService, - IDiscountService discountService, - IPictureService pictureService, - ISpecificationAttributeService specificationAttributeService, - ISpecificationAttributeApiService specificationAttributesApiService, - IDTOHelper dtoHelper) : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, localizationService, pictureService) + public ProductSpecificationAttributesController( + IJsonFieldsSerializer jsonFieldsSerializer, + ICustomerActivityService customerActivityService, + ILocalizationService localizationService, + IAclService aclService, + IStoreMappingService storeMappingService, + IStoreService storeService, + ICustomerService customerService, + IDiscountService discountService, + IPictureService pictureService, + ISpecificationAttributeService specificationAttributeService, + ISpecificationAttributeApiService specificationAttributesApiService, + IDTOHelper dtoHelper) : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, + customerActivityService, localizationService, pictureService) { _specificationAttributeService = specificationAttributeService; _specificationAttributeApiService = specificationAttributesApiService; @@ -51,37 +51,40 @@ public ProductSpecificationAttributesController(IJsonFieldsSerializer jsonFields } /// - /// Receive a list of all product specification attributes + /// Receive a list of all product specification attributes /// /// OK /// Bad Request /// Unauthorized [HttpGet] [Route("/api/productspecificationattributes")] - [ProducesResponseType(typeof(ProductSpecificationAttributesRootObjectDto), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ProductSpecificationAttributesRootObjectDto), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] [GetRequestsErrorInterceptorActionFilter] - public IActionResult GetProductSpecificationAttributes(ProductSpecifcationAttributesParametersModel parameters) + public IActionResult GetProductSpecificationAttributes(ProductSpecificationAttributesParametersModel parameters) { - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "limit", "invalid limit parameter"); } - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "invalid page parameter"); } - var productSpecificationAttribtues = _specificationAttributeApiService.GetProductSpecificationAttributes(productId: parameters.ProductId, specificationAttributeOptionId: parameters.SpecificationAttributeOptionId, allowFiltering: parameters.AllowFiltering, showOnProductPage: parameters.ShowOnProductPage, limit: parameters.Limit, page: parameters.Page, sinceId: parameters.SinceId); + var productSpecificationAttribtues = + _specificationAttributeApiService.GetProductSpecificationAttributes(parameters.ProductId, parameters.SpecificationAttributeOptionId, + parameters.AllowFiltering, parameters.ShowOnProductPage, parameters.Limit, + parameters.Page, parameters.SinceId); var productSpecificationAttributeDtos = productSpecificationAttribtues.Select(x => _dtoHelper.PrepareProductSpecificationAttributeDto(x)).ToList(); - var productSpecificationAttributesRootObject = new ProductSpecificationAttributesRootObjectDto() - { - ProductSpecificationAttributes = productSpecificationAttributeDtos - }; + var productSpecificationAttributesRootObject = new ProductSpecificationAttributesRootObjectDto + { + ProductSpecificationAttributes = productSpecificationAttributeDtos + }; var json = JsonFieldsSerializer.Serialize(productSpecificationAttributesRootObject, parameters.Fields); @@ -89,30 +92,31 @@ public IActionResult GetProductSpecificationAttributes(ProductSpecifcationAttrib } /// - /// Receive a count of all product specification attributes + /// Receive a count of all product specification attributes /// /// OK /// Unauthorized [HttpGet] [Route("/api/productspecificationattributes/count")] - [ProducesResponseType(typeof(ProductSpecificationAttributesCountRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(ProductSpecificationAttributesCountRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] - public IActionResult GetProductSpecificationAttributesCount(ProductSpecifcationAttributesCountParametersModel parameters) + public IActionResult GetProductSpecificationAttributesCount(ProductSpecificationAttributesCountParametersModel parameters) { - var productSpecificationAttributesCount = _specificationAttributeService.GetProductSpecificationAttributeCount(productId: parameters.ProductId, specificationAttributeOptionId: parameters.SpecificationAttributeOptionId); + var productSpecificationAttributesCount = + _specificationAttributeService.GetProductSpecificationAttributeCount(parameters.ProductId, parameters.SpecificationAttributeOptionId); - var productSpecificationAttributesCountRootObject = new ProductSpecificationAttributesCountRootObject() - { - Count = productSpecificationAttributesCount - }; + var productSpecificationAttributesCountRootObject = new ProductSpecificationAttributesCountRootObject + { + Count = productSpecificationAttributesCount + }; return Ok(productSpecificationAttributesCountRootObject); } /// - /// Retrieve product specification attribute by spcified id + /// Retrieve product specification attribute by spcified id /// /// Id of the product specification attribute /// Fields from the product specification attribute you want your json to contain @@ -121,10 +125,10 @@ public IActionResult GetProductSpecificationAttributesCount(ProductSpecifcationA /// Unauthorized [HttpGet] [Route("/api/productspecificationattributes/{id}")] - [ProducesResponseType(typeof(ProductSpecificationAttributesRootObjectDto), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ProductSpecificationAttributesRootObjectDto), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetProductSpecificationAttributeById(int id, string fields = "") { @@ -152,12 +156,14 @@ public IActionResult GetProductSpecificationAttributeById(int id, string fields [HttpPost] [Route("/api/productspecificationattributes")] - [ProducesResponseType(typeof(ProductSpecificationAttributesRootObjectDto), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ProductSpecificationAttributesRootObjectDto), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - public IActionResult CreateProductSpecificationAttribute([ModelBinder(typeof(JsonModelBinder))] Delta productSpecificaitonAttributeDelta) + public IActionResult CreateProductSpecificationAttribute( + [ModelBinder(typeof(JsonModelBinder))] + Delta productSpecificaitonAttributeDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -186,12 +192,14 @@ public IActionResult CreateProductSpecificationAttribute([ModelBinder(typeof(Jso [HttpPut] [Route("/api/productspecificationattributes/{id}")] - [ProducesResponseType(typeof(ProductSpecificationAttributesRootObjectDto), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ProductSpecificationAttributesRootObjectDto), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - public IActionResult UpdateProductSpecificationAttribute([ModelBinder(typeof(JsonModelBinder))] Delta productSpecificationAttributeDelta) + public IActionResult UpdateProductSpecificationAttribute( + [ModelBinder(typeof(JsonModelBinder))] + Delta productSpecificationAttributeDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -200,7 +208,7 @@ public IActionResult UpdateProductSpecificationAttribute([ModelBinder(typeof(Jso } // We do not need to validate the product attribute id, because this will happen in the model binder using the dto validator. - int productSpecificationAttributeId = productSpecificationAttributeDelta.Dto.Id; + var productSpecificationAttributeId = productSpecificationAttributeDelta.Dto.Id; var productSpecificationAttribute = _specificationAttributeService.GetProductSpecificationAttributeById(productSpecificationAttributeId); if (productSpecificationAttribute == null) @@ -211,7 +219,7 @@ public IActionResult UpdateProductSpecificationAttribute([ModelBinder(typeof(Jso productSpecificationAttributeDelta.Merge(productSpecificationAttribute); _specificationAttributeService.UpdateProductSpecificationAttribute(productSpecificationAttribute); - + CustomerActivityService.InsertActivity("EditProductSpecificationAttribute", productSpecificationAttribute.Id.ToString()); // Preparing the result dto of the new product attribute @@ -227,10 +235,10 @@ public IActionResult UpdateProductSpecificationAttribute([ModelBinder(typeof(Jso [HttpDelete] [Route("/api/productspecificationattributes/{id}")] - [ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(void), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] public IActionResult DeleteProductSpecificationAttribute(int id) { @@ -248,9 +256,11 @@ public IActionResult DeleteProductSpecificationAttribute(int id) _specificationAttributeService.DeleteProductSpecificationAttribute(productSpecificationAttribute); //activity log - CustomerActivityService.InsertActivity("DeleteProductSpecificationAttribute", LocalizationService.GetResource("ActivityLog.DeleteProductSpecificationAttribute"), productSpecificationAttribute); + CustomerActivityService.InsertActivity("DeleteProductSpecificationAttribute", + LocalizationService.GetResource("ActivityLog.DeleteProductSpecificationAttribute"), + productSpecificationAttribute); return new RawJsonActionResult("{}"); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Controllers/ProductsController.cs b/Nop.Plugin.Api/Controllers/ProductsController.cs index 8b1914e..34a2b79 100644 --- a/Nop.Plugin.Api/Controllers/ProductsController.cs +++ b/Nop.Plugin.Api/Controllers/ProductsController.cs @@ -2,15 +2,20 @@ using System.Collections.Generic; using System.Linq; using System.Net; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Discounts; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.Delta; -using Nop.Plugin.Api.DTOs.Images; -using Nop.Plugin.Api.DTOs.Products; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.Images; +using Nop.Plugin.Api.DTO.Products; using Nop.Plugin.Api.Factories; +using Nop.Plugin.Api.Helpers; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.JSON.ActionResults; +using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.ModelBinders; using Nop.Plugin.Api.Models.ProductsParameters; using Nop.Plugin.Api.Services; @@ -23,44 +28,39 @@ using Nop.Services.Security; using Nop.Services.Seo; using Nop.Services.Stores; -using Nop.Plugin.Api.Helpers; namespace Nop.Plugin.Api.Controllers { - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Mvc; - using DTOs.Errors; - using JSON.Serializers; - - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class ProductsController : BaseApiController { + private readonly IDTOHelper _dtoHelper; + private readonly IFactory _factory; + private readonly IManufacturerService _manufacturerService; private readonly IProductApiService _productApiService; + private readonly IProductAttributeService _productAttributeService; private readonly IProductService _productService; - private readonly IUrlRecordService _urlRecordService; - private readonly IManufacturerService _manufacturerService; - private readonly IFactory _factory; private readonly IProductTagService _productTagService; - private readonly IProductAttributeService _productAttributeService; - private readonly IDTOHelper _dtoHelper; + private readonly IUrlRecordService _urlRecordService; - public ProductsController(IProductApiService productApiService, - IJsonFieldsSerializer jsonFieldsSerializer, - IProductService productService, - IUrlRecordService urlRecordService, - ICustomerActivityService customerActivityService, - ILocalizationService localizationService, - IFactory factory, - IAclService aclService, - IStoreMappingService storeMappingService, - IStoreService storeService, - ICustomerService customerService, - IDiscountService discountService, - IPictureService pictureService, - IManufacturerService manufacturerService, - IProductTagService productTagService, - IProductAttributeService productAttributeService, - IDTOHelper dtoHelper) : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, localizationService, pictureService) + public ProductsController( + IProductApiService productApiService, + IJsonFieldsSerializer jsonFieldsSerializer, + IProductService productService, + IUrlRecordService urlRecordService, + ICustomerActivityService customerActivityService, + ILocalizationService localizationService, + IFactory factory, + IAclService aclService, + IStoreMappingService storeMappingService, + IStoreService storeService, + ICustomerService customerService, + IDiscountService discountService, + IPictureService pictureService, + IManufacturerService manufacturerService, + IProductTagService productTagService, + IProductAttributeService productAttributeService, + IDTOHelper dtoHelper) : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, + customerActivityService, localizationService, pictureService) { _productApiService = productApiService; _factory = factory; @@ -71,9 +71,9 @@ public ProductsController(IProductApiService productApiService, _productAttributeService = productAttributeService; _dtoHelper = dtoHelper; } - + /// - /// Receive a list of all products + /// Receive a list of all products /// /// OK /// Bad Request @@ -86,24 +86,24 @@ public ProductsController(IProductApiService productApiService, [GetRequestsErrorInterceptorActionFilter] public IActionResult GetProducts(ProductsParametersModel parameters) { - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "limit", "invalid limit parameter"); } - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "invalid page parameter"); } var allProducts = _productApiService.GetProducts(parameters.Ids, parameters.CreatedAtMin, parameters.CreatedAtMax, parameters.UpdatedAtMin, - parameters.UpdatedAtMax, parameters.Limit, parameters.Page, parameters.SinceId, parameters.CategoryId, - parameters.VendorName, parameters.PublishedStatus) + parameters.UpdatedAtMax, parameters.Limit, parameters.Page, parameters.SinceId, parameters.CategoryId, + parameters.VendorName, parameters.PublishedStatus) .Where(p => StoreMappingService.Authorize(p)); - + IList productsAsDtos = allProducts.Select(product => _dtoHelper.PrepareProductDTO(product)).ToList(); - var productsRootObject = new ProductsRootObjectDto() + var productsRootObject = new ProductsRootObjectDto { Products = productsAsDtos }; @@ -114,7 +114,7 @@ public IActionResult GetProducts(ProductsParametersModel parameters) } /// - /// Receive a count of all products + /// Receive a count of all products /// /// OK /// Unauthorized @@ -130,7 +130,7 @@ public IActionResult GetProductsCount(ProductsCountParametersModel parameters) parameters.UpdatedAtMax, parameters.PublishedStatus, parameters.VendorName, parameters.CategoryId); - var productsCountRootObject = new ProductsCountRootObject() + var productsCountRootObject = new ProductsCountRootObject { Count = allProductsCount }; @@ -139,7 +139,7 @@ public IActionResult GetProductsCount(ProductsCountParametersModel parameters) } /// - /// Retrieve product by spcified id + /// Retrieve product by spcified id /// /// Id of the product /// Fields from the product you want your json to contain @@ -174,7 +174,6 @@ public IActionResult GetProductById(int id, string fields = "") productsRootObject.Products.Add(productDto); var json = JsonFieldsSerializer.Serialize(productsRootObject, fields); - return new RawJsonActionResult(json); } @@ -183,7 +182,9 @@ public IActionResult GetProductById(int id, string fields = "") [ProducesResponseType(typeof(ProductsRootObjectDto), (int)HttpStatusCode.OK)] [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - public IActionResult CreateProduct([ModelBinder(typeof(JsonModelBinder))] Delta productDelta) + public IActionResult CreateProduct( + [ModelBinder(typeof(JsonModelBinder))] + Delta productDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -218,7 +219,7 @@ public IActionResult CreateProduct([ModelBinder(typeof(JsonModelBinder))] Delta productDelta) + public IActionResult UpdateProduct( + [ModelBinder(typeof(JsonModelBinder))] + Delta productDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -285,7 +288,7 @@ public IActionResult UpdateProduct([ModelBinder(typeof(JsonModelBinder { // If no pictures are specified means we don't have to update anything if (setPictures == null) + { return; + } // delete unused product pictures - var unusedProductPictures = entityToUpdate.ProductPictures.Where(x => setPictures.All(y => y.Id != x.Id)).ToList(); + var productPictures = _productService.GetProductPicturesByProductId(entityToUpdate.Id); + var unusedProductPictures = productPictures.Where(x => setPictures.All(y => y.Id != x.Id)).ToList(); foreach (var unusedProductPicture in unusedProductPictures) { var picture = PictureService.GetPictureById(unusedProductPicture.PictureId); if (picture == null) + { throw new ArgumentException("No picture found with the specified id"); + } PictureService.DeletePicture(picture); } @@ -350,7 +358,7 @@ private void UpdateProductPictures(Product entityToUpdate, List if (imageDto.Id > 0) { // update existing product picture - var productPictureToUpdate = entityToUpdate.ProductPictures.FirstOrDefault(x => x.Id == imageDto.Id); + var productPictureToUpdate = productPictures.FirstOrDefault(x => x.Id == imageDto.Id); if (productPictureToUpdate != null && imageDto.Position > 0) { productPictureToUpdate.DisplayOrder = imageDto.Position; @@ -361,7 +369,7 @@ private void UpdateProductPictures(Product entityToUpdate, List { // add new product picture var newPicture = PictureService.InsertPicture(imageDto.Binary, imageDto.MimeType, string.Empty); - _productService.InsertProductPicture(new ProductPicture() + _productService.InsertProductPicture(new ProductPicture { PictureId = newPicture.Id, ProductId = entityToUpdate.Id, @@ -375,12 +383,14 @@ private void UpdateProductAttributes(Product entityToUpdate, Delta p { // If no product attribute mappings are specified means we don't have to update anything if (productDtoDelta.Dto.ProductAttributeMappings == null) + { return; + } // delete unused product attribute mappings var toBeUpdatedIds = productDtoDelta.Dto.ProductAttributeMappings.Where(y => y.Id != 0).Select(x => x.Id); - - var unusedProductAttributeMappings = entityToUpdate.ProductAttributeMappings.Where(x => !toBeUpdatedIds.Contains(x.Id)).ToList(); + var productAttributeMappings = _productAttributeService.GetProductAttributeMappingsByProductId(entityToUpdate.Id); + var unusedProductAttributeMappings = productAttributeMappings.Where(x => !toBeUpdatedIds.Contains(x.Id)).ToList(); foreach (var unusedProductAttributeMapping in unusedProductAttributeMappings) { @@ -392,11 +402,11 @@ private void UpdateProductAttributes(Product entityToUpdate, Delta p if (productAttributeMappingDto.Id > 0) { // update existing product attribute mapping - var productAttributeMappingToUpdate = entityToUpdate.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingDto.Id); + var productAttributeMappingToUpdate = productAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingDto.Id); if (productAttributeMappingToUpdate != null) { - productDtoDelta.Merge(productAttributeMappingDto,productAttributeMappingToUpdate,false); - + productDtoDelta.Merge(productAttributeMappingDto, productAttributeMappingToUpdate, false); + _productAttributeService.UpdateProductAttributeMapping(productAttributeMappingToUpdate); UpdateProductAttributeValues(productAttributeMappingDto, productDtoDelta); @@ -404,7 +414,10 @@ private void UpdateProductAttributes(Product entityToUpdate, Delta p } else { - var newProductAttributeMapping = new ProductAttributeMapping {ProductId = entityToUpdate.Id}; + var newProductAttributeMapping = new ProductAttributeMapping + { + ProductId = entityToUpdate.Id + }; productDtoDelta.Merge(productAttributeMappingDto, newProductAttributeMapping); @@ -418,7 +431,9 @@ private void UpdateProductAttributeValues(ProductAttributeMappingDto productAttr { // If no product attribute values are specified means we don't have to update anything if (productAttributeMappingDto.ProductAttributeValues == null) + { return; + } // delete unused product attribute values var toBeUpdatedIds = productAttributeMappingDto.ProductAttributeValues.Where(y => y.Id != 0).Select(x => x.Id); @@ -460,10 +475,14 @@ private void UpdateProductAttributeValues(ProductAttributeMappingDto productAttr private void UpdateProductTags(Product product, IReadOnlyCollection productTags) { if (productTags == null) + { return; + } if (product == null) + { throw new ArgumentNullException(nameof(product)); + } //Copied from UpdateProductTags method of ProductTagService //product tags @@ -475,7 +494,9 @@ private void UpdateProductTags(Product product, IReadOnlyCollection prod foreach (var newProductTag in productTags) { if (!existingProductTag.Name.Equals(newProductTag, StringComparison.InvariantCultureIgnoreCase)) + { continue; + } found = true; break; @@ -490,8 +511,8 @@ private void UpdateProductTags(Product product, IReadOnlyCollection prod foreach (var productTag in productTagsToRemove) { //product.ProductTags.Remove(productTag); - product.ProductProductTagMappings - .Remove(product.ProductProductTagMappings.FirstOrDefault(mapping => mapping.ProductTagId == productTag.Id)); + //product.ProductProductTagMappings + // .Remove(product.ProductProductTagMappings.FirstOrDefault(mapping => mapping.ProductTagId == productTag.Id)); _productService.UpdateProduct(product); } @@ -513,11 +534,14 @@ private void UpdateProductTags(Product product, IReadOnlyCollection prod productTag = productTag2; } - if (!_productService.ProductTagExists(product, productTag.Id)) - { - product.ProductProductTagMappings.Add(new ProductProductTagMapping { ProductTag = productTag }); - _productService.UpdateProduct(product); - } + //if (!_productService.ProductTagExists(product, productTag.Id)) + //{ + // product.ProductProductTagMappings.Add(new ProductProductTagMapping + // { + // ProductTag = productTag + // }); + // _productService.UpdateProduct(product); + //} var seName = _urlRecordService.ValidateSeName(productTag, string.Empty, productTag.Name, true); _urlRecordService.SaveSlug(productTag, seName, 0); @@ -527,55 +551,66 @@ private void UpdateProductTags(Product product, IReadOnlyCollection prod private void UpdateDiscountMappings(Product product, List passedDiscountIds) { if (passedDiscountIds == null) + { return; + } var allDiscounts = DiscountService.GetAllDiscounts(DiscountType.AssignedToSkus, showHidden: true); - + var appliedProductDiscount = DiscountService.GetAppliedDiscounts(product); foreach (var discount in allDiscounts) { if (passedDiscountIds.Contains(discount.Id)) { //new discount - if (product.AppliedDiscounts.Count(d => d.Id == discount.Id) == 0) - product.AppliedDiscounts.Add(discount); + if (appliedProductDiscount.Count(d => d.Id == discount.Id) == 0) + { + appliedProductDiscount.Add(discount); + } } else { //remove discount - if (product.AppliedDiscounts.Count(d => d.Id == discount.Id) > 0) - product.AppliedDiscounts.Remove(discount); + if (appliedProductDiscount.Count(d => d.Id == discount.Id) > 0) + { + appliedProductDiscount.Remove(discount); + } } } _productService.UpdateProduct(product); _productService.UpdateHasDiscountsApplied(product); } - + private void UpdateProductManufacturers(Product product, List passedManufacturerIds) { // If no manufacturers specified then there is nothing to map if (passedManufacturerIds == null) + { return; - - var unusedProductManufacturers = product.ProductManufacturers.Where(x => !passedManufacturerIds.Contains(x.ManufacturerId)).ToList(); + } + var productmanufacturers = _manufacturerService.GetProductManufacturersByProductId(product.Id); + var unusedProductManufacturers = productmanufacturers.Where(x => !passedManufacturerIds.Contains(x.Id)).ToList(); // remove all manufacturers that are not passed foreach (var unusedProductManufacturer in unusedProductManufacturers) { - _manufacturerService.DeleteProductManufacturer(unusedProductManufacturer); + //_manufacturerService.DeleteProductManufacturer(unusedProductManufacturer); } foreach (var passedManufacturerId in passedManufacturerIds) { // not part of existing manufacturers so we will create a new one - if (product.ProductManufacturers.All(x => x.ManufacturerId != passedManufacturerId)) + if (productmanufacturers.All(x => x.Id != passedManufacturerId)) { // if manufacturer does not exist we simply ignore it, otherwise add it to the product var manufacturer = _manufacturerService.GetManufacturerById(passedManufacturerId); if (manufacturer != null) { - _manufacturerService.InsertProductManufacturer(new ProductManufacturer() - { ProductId = product.Id, ManufacturerId = manufacturer.Id }); + _manufacturerService.InsertProductManufacturer(new ProductManufacturer + { + ProductId = product.Id, + ManufacturerId = manufacturer.Id + }); } } } @@ -585,11 +620,13 @@ private void UpdateAssociatedProducts(Product product, List passedAssociate { // If no associated products specified then there is nothing to map if (passedAssociatedProductIds == null) + { return; + } var noLongerAssociatedProducts = _productService.GetAssociatedProducts(product.Id, showHidden: true) - .Where(p => !passedAssociatedProductIds.Contains(p.Id)); + .Where(p => !passedAssociatedProductIds.Contains(p.Id)); // update all products that are no longer associated with our product foreach (var noLongerAssocuatedProduct in noLongerAssociatedProducts) @@ -606,4 +643,4 @@ private void UpdateAssociatedProducts(Product product, List passedAssociate } } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Controllers/ShoppingCartItemsController.cs b/Nop.Plugin.Api/Controllers/ShoppingCartItemsController.cs index da2d6bb..2a23649 100644 --- a/Nop.Plugin.Api/Controllers/ShoppingCartItemsController.cs +++ b/Nop.Plugin.Api/Controllers/ShoppingCartItemsController.cs @@ -2,13 +2,18 @@ using System.Collections.Generic; using System.Linq; using System.Net; +using Microsoft.AspNetCore.Mvc; +using Nop.Core; using Nop.Core.Domain.Orders; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.Delta; -using Nop.Plugin.Api.DTOs.ShoppingCarts; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.ShoppingCarts; using Nop.Plugin.Api.Factories; +using Nop.Plugin.Api.Helpers; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.JSON.ActionResults; +using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.ModelBinders; using Nop.Plugin.Api.Models.ShoppingCartsParameters; using Nop.Plugin.Api.Services; @@ -21,28 +26,21 @@ using Nop.Services.Orders; using Nop.Services.Security; using Nop.Services.Stores; -using Nop.Plugin.Api.Helpers; -using Nop.Core; namespace Nop.Plugin.Api.Controllers { - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Mvc; - using DTOs.Errors; - using JSON.Serializers; - - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class ShoppingCartItemsController : BaseApiController { - private readonly IShoppingCartItemApiService _shoppingCartItemApiService; - private readonly IShoppingCartService _shoppingCartService; - private readonly IProductService _productService; + private readonly IDTOHelper _dtoHelper; private readonly IFactory _factory; private readonly IProductAttributeConverter _productAttributeConverter; - private readonly IDTOHelper _dtoHelper; + private readonly IProductService _productService; + private readonly IShoppingCartItemApiService _shoppingCartItemApiService; + private readonly IShoppingCartService _shoppingCartService; private readonly IStoreContext _storeContext; - public ShoppingCartItemsController(IShoppingCartItemApiService shoppingCartItemApiService, + public ShoppingCartItemsController( + IShoppingCartItemApiService shoppingCartItemApiService, IJsonFieldsSerializer jsonFieldsSerializer, IAclService aclService, ICustomerService customerService, @@ -59,14 +57,14 @@ public ShoppingCartItemsController(IShoppingCartItemApiService shoppingCartItemA IDTOHelper dtoHelper, IStoreContext storeContext) : base(jsonFieldsSerializer, - aclService, - customerService, - storeMappingService, - storeService, - discountService, - customerActivityService, - localizationService, - pictureService) + aclService, + customerService, + storeMappingService, + storeService, + discountService, + customerActivityService, + localizationService, + pictureService) { _shoppingCartItemApiService = shoppingCartItemApiService; _shoppingCartService = shoppingCartService; @@ -78,46 +76,43 @@ public ShoppingCartItemsController(IShoppingCartItemApiService shoppingCartItemA } /// - /// Receive a list of all shopping cart items + /// Receive a list of all shopping cart items /// /// OK /// Bad Request /// Unauthorized [HttpGet] [Route("/api/shopping_cart_items")] - [ProducesResponseType(typeof(ShoppingCartItemsRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(ShoppingCartItemsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetShoppingCartItems(ShoppingCartItemsParametersModel parameters) { - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "limit", "invalid limit parameter"); } - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "invalid page parameter"); } - IList shoppingCartItems = _shoppingCartItemApiService.GetShoppingCartItems(customerId: null, - createdAtMin: parameters.CreatedAtMin, - createdAtMax: parameters.CreatedAtMax, - updatedAtMin: parameters.UpdatedAtMin, - updatedAtMax: parameters.UpdatedAtMax, - limit: parameters.Limit, - page: parameters.Page); + IList shoppingCartItems = _shoppingCartItemApiService.GetShoppingCartItems(null, + parameters.CreatedAtMin, + parameters.CreatedAtMax, + parameters.UpdatedAtMin, + parameters.UpdatedAtMax, + parameters.Limit, + parameters.Page); - var shoppingCartItemsDtos = shoppingCartItems.Select(shoppingCartItem => - { - return _dtoHelper.PrepareShoppingCartItemDTO(shoppingCartItem); - }).ToList(); + var shoppingCartItemsDtos = shoppingCartItems.Select(shoppingCartItem => { return _dtoHelper.PrepareShoppingCartItemDTO(shoppingCartItem); }).ToList(); - var shoppingCartsRootObject = new ShoppingCartItemsRootObject() - { - ShoppingCartItems = shoppingCartItemsDtos - }; + var shoppingCartsRootObject = new ShoppingCartItemsRootObject + { + ShoppingCartItems = shoppingCartItemsDtos + }; var json = JsonFieldsSerializer.Serialize(shoppingCartsRootObject, parameters.Fields); @@ -125,7 +120,7 @@ public IActionResult GetShoppingCartItems(ShoppingCartItemsParametersModel param } /// - /// Receive a list of all shopping cart items by customer id + /// Receive a list of all shopping cart items by customer id /// /// Id of the customer whoes shopping cart items you want to get /// @@ -135,24 +130,24 @@ public IActionResult GetShoppingCartItems(ShoppingCartItemsParametersModel param /// Unauthorized [HttpGet] [Route("/api/shopping_cart_items/{customerId}")] - [ProducesResponseType(typeof(ShoppingCartItemsRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ShoppingCartItemsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetShoppingCartItemsByCustomerId(int customerId, ShoppingCartItemsForCustomerParametersModel parameters) { - if (customerId <= Configurations.DefaultCustomerId) + if (customerId <= Constants.Configurations.DefaultCustomerId) { return Error(HttpStatusCode.BadRequest, "customer_id", "invalid customer_id"); } - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "limit", "invalid limit parameter"); } - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "invalid page parameter"); } @@ -169,13 +164,13 @@ public IActionResult GetShoppingCartItemsByCustomerId(int customerId, ShoppingCa } var shoppingCartItemsDtos = shoppingCartItems - .Select(shoppingCartItem => _dtoHelper.PrepareShoppingCartItemDTO(shoppingCartItem)) - .ToList(); + .Select(shoppingCartItem => _dtoHelper.PrepareShoppingCartItemDTO(shoppingCartItem)) + .ToList(); - var shoppingCartsRootObject = new ShoppingCartItemsRootObject() - { - ShoppingCartItems = shoppingCartItemsDtos - }; + var shoppingCartsRootObject = new ShoppingCartItemsRootObject + { + ShoppingCartItems = shoppingCartItemsDtos + }; var json = JsonFieldsSerializer.Serialize(shoppingCartsRootObject, parameters.Fields); @@ -184,12 +179,14 @@ public IActionResult GetShoppingCartItemsByCustomerId(int customerId, ShoppingCa [HttpPost] [Route("/api/shopping_cart_items")] - [ProducesResponseType(typeof(ShoppingCartItemsRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ShoppingCartItemsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(string), 422)] - public IActionResult CreateShoppingCartItem([ModelBinder(typeof(JsonModelBinder))] Delta shoppingCartItemDelta) + public IActionResult CreateShoppingCartItem( + [ModelBinder(typeof(JsonModelBinder))] + Delta shoppingCartItemDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -216,7 +213,7 @@ public IActionResult CreateShoppingCartItem([ModelBinder(typeof(JsonModelBinder< return Error(HttpStatusCode.NotFound, "customer", "not found"); } - var shoppingCartType = (ShoppingCartType)Enum.Parse(typeof(ShoppingCartType), shoppingCartItemDelta.Dto.ShoppingCartType); + var shoppingCartType = (ShoppingCartType) Enum.Parse(typeof(ShoppingCartType), shoppingCartItemDelta.Dto.ShoppingCartType); if (!product.IsRental) { @@ -224,13 +221,13 @@ public IActionResult CreateShoppingCartItem([ModelBinder(typeof(JsonModelBinder< newShoppingCartItem.RentalEndDateUtc = null; } - var attributesXml =_productAttributeConverter.ConvertToXml(shoppingCartItemDelta.Dto.Attributes, product.Id); + var attributesXml = _productAttributeConverter.ConvertToXml(shoppingCartItemDelta.Dto.Attributes, product.Id); var currentStoreId = _storeContext.CurrentStore.Id; var warnings = _shoppingCartService.AddToCart(customer, product, shoppingCartType, currentStoreId, attributesXml, 0M, - newShoppingCartItem.RentalStartDateUtc, newShoppingCartItem.RentalEndDateUtc, - shoppingCartItemDelta.Dto.Quantity ?? 1); + newShoppingCartItem.RentalStartDateUtc, newShoppingCartItem.RentalEndDateUtc, + shoppingCartItemDelta.Dto.Quantity ?? 1); if (warnings.Count > 0) { @@ -241,10 +238,8 @@ public IActionResult CreateShoppingCartItem([ModelBinder(typeof(JsonModelBinder< return Error(HttpStatusCode.BadRequest); } - else { - // the newly added shopping cart item should be the last one - newShoppingCartItem = customer.ShoppingCartItems.LastOrDefault(); - } + // the newly added shopping cart item should be the last one + newShoppingCartItem = _shoppingCartService.GetShoppingCart(customer,ShoppingCartType.ShoppingCart).LastOrDefault(); // Preparing the result dto of the new product category mapping var newShoppingCartItemDto = _dtoHelper.PrepareShoppingCartItemDTO(newShoppingCartItem); @@ -260,12 +255,14 @@ public IActionResult CreateShoppingCartItem([ModelBinder(typeof(JsonModelBinder< [HttpPut] [Route("/api/shopping_cart_items/{id}")] - [ProducesResponseType(typeof(ShoppingCartItemsRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ShoppingCartItemsRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - public IActionResult UpdateShoppingCartItem([ModelBinder(typeof(JsonModelBinder))] Delta shoppingCartItemDelta) + public IActionResult UpdateShoppingCartItem( + [ModelBinder(typeof(JsonModelBinder))] + Delta shoppingCartItemDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -281,9 +278,9 @@ public IActionResult UpdateShoppingCartItem([ModelBinder(typeof(JsonModelBinder< return Error(HttpStatusCode.NotFound, "shopping_cart_item", "not found"); } - shoppingCartItemDelta.Merge(shoppingCartItemForUpdate); + shoppingCartItemDelta.Merge(shoppingCartItemForUpdate); - if (!shoppingCartItemForUpdate.Product.IsRental) + if (!_productService.GetProductById(shoppingCartItemForUpdate.ProductId).IsRental) { shoppingCartItemForUpdate.RentalStartDateUtc = null; shoppingCartItemForUpdate.RentalEndDateUtc = null; @@ -291,14 +288,16 @@ public IActionResult UpdateShoppingCartItem([ModelBinder(typeof(JsonModelBinder< if (shoppingCartItemDelta.Dto.Attributes != null) { - shoppingCartItemForUpdate.AttributesXml = _productAttributeConverter.ConvertToXml(shoppingCartItemDelta.Dto.Attributes, shoppingCartItemForUpdate.Product.Id); + shoppingCartItemForUpdate.AttributesXml = + _productAttributeConverter.ConvertToXml(shoppingCartItemDelta.Dto.Attributes, shoppingCartItemForUpdate.ProductId); } + var customer = CustomerService.GetCustomerById(shoppingCartItemForUpdate.CustomerId); // The update time is set in the service. - var warnings = _shoppingCartService.UpdateShoppingCartItem(shoppingCartItemForUpdate.Customer, shoppingCartItemForUpdate.Id, - shoppingCartItemForUpdate.AttributesXml, shoppingCartItemForUpdate.CustomerEnteredPrice, - shoppingCartItemForUpdate.RentalStartDateUtc, shoppingCartItemForUpdate.RentalEndDateUtc, - shoppingCartItemForUpdate.Quantity); + var warnings = _shoppingCartService.UpdateShoppingCartItem(customer, shoppingCartItemForUpdate.Id, + shoppingCartItemForUpdate.AttributesXml, shoppingCartItemForUpdate.CustomerEnteredPrice, + shoppingCartItemForUpdate.RentalStartDateUtc, shoppingCartItemForUpdate.RentalEndDateUtc, + shoppingCartItemForUpdate.Quantity); if (warnings.Count > 0) { @@ -309,10 +308,7 @@ public IActionResult UpdateShoppingCartItem([ModelBinder(typeof(JsonModelBinder< return Error(HttpStatusCode.BadRequest); } - else - { - shoppingCartItemForUpdate = _shoppingCartItemApiService.GetShoppingCartItem(shoppingCartItemForUpdate.Id); - } + shoppingCartItemForUpdate = _shoppingCartItemApiService.GetShoppingCartItem(shoppingCartItemForUpdate.Id); // Preparing the result dto of the new product category mapping var newShoppingCartItemDto = _dtoHelper.PrepareShoppingCartItemDTO(shoppingCartItemForUpdate); @@ -328,10 +324,10 @@ public IActionResult UpdateShoppingCartItem([ModelBinder(typeof(JsonModelBinder< [HttpDelete] [Route("/api/shopping_cart_items/{id}")] - [ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(void), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [GetRequestsErrorInterceptorActionFilter] public IActionResult DeleteShoppingCartItem(int id) { @@ -350,9 +346,10 @@ public IActionResult DeleteShoppingCartItem(int id) _shoppingCartService.DeleteShoppingCartItem(shoppingCartItemForDelete); //activity log - CustomerActivityService.InsertActivity("DeleteShoppingCartItem", LocalizationService.GetResource("ActivityLog.DeleteShoppingCartItem"), shoppingCartItemForDelete); + CustomerActivityService.InsertActivity("DeleteShoppingCartItem", LocalizationService.GetResource("ActivityLog.DeleteShoppingCartItem"), + shoppingCartItemForDelete); return new RawJsonActionResult("{}"); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Controllers/SpecificationAttributesController.cs b/Nop.Plugin.Api/Controllers/SpecificationAttributesController.cs index a6a3732..10544c2 100644 --- a/Nop.Plugin.Api/Controllers/SpecificationAttributesController.cs +++ b/Nop.Plugin.Api/Controllers/SpecificationAttributesController.cs @@ -1,16 +1,17 @@ -using Microsoft.AspNetCore.Authentication.JwtBearer; +using System.Linq; +using System.Net; using Microsoft.AspNetCore.Mvc; using Nop.Core.Domain.Catalog; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.Delta; -using Nop.Plugin.Api.DTOs.Errors; -using Nop.Plugin.Api.DTOs.SpecificationAttributes; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.SpecificationAttributes; using Nop.Plugin.Api.Helpers; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.JSON.ActionResults; using Nop.Plugin.Api.JSON.Serializers; using Nop.Plugin.Api.ModelBinders; -using Nop.Plugin.Api.Models.SpecificationAttributes; +using Nop.Plugin.Api.Models.SpecificationAttributesParameters; using Nop.Plugin.Api.Services; using Nop.Services.Catalog; using Nop.Services.Customers; @@ -20,30 +21,29 @@ using Nop.Services.Media; using Nop.Services.Security; using Nop.Services.Stores; -using System.Linq; -using System.Net; namespace Nop.Plugin.Api.Controllers { - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class SpecificationAttributesController : BaseApiController { - private readonly ISpecificationAttributeService _specificationAttributeService; - private readonly ISpecificationAttributeApiService _specificationAttributeApiService; private readonly IDTOHelper _dtoHelper; + private readonly ISpecificationAttributeApiService _specificationAttributeApiService; + private readonly ISpecificationAttributeService _specificationAttributeService; - public SpecificationAttributesController(IJsonFieldsSerializer jsonFieldsSerializer, - ICustomerActivityService customerActivityService, - ILocalizationService localizationService, - IAclService aclService, - IStoreMappingService storeMappingService, - IStoreService storeService, - ICustomerService customerService, - IDiscountService discountService, - IPictureService pictureService, - ISpecificationAttributeService specificationAttributeService, - ISpecificationAttributeApiService specificationAttributesApiService, - IDTOHelper dtoHelper) : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, customerActivityService, localizationService, pictureService) + public SpecificationAttributesController( + IJsonFieldsSerializer jsonFieldsSerializer, + ICustomerActivityService customerActivityService, + ILocalizationService localizationService, + IAclService aclService, + IStoreMappingService storeMappingService, + IStoreService storeService, + ICustomerService customerService, + IDiscountService discountService, + IPictureService pictureService, + ISpecificationAttributeService specificationAttributeService, + ISpecificationAttributeApiService specificationAttributesApiService, + IDTOHelper dtoHelper) : base(jsonFieldsSerializer, aclService, customerService, storeMappingService, storeService, discountService, + customerActivityService, localizationService, pictureService) { _specificationAttributeService = specificationAttributeService; _specificationAttributeApiService = specificationAttributesApiService; @@ -51,37 +51,37 @@ public SpecificationAttributesController(IJsonFieldsSerializer jsonFieldsSeriali } /// - /// Receive a list of all specification attributes + /// Receive a list of all specification attributes /// /// OK /// Bad Request /// Unauthorized [HttpGet] [Route("/api/specificationattributes")] - [ProducesResponseType(typeof(SpecificationAttributesRootObjectDto), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(SpecificationAttributesRootObjectDto), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] [GetRequestsErrorInterceptorActionFilter] - public IActionResult GetSpecificationAttributes(SpecifcationAttributesParametersModel parameters) + public IActionResult GetSpecificationAttributes(SpecificationAttributesParametersModel parameters) { - if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) + if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return Error(HttpStatusCode.BadRequest, "limit", "invalid limit parameter"); } - if (parameters.Page < Configurations.DefaultPageValue) + if (parameters.Page < Constants.Configurations.DefaultPageValue) { return Error(HttpStatusCode.BadRequest, "page", "invalid page parameter"); } - var specificationAttribtues = _specificationAttributeApiService.GetSpecificationAttributes(limit: parameters.Limit, page: parameters.Page, sinceId: parameters.SinceId); + var specificationAttribtues = _specificationAttributeApiService.GetSpecificationAttributes(parameters.Limit, parameters.Page, parameters.SinceId); var specificationAttributeDtos = specificationAttribtues.Select(x => _dtoHelper.PrepareSpecificationAttributeDto(x)).ToList(); - var specificationAttributesRootObject = new SpecificationAttributesRootObjectDto() - { - SpecificationAttributes = specificationAttributeDtos - }; + var specificationAttributesRootObject = new SpecificationAttributesRootObjectDto + { + SpecificationAttributes = specificationAttributeDtos + }; var json = JsonFieldsSerializer.Serialize(specificationAttributesRootObject, parameters.Fields); @@ -89,30 +89,30 @@ public IActionResult GetSpecificationAttributes(SpecifcationAttributesParameters } /// - /// Receive a count of all specification attributes + /// Receive a count of all specification attributes /// /// OK /// Unauthorized [HttpGet] [Route("/api/specificationattributes/count")] - [ProducesResponseType(typeof(SpecificationAttributesCountRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(SpecificationAttributesCountRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] - public IActionResult GetSpecificationAttributesCount(SpecifcationAttributesCountParametersModel parameters) + public IActionResult GetSpecificationAttributesCount(SpecificationAttributesCountParametersModel parameters) { var specificationAttributesCount = _specificationAttributeService.GetSpecificationAttributes().Count(); - var specificationAttributesCountRootObject = new SpecificationAttributesCountRootObject() - { - Count = specificationAttributesCount - }; + var specificationAttributesCountRootObject = new SpecificationAttributesCountRootObject + { + Count = specificationAttributesCount + }; return Ok(specificationAttributesCountRootObject); } /// - /// Retrieve specification attribute by spcified id + /// Retrieve specification attribute by spcified id /// /// Id of the specification attribute /// Fields from the specification attribute you want your json to contain @@ -121,10 +121,10 @@ public IActionResult GetSpecificationAttributesCount(SpecifcationAttributesCount /// Unauthorized [HttpGet] [Route("/api/specificationattributes/{id}")] - [ProducesResponseType(typeof(SpecificationAttributesRootObjectDto), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(SpecificationAttributesRootObjectDto), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetSpecificationAttributeById(int id, string fields = "") { @@ -152,12 +152,14 @@ public IActionResult GetSpecificationAttributeById(int id, string fields = "") [HttpPost] [Route("/api/specificationattributes")] - [ProducesResponseType(typeof(SpecificationAttributesRootObjectDto), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(SpecificationAttributesRootObjectDto), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - public IActionResult CreateSpecificationAttribute([ModelBinder(typeof(JsonModelBinder))] Delta specificaitonAttributeDelta) + public IActionResult CreateSpecificationAttribute( + [ModelBinder(typeof(JsonModelBinder))] + Delta specificaitonAttributeDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -171,7 +173,8 @@ public IActionResult CreateSpecificationAttribute([ModelBinder(typeof(JsonModelB _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); - CustomerActivityService.InsertActivity("AddNewSpecAttribute", LocalizationService.GetResource("ActivityLog.AddNewSpecAttribute"), specificationAttribute); + CustomerActivityService.InsertActivity("AddNewSpecAttribute", LocalizationService.GetResource("ActivityLog.AddNewSpecAttribute"), + specificationAttribute); // Preparing the result dto of the new product var specificationAttributeDto = _dtoHelper.PrepareSpecificationAttributeDto(specificationAttribute); @@ -186,12 +189,14 @@ public IActionResult CreateSpecificationAttribute([ModelBinder(typeof(JsonModelB [HttpPut] [Route("/api/specificationattributes/{id}")] - [ProducesResponseType(typeof(SpecificationAttributesRootObjectDto), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(SpecificationAttributesRootObjectDto), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] - public IActionResult UpdateSpecificationAttribute([ModelBinder(typeof(JsonModelBinder))] Delta specificationAttributeDelta) + public IActionResult UpdateSpecificationAttribute( + [ModelBinder(typeof(JsonModelBinder))] + Delta specificationAttributeDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) @@ -200,7 +205,7 @@ public IActionResult UpdateSpecificationAttribute([ModelBinder(typeof(JsonModelB } // We do not need to validate the product attribute id, because this will happen in the model binder using the dto validator. - int specificationAttributeId = specificationAttributeDelta.Dto.Id; + var specificationAttributeId = specificationAttributeDelta.Dto.Id; var specificationAttribute = _specificationAttributeService.GetSpecificationAttributeById(specificationAttributeId); if (specificationAttribute == null) @@ -211,7 +216,7 @@ public IActionResult UpdateSpecificationAttribute([ModelBinder(typeof(JsonModelB specificationAttributeDelta.Merge(specificationAttribute); _specificationAttributeService.UpdateSpecificationAttribute(specificationAttribute); - + CustomerActivityService.InsertActivity("EditSpecAttribute", LocalizationService.GetResource("ActivityLog.EditSpecAttribute"), specificationAttribute); // Preparing the result dto of the new product attribute @@ -227,10 +232,10 @@ public IActionResult UpdateSpecificationAttribute([ModelBinder(typeof(JsonModelB [HttpDelete] [Route("/api/specificationattributes/{id}")] - [ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(void), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] [ProducesResponseType(typeof(ErrorsRootObject), 422)] public IActionResult DeleteSpecificationAttribute(int id) { @@ -248,9 +253,10 @@ public IActionResult DeleteSpecificationAttribute(int id) _specificationAttributeService.DeleteSpecificationAttribute(specificationAttribute); //activity log - CustomerActivityService.InsertActivity("DeleteSpecAttribute", LocalizationService.GetResource("ActivityLog.DeleteSpecAttribute"), specificationAttribute); + CustomerActivityService.InsertActivity("DeleteSpecAttribute", LocalizationService.GetResource("ActivityLog.DeleteSpecAttribute"), + specificationAttribute); return new RawJsonActionResult("{}"); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Controllers/StoreController.cs b/Nop.Plugin.Api/Controllers/StoreController.cs index 352de62..42f41c1 100644 --- a/Nop.Plugin.Api/Controllers/StoreController.cs +++ b/Nop.Plugin.Api/Controllers/StoreController.cs @@ -1,7 +1,13 @@ -using Nop.Core; +using System.Collections.Generic; +using System.Net; +using Microsoft.AspNetCore.Mvc; +using Nop.Core; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.DTOs.Stores; +using Nop.Plugin.Api.DTO.Errors; +using Nop.Plugin.Api.DTO.Stores; +using Nop.Plugin.Api.Helpers; using Nop.Plugin.Api.JSON.ActionResults; +using Nop.Plugin.Api.JSON.Serializers; using Nop.Services.Customers; using Nop.Services.Discounts; using Nop.Services.Localization; @@ -9,24 +15,16 @@ using Nop.Services.Media; using Nop.Services.Security; using Nop.Services.Stores; -using System.Collections.Generic; -using System.Net; -using Nop.Plugin.Api.Helpers; namespace Nop.Plugin.Api.Controllers { - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Mvc; - using DTOs.Errors; - using JSON.Serializers; - - [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class StoreController : BaseApiController { - private readonly IStoreContext _storeContext; private readonly IDTOHelper _dtoHelper; + private readonly IStoreContext _storeContext; - public StoreController(IJsonFieldsSerializer jsonFieldsSerializer, + public StoreController( + IJsonFieldsSerializer jsonFieldsSerializer, IAclService aclService, ICustomerService customerService, IStoreMappingService storeMappingService, @@ -38,21 +36,21 @@ public StoreController(IJsonFieldsSerializer jsonFieldsSerializer, IStoreContext storeContext, IDTOHelper dtoHelper) : base(jsonFieldsSerializer, - aclService, - customerService, - storeMappingService, - storeService, - discountService, - customerActivityService, - localizationService, - pictureService) + aclService, + customerService, + storeMappingService, + storeService, + discountService, + customerActivityService, + localizationService, + pictureService) { _storeContext = storeContext; _dtoHelper = dtoHelper; } /// - /// Retrieve category by spcified id + /// Retrieve category by spcified id /// /// Fields from the category you want your json to contain /// OK @@ -60,10 +58,10 @@ public StoreController(IJsonFieldsSerializer jsonFieldsSerializer, /// Unauthorized [HttpGet] [Route("/api/current_store")] - [ProducesResponseType(typeof(StoresRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(StoresRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.NotFound)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetCurrentStore(string fields = "") { @@ -86,21 +84,21 @@ public IActionResult GetCurrentStore(string fields = "") } /// - /// Retrieve all stores + /// Retrieve all stores /// /// Fields from the store you want your json to contain /// OK /// Unauthorized [HttpGet] [Route("/api/stores")] - [ProducesResponseType(typeof(StoresRootObject), (int)HttpStatusCode.OK)] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] - [ProducesResponseType(typeof(ErrorsRootObject), (int)HttpStatusCode.BadRequest)] + [ProducesResponseType(typeof(StoresRootObject), (int) HttpStatusCode.OK)] + [ProducesResponseType(typeof(string), (int) HttpStatusCode.Unauthorized)] + [ProducesResponseType(typeof(ErrorsRootObject), (int) HttpStatusCode.BadRequest)] [GetRequestsErrorInterceptorActionFilter] public IActionResult GetAllStores(string fields = "") { var allStores = StoreService.GetAllStores(); - + IList storesAsDto = new List(); foreach (var store in allStores) @@ -110,10 +108,10 @@ public IActionResult GetAllStores(string fields = "") storesAsDto.Add(storeDto); } - var storesRootObject = new StoresRootObject() - { - Stores = storesAsDto - }; + var storesRootObject = new StoresRootObject + { + Stores = storesAsDto + }; var json = JsonFieldsSerializer.Serialize(storesRootObject, fields); diff --git a/Nop.Plugin.Api/Controllers/TokenController.cs b/Nop.Plugin.Api/Controllers/TokenController.cs new file mode 100644 index 0000000..5e6771f --- /dev/null +++ b/Nop.Plugin.Api/Controllers/TokenController.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.IdentityModel.Tokens; +using Nop.Core.Domain.Customers; +using Nop.Plugin.Api.Configuration; +using Nop.Plugin.Api.Domain; +using Nop.Plugin.Api.Infrastructure; +using Nop.Plugin.Api.Models.Authentication; +using Nop.Services.Customers; +using Nop.Services.Logging; + +namespace Nop.Plugin.Api.Controllers +{ + [AllowAnonymous] + public class TokenController : Controller + { + private readonly ApiConfiguration _apiConfiguration; + private readonly ApiSettings _apiSettings; + private readonly ICustomerActivityService _customerActivityService; + private readonly ICustomerRegistrationService _customerRegistrationService; + private readonly ICustomerService _customerService; + private readonly CustomerSettings _customerSettings; + + public TokenController( + ICustomerService customerService, + ICustomerRegistrationService customerRegistrationService, + ICustomerActivityService customerActivityService, + CustomerSettings customerSettings, + ApiSettings apiSettings, + ApiConfiguration apiConfiguration) + { + _customerService = customerService; + _customerRegistrationService = customerRegistrationService; + _customerActivityService = customerActivityService; + _customerSettings = customerSettings; + _apiSettings = apiSettings; + _apiConfiguration = apiConfiguration; + } + + [Route("/token")] + [HttpGet] + public IActionResult Create(TokenRequest model) + { + if (string.IsNullOrEmpty(model.Username)) + { + return Json(new TokenResponse("Missing username")); + } + + if (string.IsNullOrEmpty(model.Password)) + { + return Json(new TokenResponse("Missing password")); + } + + var customer = ValidateUser(model); + + if (customer != null) + { + return Json(GenerateToken(customer)); + } + + return Json(new TokenResponse("Access Denied")); + } + + private CustomerLoginResults LoginCustomer(TokenRequest model) + { + var loginResult = _customerRegistrationService + .ValidateCustomer(model.Username, model.Password); + + return loginResult; + } + + private Customer ValidateUser(TokenRequest model) + { + var result = LoginCustomer(model); + + if (result == CustomerLoginResults.Successful) + { + var customer = _customerSettings.UsernamesEnabled + ? _customerService.GetCustomerByUsername(model.Username) + : _customerService.GetCustomerByEmail(model.Username); + + + //activity log + _customerActivityService.InsertActivity(customer, "Api.TokenRequest", "User API token request", customer); + + return customer; + } + + return null; + } + + private int GetTokenExpiryInDays() + { + return _apiSettings.TokenExpiryInDays <= 0 + ? Constants.Configurations.DefaultAccessTokenExpirationInDays + : _apiSettings.TokenExpiryInDays; + } + + private TokenResponse GenerateToken(Customer customer) + { + var expiresInSeconds = new DateTimeOffset(DateTime.Now.AddDays(GetTokenExpiryInDays())).ToUnixTimeSeconds(); + + var claims = new List + { + new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()), + new Claim(JwtRegisteredClaimNames.Exp, expiresInSeconds.ToString()), + new Claim(ClaimTypes.Email, customer.Email), + new Claim(ClaimTypes.NameIdentifier, customer.CustomerGuid.ToString()), + _customerSettings.UsernamesEnabled + ? new Claim(ClaimTypes.Name, customer.Username) + : new Claim(ClaimTypes.Name, customer.Email) + }; + + var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_apiConfiguration.SecurityKey)), + SecurityAlgorithms.HmacSha256); + var token = new JwtSecurityToken(new JwtHeader(signingCredentials), new JwtPayload(claims)); + var accessToken = new JwtSecurityTokenHandler().WriteToken(token); + + + return new TokenResponse(accessToken, expiresInSeconds); + } + } +} diff --git a/Nop.Plugin.Api/Controllers/WebHookFiltersController.cs b/Nop.Plugin.Api/Controllers/WebHookFiltersController.cs deleted file mode 100644 index 14a1feb..0000000 --- a/Nop.Plugin.Api/Controllers/WebHookFiltersController.cs +++ /dev/null @@ -1,60 +0,0 @@ -//using System.Collections.Generic; -//using System.Threading.Tasks; -//using Microsoft.AspNetCore.Mvc; -//using Nop.Plugin.Api.Attributes; -//using Nop.Plugin.Api.JSON.Serializers; -//using Nop.Services.Customers; -//using Nop.Services.Discounts; -//using Nop.Services.Localization; -//using Nop.Services.Logging; -//using Nop.Services.Media; -//using Nop.Services.Security; -//using Nop.Services.Stores; - -//namespace Nop.Plugin.Api.Controllers -//{ -// using System.Net; -// using Microsoft.AspNet.WebHooks; -// using Microsoft.AspNetCore.Authentication.JwtBearer; -// using Microsoft.AspNetCore.Authorization; -// using Nop.Plugin.Api.Services; - -// [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] -// public class WebHookFiltersController : BaseApiController -// { -// private readonly IWebHookFilterManager _filterManager; - -// public WebHookFiltersController(IJsonFieldsSerializer jsonFieldsSerializer, -// IAclService aclService, -// ICustomerService customerService, -// IStoreMappingService storeMappingService, -// IStoreService storeService, -// IDiscountService discountService, -// ICustomerActivityService customerActivityService, -// ILocalizationService localizationService, -// IPictureService pictureService, -// IWebHookService webHookService) : -// base(jsonFieldsSerializer, -// aclService, -// customerService, -// storeMappingService, -// storeService, -// discountService, -// customerActivityService, -// localizationService, -// pictureService) -// { -// _filterManager = webHookService.GetWebHookFilterManager(); -// } - -// [HttpGet] -// [Route("/api/webhooks/filters")] -// [ProducesResponseType(typeof(IEnumerable), (int)HttpStatusCode.OK)] -// [GetRequestsErrorInterceptorActionFilter] -// public async Task> GetWebHookFilters() -// { -// IDictionary filters = await _filterManager.GetAllWebHookFiltersAsync(); -// return filters.Values; -// } -// } -//} diff --git a/Nop.Plugin.Api/Controllers/WebHookRegistrationsController.cs b/Nop.Plugin.Api/Controllers/WebHookRegistrationsController.cs deleted file mode 100644 index d801c11..0000000 --- a/Nop.Plugin.Api/Controllers/WebHookRegistrationsController.cs +++ /dev/null @@ -1,434 +0,0 @@ -//using Nop.Plugin.Api.Attributes; -//using System; -//using System.Collections.Generic; -//using System.Linq; -//using System.Threading.Tasks; -//using Nop.Plugin.Api.JSON.Serializers; -//using Nop.Services.Customers; -//using Nop.Services.Discounts; -//using Nop.Services.Localization; -//using Nop.Services.Logging; -//using Nop.Services.Security; -//using Nop.Services.Stores; -//using Nop.Core.Domain.Stores; -//using System.Net.Http; -//using System.Net; -//using System.Globalization; -//using Nop.Core; -//using Nop.Plugin.Api.Constants; -//using Nop.Services.Media; -//using Microsoft.AspNetCore.Mvc; -//using Microsoft.AspNet.WebHooks; -//using Nop.Plugin.Api.Services; - -//namespace Nop.Plugin.Api.Controllers -//{ -// using System.Security; -// using System.Security.Claims; -// using IdentityServer4.EntityFramework.Entities; -// using IdentityServer4.Stores; -// using Microsoft.AspNetCore.Authentication.JwtBearer; -// using Microsoft.AspNetCore.Authorization; -// using Microsoft.AspNetCore.Http; -// using Nop.Plugin.Api.JSON.Serializers; - -// [ApiAuthorize(Policy = JwtBearerDefaults.AuthenticationScheme, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] -// public class WebHookRegistrationsController : BaseApiController -// { -// private const string ErrorPropertyKey = "webhook"; -// private const string PRIVATE_FILTER_PREFIX = "MS_Private_"; - -// private readonly IWebHookManager _manager; -// private readonly IWebHookStore _store; -// private readonly IWebHookFilterManager _filterManager; -// private readonly IStoreContext _storeContext; -// private readonly IHttpContextAccessor _httpContextAccessor; -// private readonly IClientStore _clientStore; - -// public WebHookRegistrationsController(IJsonFieldsSerializer jsonFieldsSerializer, -// IAclService aclService, -// ICustomerService customerService, -// IStoreMappingService storeMappingService, -// IStoreService storeService, -// IDiscountService discountService, -// ICustomerActivityService customerActivityService, -// ILocalizationService localizationService, -// IPictureService pictureService, -// IStoreContext storeContext, -// IWebHookService webHookService, -// IHttpContextAccessor httpContextAccessor, -// IClientStore clientStore) -// : base(jsonFieldsSerializer, -// aclService, customerService, -// storeMappingService, -// storeService, -// discountService, -// customerActivityService, -// localizationService, -// pictureService) -// { -// _storeContext = storeContext; -// _manager = webHookService.GetWebHookManager(); -// _store = webHookService.GetWebHookStore(); -// _filterManager = webHookService.GetWebHookFilterManager(); -// _httpContextAccessor = httpContextAccessor; -// _clientStore = clientStore; -// } - -// /// -// /// Gets all registered WebHooks for a given user. -// /// -// /// A collection containing the registered instances for a given user. -// [HttpGet] -// [Route("/api/webhooks/registrations")] -// [ProducesResponseType(typeof(IEnumerable), (int)HttpStatusCode.OK)] -// [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] -// [GetRequestsErrorInterceptorActionFilter] -// public async Task> GetAllWebHooks() -// { -// string userId = GetUserId(); -// IEnumerable webHooks = await _store.GetAllWebHooksAsync(userId); -// RemovePrivateFilters(webHooks); -// return webHooks; -// } - -// /// -// /// Looks up a registered WebHook with the given for a given user. -// /// -// /// The registered instance for a given user. -// [HttpGet] -// [Route("/api/webhooks/registrations/{id}",Name = WebHookNames.GetWebhookByIdAction)] -// [ProducesResponseType(typeof(WebHook), (int)HttpStatusCode.OK)] -// [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] -// [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] -// [GetRequestsErrorInterceptorActionFilter] -// public async Task GetWebHookById(string id) -// { -// string userId = GetUserId(); -// WebHook webHook = await _store.LookupWebHookAsync(userId, id); -// if (webHook != null) -// { -// RemovePrivateFilters(new[] { webHook }); -// return Ok(webHook); -// } - -// return NotFound(); -// } - -// /// -// /// Registers a new WebHook for a given user. -// /// -// /// The to create. -// [HttpPost] -// [Route("/api/webhooks/registrations")] -// [ProducesResponseType(typeof(StoreResult), (int)HttpStatusCode.OK)] -// [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] -// [ProducesResponseType(typeof(HttpResponseMessage), (int)HttpStatusCode.InternalServerError)] -// [ProducesResponseType(typeof(HttpResponseMessage), (int)HttpStatusCode.Conflict)] -// [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] -// public async Task RegisterWebHook([FromBody]WebHook webHook) -// { -// if (!ModelState.IsValid) -// { -// return Error(); -// } - -// if (webHook == null) -// { -// return BadRequest(); -// } - -// string userId = GetUserId(); - -// try -// { -// await VerifyFilters(webHook); -// await VerifyWebHook(webHook); -// } -// catch (VerificationException ex) -// { -// return BadRequest(ex.Message); -// } - -// // In order to ensure that a web hook filter is not registered multiple times for the same uri -// // we remove the already registered filters from the current web hook. -// // If the same filters are registered multiple times with the same uri, the web hook event will be -// // sent for each registration. -// IEnumerable existingWebhooks = await GetAllWebHooks(); -// IEnumerable existingWebhooksForTheSameUri = existingWebhooks.Where(wh => wh.WebHookUri == webHook.WebHookUri); - -// foreach (var existingWebHook in existingWebhooksForTheSameUri) -// { -// webHook.Filters.ExceptWith(existingWebHook.Filters); - -// if (!webHook.Filters.Any()) -// { -// string msg = _localizationService.GetResource("Api.WebHooks.CouldNotRegisterDuplicateWebhook"); -// return Error(HttpStatusCode.Conflict, ErrorPropertyKey, msg); -// } -// } - -// try -// { -// // Validate the provided WebHook ID (or force one to be created on server side) -// if (Request == null) -// { -// throw new ArgumentNullException(nameof(Request)); -// } - -// // Ensure we have a normalized ID for the WebHook -// webHook.Id = null; - -// // Add WebHook for this user. -// StoreResult result = await _store.InsertWebHookAsync(userId, webHook); - -// if (result == StoreResult.Success) -// { -// return CreatedAtRoute(WebHookNames.GetWebhookByIdAction, new { id = webHook.Id }, webHook); -// } -// return CreateHttpResult(result); -// } -// catch (Exception ex) -// { -// string msg = string.Format(CultureInfo.InvariantCulture, _localizationService.GetResource("Api.WebHooks.CouldNotRegisterWebhook"), ex.Message); -// //Configuration.DependencyResolver.GetLogger().Error(msg, ex); -// return Error(HttpStatusCode.Conflict, ErrorPropertyKey, msg); -// } -// } - -// /// -// /// Updates an existing WebHook registration. -// /// -// /// The WebHook ID. -// /// The new to use. -// [HttpPut] -// [Route("/api/webhooks/registrations/{id}")] -// [ProducesResponseType(typeof(StoreResult), (int)HttpStatusCode.OK)] -// [ProducesResponseType(typeof(string), (int)HttpStatusCode.NotFound)] -// [ProducesResponseType(typeof(HttpResponseMessage), (int)HttpStatusCode.InternalServerError)] -// [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] -// [ProducesResponseType(typeof(string), (int)HttpStatusCode.BadRequest)] -// public async Task UpdateWebHook(string id, WebHook webHook) -// { -// if (webHook == null) -// { -// return BadRequest(); -// } -// if (!string.Equals(id, webHook.Id, StringComparison.OrdinalIgnoreCase)) -// { -// return BadRequest(); -// } - -// string userId = GetUserId(); -// await VerifyFilters(webHook); -// await VerifyWebHook(webHook); - -// try -// { -// StoreResult result = await _store.UpdateWebHookAsync(userId, webHook); -// return CreateHttpResult(result); -// } -// catch (Exception ex) -// { -// string msg = string.Format(CultureInfo.InvariantCulture, _localizationService.GetResource("Api.WebHooks.CouldNotUpdateWebhook"), ex.Message); -// // Configuration.DependencyResolver.GetLogger().Error(msg, ex); -// return Error(HttpStatusCode.InternalServerError, ErrorPropertyKey, msg); -// } -// } - -// /// -// /// Deletes an existing WebHook registration. -// /// -// /// The WebHook ID. -// [HttpDelete] -// [Route("/api/webhooks/registrations/{id}")] -// [ProducesResponseType(typeof(StoreResult), (int)HttpStatusCode.OK)] -// [ProducesResponseType(typeof(HttpResponseMessage), (int)HttpStatusCode.InternalServerError)] -// [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] -// public async Task DeleteWebHook(string id) -// { -// string userId = GetUserId(); - -// try -// { -// StoreResult result = await _store.DeleteWebHookAsync(userId, id); -// return CreateHttpResult(result); -// } -// catch (Exception ex) -// { -// string msg = string.Format(CultureInfo.InvariantCulture, _localizationService.GetResource("Api.WebHooks.CouldNotDeleteWebhook"), ex.Message); -// //Configuration.DependencyResolver.GetLogger().Error(msg, ex); -// return Error(HttpStatusCode.InternalServerError, ErrorPropertyKey, msg); -// } -// } - -// /// -// /// Deletes all existing WebHook registrations. -// /// -// [HttpDelete] -// [Route("/api/webhooks/registrations")] -// [ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)] -// [ProducesResponseType(typeof(HttpResponseMessage), (int)HttpStatusCode.InternalServerError)] -// [ProducesResponseType(typeof(string), (int)HttpStatusCode.Unauthorized)] -// public async Task DeleteAllWebHooks() -// { -// string userId = GetUserId(); - -// try -// { -// await _store.DeleteAllWebHooksAsync(userId); -// return Ok(); -// } -// catch (Exception ex) -// { -// string msg = string.Format(CultureInfo.InvariantCulture, _localizationService.GetResource("Api.WebHooks.CouldNotDeleteWebhooks"), ex.Message); -// // Configuration.DependencyResolver.GetLogger().Error(msg, ex); -// return Error(HttpStatusCode.InternalServerError, ErrorPropertyKey, msg); -// } -// } - -// /// -// /// Ensure that the provided only has registered filters. -// /// -// protected virtual async Task VerifyFilters(WebHook webHook) -// { -// if (webHook == null) -// { -// throw new ArgumentNullException(nameof(webHook)); -// } - -// // If there are no filters then add our wildcard filter. -// if (webHook.Filters.Count == 0) -// { -// webHook.Filters.Add(WildcardWebHookFilterProvider.Name); -// return; -// } - -// IDictionary filters = await _filterManager.GetAllWebHookFiltersAsync(); -// HashSet normalizedFilters = new HashSet(); -// List invalidFilters = new List(); -// foreach (string filter in webHook.Filters) -// { -// WebHookFilter hookFilter; -// if (filters.TryGetValue(filter, out hookFilter)) -// { -// normalizedFilters.Add(hookFilter.Name); -// } -// else -// { -// invalidFilters.Add(filter); -// } -// } - -// if (invalidFilters.Count > 0) -// { -// string invalidFiltersMsg = string.Join(", ", invalidFilters); -// string link = Url.Link(WebHookNames.FiltersGetAction, null); -// string msg = string.Format(CultureInfo.CurrentCulture, _localizationService.GetResource("Api.WebHooks.InvalidFilters"), invalidFiltersMsg, link); -// //Configuration.DependencyResolver.GetLogger().Info(msg); - -// throw new VerificationException(msg); -// } -// else -// { -// webHook.Filters.Clear(); -// foreach (string filter in normalizedFilters) -// { -// webHook.Filters.Add(filter); -// } -// } -// } - -// /// -// /// Removes all private filters from registered WebHooks. -// /// -// protected virtual void RemovePrivateFilters(IEnumerable webHooks) -// { -// if (webHooks == null) -// { -// throw new ArgumentNullException(nameof(webHooks)); -// } - -// foreach (WebHook webHook in webHooks) -// { -// var filters = webHook.Filters.Where(f => f.StartsWith(PRIVATE_FILTER_PREFIX, StringComparison.OrdinalIgnoreCase)).ToArray(); -// foreach (string filter in filters) -// { -// webHook.Filters.Remove(filter); -// } -// } -// } - -// /// -// /// Ensures that the provided has a reachable Web Hook URI unless -// /// the WebHook URI has a NoEcho query parameter. -// /// -// private async Task VerifyWebHook(WebHook webHook) -// { -// if (webHook == null) -// { -// throw new ArgumentNullException(nameof(webHook)); -// } - -// // If no secret is provided then we create one here. This allows for scenarios -// // where the caller may use a secret directly embedded in the WebHook URI, or -// // has some other way of enforcing security. -// if (string.IsNullOrEmpty(webHook.Secret)) -// { -// webHook.Secret = Guid.NewGuid().ToString("N"); -// } - -// try -// { -// await _manager.VerifyWebHookAsync(webHook); -// } -// catch (Exception ex) -// { -// throw new VerificationException(ex.Message); -// } -// } - -// /// -// /// Gets the user ID for this request. -// /// -// private string GetUserId() -// { -// // If we are here the client is already authorized. -// // So there is a client ID and the client is active. -// var clientId = -// _httpContextAccessor.HttpContext.User.FindFirst("client_id")?.Value; - -// var storeId = _storeContext.CurrentStore.Id; - -// var webHookUser = clientId + "-" + storeId; - -// return webHookUser; -// } - -// /// -// /// Creates an based on the provided . -// /// -// /// The result to use when creating the . -// /// An initialized . -// private IActionResult CreateHttpResult(StoreResult result) -// { -// switch (result) -// { -// case StoreResult.Success: -// return Ok(); - -// case StoreResult.Conflict: -// return Error(HttpStatusCode.Conflict); - -// case StoreResult.NotFound: -// return NotFound(); - -// case StoreResult.OperationError: -// return BadRequest(); - -// default: -// return Error(HttpStatusCode.InternalServerError); -// } -// } -// } -//} diff --git a/Nop.Plugin.Api/Converters/ApiTypeConverter.cs b/Nop.Plugin.Api/Converters/ApiTypeConverter.cs index b27c343..8190f22 100644 --- a/Nop.Plugin.Api/Converters/ApiTypeConverter.cs +++ b/Nop.Plugin.Api/Converters/ApiTypeConverter.cs @@ -8,7 +8,7 @@ namespace Nop.Plugin.Api.Converters public class ApiTypeConverter : IApiTypeConverter { /// - /// Converts the value, which should be in ISO 8601 format to UTC time or null if not valid + /// Converts the value, which should be in ISO 8601 format to UTC time or null if not valid /// /// The time format in ISO 8601. If no timezone or offset specified we assume it is in UTC /// The time in UTC or null if the time is not valid @@ -16,16 +16,10 @@ public class ApiTypeConverter : IApiTypeConverter { DateTime result; - var formats = new string[] - { - "yyyy", - "yyyy-MM", - "yyyy-MM-dd", - "yyyy-MM-ddTHH:mm", - "yyyy-MM-ddTHH:mm:ss", - "yyyy-MM-ddTHH:mm:sszzz", - "yyyy-MM-ddTHH:mm:ss.FFFFFFFK" - }; + var formats = new[] + { + "yyyy", "yyyy-MM", "yyyy-MM-dd", "yyyy-MM-ddTHH:mm", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-ddTHH:mm:sszzz", "yyyy-MM-ddTHH:mm:ss.FFFFFFFK" + }; if (DateTime.TryParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out result)) { @@ -69,7 +63,10 @@ public IList ToListOfInts(string value) { if (!string.IsNullOrEmpty(value)) { - var stringIds = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); + var stringIds = value.Split(new[] + { + ',' + }, StringSplitOptions.RemoveEmptyEntries).ToList(); var intIds = new List(); foreach (var id in stringIds) @@ -82,7 +79,9 @@ public IList ToListOfInts(string value) } intIds = intIds.Distinct().ToList(); - return intIds.Count > 0 ? intIds : null; + return intIds.Count > 0 + ? intIds + : null; } return null; @@ -96,7 +95,7 @@ public IList ToListOfInts(string value) { return true; } - else if (value.Equals("unpublished", StringComparison.InvariantCultureIgnoreCase)) + if (value.Equals("unpublished", StringComparison.InvariantCultureIgnoreCase)) { return false; } @@ -122,4 +121,4 @@ public object ToEnumNullable(string value, Type type) return null; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Converters/IApiTypeConverter.cs b/Nop.Plugin.Api/Converters/IApiTypeConverter.cs index d1304a1..dbbc9d6 100644 --- a/Nop.Plugin.Api/Converters/IApiTypeConverter.cs +++ b/Nop.Plugin.Api/Converters/IApiTypeConverter.cs @@ -12,4 +12,4 @@ public interface IApiTypeConverter bool? ToStatus(string value); object ToEnumNullable(string value, Type type); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Converters/IObjectConverter.cs b/Nop.Plugin.Api/Converters/IObjectConverter.cs index c9e600a..6e2dcea 100644 --- a/Nop.Plugin.Api/Converters/IObjectConverter.cs +++ b/Nop.Plugin.Api/Converters/IObjectConverter.cs @@ -7,4 +7,4 @@ public interface IObjectConverter T ToObject(ICollection> source) where T : class, new(); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Converters/ObjectConverter.cs b/Nop.Plugin.Api/Converters/ObjectConverter.cs index 0d3c2a3..4c6f8dd 100644 --- a/Nop.Plugin.Api/Converters/ObjectConverter.cs +++ b/Nop.Plugin.Api/Converters/ObjectConverter.cs @@ -25,7 +25,7 @@ public T ToObject(ICollection> source) { var itemKey = item.Key.Replace("_", string.Empty); var currentProperty = someObjectType.GetProperty(itemKey, - BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); + BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (currentProperty != null) { @@ -43,24 +43,24 @@ private object To(string value, Type type) { return _apiTypeConverter.ToUtcDateTimeNullable(value); } - else if (type == typeof (int?)) + if (type == typeof(int?)) { return _apiTypeConverter.ToIntNullable(value); } - else if (type == typeof(int)) + if (type == typeof(int)) { return _apiTypeConverter.ToInt(value); } - else if (type == typeof(List)) + if (type == typeof(List)) { return _apiTypeConverter.ToListOfInts(value); } - else if(type == typeof(bool?)) + if (type == typeof(bool?)) { // Because currently status is the only boolean and we need to accept published and unpublished statuses. return _apiTypeConverter.ToStatus(value); } - else if (IsNullableEnum(type)) + if (IsNullableEnum(type)) { return _apiTypeConverter.ToEnumNullable(value, type); } @@ -72,7 +72,7 @@ private object To(string value, Type type) private bool IsNullableEnum(Type t) { var u = Nullable.GetUnderlyingType(t); - return (u != null) && u.IsEnum; + return u != null && u.IsEnum; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/AddressDto.cs b/Nop.Plugin.Api/DTOs/AddressDto.cs index 35292d1..b65ee14 100644 --- a/Nop.Plugin.Api/DTOs/AddressDto.cs +++ b/Nop.Plugin.Api/DTOs/AddressDto.cs @@ -1,107 +1,107 @@ using System; using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; -using Nop.Plugin.Api.Validators; +using Nop.Plugin.Api.DTO.Base; -namespace Nop.Plugin.Api.DTOs +namespace Nop.Plugin.Api.DTO { [JsonObject(Title = "address")] + //[Validator(typeof(AddressDtoValidator))] public class AddressDto : BaseDto { /// - /// Gets or sets the first name + /// Gets or sets the first name /// [JsonProperty("first_name")] public string FirstName { get; set; } /// - /// Gets or sets the last name + /// Gets or sets the last name /// [JsonProperty("last_name")] public string LastName { get; set; } /// - /// Gets or sets the email + /// Gets or sets the email /// [JsonProperty("email")] public string Email { get; set; } /// - /// Gets or sets the company + /// Gets or sets the company /// [JsonProperty("company")] public string Company { get; set; } /// - /// Gets or sets the country identifier + /// Gets or sets the country identifier /// [JsonProperty("country_id")] public int? CountryId { get; set; } /// - /// Gets or sets the country name + /// Gets or sets the country name /// [JsonProperty("country")] public string CountryName { get; set; } /// - /// Gets or sets the state/province identifier + /// Gets or sets the state/province identifier /// [JsonProperty("state_province_id")] public int? StateProvinceId { get; set; } /// - /// Gets or sets the city + /// Gets or sets the city /// [JsonProperty("city")] public string City { get; set; } /// - /// Gets or sets the address 1 + /// Gets or sets the address 1 /// [JsonProperty("address1")] public string Address1 { get; set; } /// - /// Gets or sets the address 2 + /// Gets or sets the address 2 /// [JsonProperty("address2")] public string Address2 { get; set; } /// - /// Gets or sets the zip/postal code + /// Gets or sets the zip/postal code /// [JsonProperty("zip_postal_code")] public string ZipPostalCode { get; set; } /// - /// Gets or sets the phone number + /// Gets or sets the phone number /// [JsonProperty("phone_number")] public string PhoneNumber { get; set; } /// - /// Gets or sets the fax number + /// Gets or sets the fax number /// [JsonProperty("fax_number")] public string FaxNumber { get; set; } /// - /// Gets or sets the custom attributes (see "AddressAttribute" entity for more info) + /// Gets or sets the custom attributes (see "AddressAttribute" entity for more info) /// [JsonProperty("customer_attributes")] public string CustomAttributes { get; set; } /// - /// Gets or sets the date and time of instance creation + /// Gets or sets the date and time of instance creation /// [JsonProperty("created_on_utc")] public DateTime? CreatedOnUtc { get; set; } /// - /// Gets or sets the state/province + /// Gets or sets the state/province /// [JsonProperty("province")] public string StateProvinceName { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Base/BaseDto.cs b/Nop.Plugin.Api/DTOs/Base/BaseDto.cs index 539a687..72e9247 100644 --- a/Nop.Plugin.Api/DTOs/Base/BaseDto.cs +++ b/Nop.Plugin.Api/DTOs/Base/BaseDto.cs @@ -1,10 +1,10 @@ using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Base +namespace Nop.Plugin.Api.DTO.Base { public abstract class BaseDto { [JsonProperty("id")] public int Id { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Categories/CategoriesCountRootObject.cs b/Nop.Plugin.Api/DTOs/Categories/CategoriesCountRootObject.cs index 49e6902..67fe568 100644 --- a/Nop.Plugin.Api/DTOs/Categories/CategoriesCountRootObject.cs +++ b/Nop.Plugin.Api/DTOs/Categories/CategoriesCountRootObject.cs @@ -1,10 +1,10 @@ using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Categories +namespace Nop.Plugin.Api.DTO.Categories { public class CategoriesCountRootObject { [JsonProperty("count")] public int Count { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Categories/CategoriesRootObject.cs b/Nop.Plugin.Api/DTOs/Categories/CategoriesRootObject.cs index 11d8252..72d980a 100644 --- a/Nop.Plugin.Api/DTOs/Categories/CategoriesRootObject.cs +++ b/Nop.Plugin.Api/DTOs/Categories/CategoriesRootObject.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Categories +namespace Nop.Plugin.Api.DTO.Categories { public class CategoriesRootObject : ISerializableObject { @@ -21,7 +21,7 @@ public string GetPrimaryPropertyName() public Type GetPrimaryPropertyType() { - return typeof (CategoryDto); + return typeof(CategoryDto); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Categories/CategoryDto.cs b/Nop.Plugin.Api/DTOs/Categories/CategoryDto.cs index 44d2caf..0ed41ef 100644 --- a/Nop.Plugin.Api/DTOs/Categories/CategoryDto.cs +++ b/Nop.Plugin.Api/DTOs/Categories/CategoryDto.cs @@ -1,199 +1,145 @@ using System; using System.Collections.Generic; using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; -using Nop.Plugin.Api.DTOs.Images; -using Nop.Plugin.Api.DTOs.Languages; -using Nop.Plugin.Api.Validators; +using Nop.Plugin.Api.DTO.Base; +using Nop.Plugin.Api.DTO.Images; +using Nop.Plugin.Api.DTO.Languages; -namespace Nop.Plugin.Api.DTOs.Categories +namespace Nop.Plugin.Api.DTO.Categories { + //[Validator(typeof(CategoryDtoValidator))] [JsonObject(Title = "category")] public class CategoryDto : BaseDto { - private ImageDto _imageDto; - private List _localizedNames; - private List _storeIds; - private List _discountIds; - private List _roleIds; - [JsonProperty("name")] public string Name { get; set; } /// - /// Gets or sets the localized names + /// Gets or sets the localized names /// [JsonProperty("localized_names")] - public List LocalizedNames - { - get - { - return _localizedNames; - } - set - { - _localizedNames = value; - } - } + public List LocalizedNames { get; set; } /// - /// Gets or sets the description + /// Gets or sets the description /// [JsonProperty("description")] public string Description { get; set; } /// - /// Gets or sets a value of used category template identifier + /// Gets or sets a value of used category template identifier /// [JsonProperty("category_template_id")] public int? CategoryTemplateId { get; set; } /// - /// Gets or sets the meta keywords + /// Gets or sets the meta keywords /// [JsonProperty("meta_keywords")] public string MetaKeywords { get; set; } /// - /// Gets or sets the meta description + /// Gets or sets the meta description /// [JsonProperty("meta_description")] public string MetaDescription { get; set; } /// - /// Gets or sets the meta title + /// Gets or sets the meta title /// [JsonProperty("meta_title")] public string MetaTitle { get; set; } /// - /// Gets or sets the parent category identifier + /// Gets or sets the parent category identifier /// [JsonProperty("parent_category_id")] public int? ParentCategoryId { get; set; } /// - /// Gets or sets the page size + /// Gets or sets the page size /// [JsonProperty("page_size")] public int? PageSize { get; set; } /// - /// Gets or sets the available customer selectable page size options + /// Gets or sets the available customer selectable page size options /// [JsonProperty("page_size_options")] public string PageSizeOptions { get; set; } /// - /// Gets or sets the available price ranges + /// Gets or sets the available price ranges /// [JsonProperty("price_ranges")] public string PriceRanges { get; set; } /// - /// Gets or sets a value indicating whether to show the category on home page + /// Gets or sets a value indicating whether to show the category on home page /// [JsonProperty("show_on_home_page")] public bool? ShowOnHomePage { get; set; } /// - /// Gets or sets a value indicating whether to include this category in the top menu + /// Gets or sets a value indicating whether to include this category in the top menu /// [JsonProperty("include_in_top_menu")] public bool? IncludeInTopMenu { get; set; } /// - /// Gets or sets a value indicating whether this category has discounts applied - /// The same as if we run category.AppliedDiscounts.Count > 0 - /// We use this property for performance optimization: - /// if this property is set to false, then we do not need to load Applied Discounts navigation property - /// + /// Gets or sets a value indicating whether this category has discounts applied + /// + /// The same as if we run category.AppliedDiscounts.Count > 0 + /// We use this property for performance optimization: + /// if this property is set to false, then we do not need to load Applied Discounts navigation property + /// /// [JsonProperty("has_discounts_applied")] public bool? HasDiscountsApplied { get; set; } /// - /// Gets or sets a value indicating whether the entity is published + /// Gets or sets a value indicating whether the entity is published /// [JsonProperty("published")] public bool? Published { get; set; } /// - /// Gets or sets a value indicating whether the entity has been deleted + /// Gets or sets a value indicating whether the entity has been deleted /// [JsonProperty("deleted")] public bool? Deleted { get; set; } /// - /// Gets or sets the display order + /// Gets or sets the display order /// [JsonProperty("display_order")] public int? DisplayOrder { get; set; } /// - /// Gets or sets the date and time of instance creation + /// Gets or sets the date and time of instance creation /// [JsonProperty("created_on_utc")] public DateTime? CreatedOnUtc { get; set; } /// - /// Gets or sets the date and time of instance update + /// Gets or sets the date and time of instance update /// [JsonProperty("updated_on_utc")] public DateTime? UpdatedOnUtc { get; set; } [JsonProperty("role_ids")] - public List RoleIds - { - get - { - return _roleIds; - } - set - { - _roleIds = value; - } - } + public List RoleIds { get; set; } [JsonProperty("discount_ids")] - public List DiscountIds - { - get - { - return _discountIds; - } - set - { - _discountIds = value; - } - } + public List DiscountIds { get; set; } [JsonProperty("store_ids")] - public List StoreIds - { - get - { - return _storeIds; - } - set - { - _storeIds = value; - } - } + public List StoreIds { get; set; } [JsonProperty("image")] - public ImageDto Image { - get - { - return _imageDto; - } - set - { - _imageDto = value; - } - } + public ImageDto Image { get; set; } [JsonProperty("se_name")] public string SeName { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/CustomerRoles/CustomerRoleDto.cs b/Nop.Plugin.Api/DTOs/CustomerRoles/CustomerRoleDto.cs index 56c88c6..0efbbfa 100644 --- a/Nop.Plugin.Api/DTOs/CustomerRoles/CustomerRoleDto.cs +++ b/Nop.Plugin.Api/DTOs/CustomerRoles/CustomerRoleDto.cs @@ -1,57 +1,57 @@ using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; +using Nop.Plugin.Api.DTO.Base; -namespace Nop.Plugin.Api.DTOs.CustomerRoles +namespace Nop.Plugin.Api.DTO.CustomerRoles { [JsonObject(Title = "customer_role")] public class CustomerRoleDto : BaseDto { /// - /// Gets or sets the customer role name + /// Gets or sets the customer role name /// [JsonProperty("name")] public string Name { get; set; } /// - /// Gets or sets a value indicating whether the customer role is marked as free shiping + /// Gets or sets a value indicating whether the customer role is marked as free shiping /// [JsonProperty("free_shipping")] public bool? FreeShipping { get; set; } /// - /// Gets or sets a value indicating whether the customer role is marked as tax exempt + /// Gets or sets a value indicating whether the customer role is marked as tax exempt /// [JsonProperty("tax_exempt")] public bool? TaxExempt { get; set; } /// - /// Gets or sets a value indicating whether the customer role is active + /// Gets or sets a value indicating whether the customer role is active /// [JsonProperty("active")] public bool? Active { get; set; } /// - /// Gets or sets a value indicating whether the customer role is system + /// Gets or sets a value indicating whether the customer role is system /// [JsonProperty("is_system_role")] public bool? IsSystemRole { get; set; } /// - /// Gets or sets the customer role system name + /// Gets or sets the customer role system name /// [JsonProperty("system_name")] public string SystemName { get; set; } /// - /// Gets or sets a value indicating whether the customers must change passwords after a specified time + /// Gets or sets a value indicating whether the customers must change passwords after a specified time /// [JsonProperty("enable_password_lifetime")] public bool? EnablePasswordLifetime { get; set; } /// - /// Gets or sets a product identifier that is required by this customer role. - /// A customer is added to this customer role once a specified product is purchased. + /// Gets or sets a product identifier that is required by this customer role. + /// A customer is added to this customer role once a specified product is purchased. /// [JsonProperty("purchased_with_product_id")] public int? PurchasedWithProductId { get; set; } diff --git a/Nop.Plugin.Api/DTOs/CustomerRoles/CustomerRolesRootObject.cs b/Nop.Plugin.Api/DTOs/CustomerRoles/CustomerRolesRootObject.cs index a65a011..8450046 100644 --- a/Nop.Plugin.Api/DTOs/CustomerRoles/CustomerRolesRootObject.cs +++ b/Nop.Plugin.Api/DTOs/CustomerRoles/CustomerRolesRootObject.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.CustomerRoles +namespace Nop.Plugin.Api.DTO.CustomerRoles { public class CustomerRolesRootObject : ISerializableObject { diff --git a/Nop.Plugin.Api/DTOs/Customers/BaseCustomerDto.cs b/Nop.Plugin.Api/DTOs/Customers/BaseCustomerDto.cs index 13670dc..f571ef2 100644 --- a/Nop.Plugin.Api/DTOs/Customers/BaseCustomerDto.cs +++ b/Nop.Plugin.Api/DTOs/Customers/BaseCustomerDto.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; +using Nop.Plugin.Api.DTO.Base; -namespace Nop.Plugin.Api.DTOs.Customers +namespace Nop.Plugin.Api.DTO.Customers { public class BaseCustomerDto : BaseDto { @@ -14,8 +14,9 @@ public class BaseCustomerDto : BaseDto [JsonProperty("username")] public string Username { get; set; } + /// - /// Gets or sets the email + /// Gets or sets the email /// [JsonProperty("email")] public string Email { get; set; } @@ -36,84 +37,86 @@ public class BaseCustomerDto : BaseDto public string Gender { get; set; } /// - /// Gets or sets the admin comment + /// Gets or sets the admin comment /// [JsonProperty("admin_comment")] public string AdminComment { get; set; } /// - /// Gets or sets a value indicating whether the customer is tax exempt + /// Gets or sets a value indicating whether the customer is tax exempt /// [JsonProperty("is_tax_exempt")] public bool? IsTaxExempt { get; set; } /// - /// Gets or sets a value indicating whether this customer has some products in the shopping cart - /// The same as if we run this.ShoppingCartItems.Count > 0 - /// We use this property for performance optimization: - /// if this property is set to false, then we do not need to load "ShoppingCartItems" navigation property for each page load - /// It's used only in a couple of places in the presenation layer - /// + /// Gets or sets a value indicating whether this customer has some products in the shopping cart + /// + /// The same as if we run this.ShoppingCartItems.Count > 0 + /// We use this property for performance optimization: + /// if this property is set to false, then we do not need to load "ShoppingCartItems" navigation property for each + /// page load + /// It's used only in a couple of places in the presenation layer + /// /// [JsonProperty("has_shopping_cart_items")] public bool? HasShoppingCartItems { get; set; } /// - /// Gets or sets a value indicating whether the customer is active + /// Gets or sets a value indicating whether the customer is active /// [JsonProperty("active")] public bool? Active { get; set; } /// - /// Gets or sets a value indicating whether the customer has been deleted + /// Gets or sets a value indicating whether the customer has been deleted /// [JsonProperty("deleted")] public bool? Deleted { get; set; } /// - /// Gets or sets a value indicating whether the customer account is system + /// Gets or sets a value indicating whether the customer account is system /// [JsonProperty("is_system_account")] public bool? IsSystemAccount { get; set; } /// - /// Gets or sets the customer system name + /// Gets or sets the customer system name /// [JsonProperty("system_name")] public string SystemName { get; set; } /// - /// Gets or sets the last IP address + /// Gets or sets the last IP address /// [JsonProperty("last_ip_address")] public string LastIpAddress { get; set; } /// - /// Gets or sets the date and time of entity creation + /// Gets or sets the date and time of entity creation /// [JsonProperty("created_on_utc")] public DateTime? CreatedOnUtc { get; set; } /// - /// Gets or sets the date and time of last login + /// Gets or sets the date and time of last login /// [JsonProperty("last_login_date_utc")] public DateTime? LastLoginDateUtc { get; set; } /// - /// Gets or sets the date and time of last activity + /// Gets or sets the date and time of last activity /// [JsonProperty("last_activity_date_utc")] public DateTime? LastActivityDateUtc { get; set; } /// - /// Gets or sets the store identifier in which customer registered + /// Gets or sets the store identifier in which customer registered /// [JsonProperty("registered_in_store_id")] public int? RegisteredInStoreId { get; set; } /// - /// Gets or sets the subscribed to newsletter property + /// Gets or sets the subscribed to newsletter property /// [JsonProperty("subscribed_to_newsletter")] public bool SubscribedToNewsletter { get; set; } @@ -130,7 +133,7 @@ public List RoleIds return _roleIds; } - set { _roleIds = value; } - } + set => _roleIds = value; + } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Customers/CustomerAttributeMappingDto.cs b/Nop.Plugin.Api/DTOs/Customers/CustomerAttributeMappingDto.cs index 6350578..68dcf14 100644 --- a/Nop.Plugin.Api/DTOs/Customers/CustomerAttributeMappingDto.cs +++ b/Nop.Plugin.Api/DTOs/Customers/CustomerAttributeMappingDto.cs @@ -1,11 +1,11 @@ using Nop.Core.Domain.Common; using Nop.Core.Domain.Customers; -namespace Nop.Plugin.Api.DTOs.Customers +namespace Nop.Plugin.Api.DTO.Customers { public class CustomerAttributeMappingDto { public Customer Customer { get; set; } - public GenericAttribute Attribute { get; set; } + public GenericAttribute Attribute { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Customers/CustomerDto.cs b/Nop.Plugin.Api/DTOs/Customers/CustomerDto.cs index 81c0efa..2d2e737 100644 --- a/Nop.Plugin.Api/DTOs/Customers/CustomerDto.cs +++ b/Nop.Plugin.Api/DTOs/Customers/CustomerDto.cs @@ -1,16 +1,16 @@ using System.Collections.Generic; using Newtonsoft.Json; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.DTOs.ShoppingCarts; -using Nop.Plugin.Api.Validators; +using Nop.Plugin.Api.DTO.ShoppingCarts; -namespace Nop.Plugin.Api.DTOs.Customers +namespace Nop.Plugin.Api.DTO.Customers { [JsonObject(Title = "customer")] + //[Validator(typeof(CustomerDtoValidator))] public class CustomerDto : BaseCustomerDto { - private ICollection _shoppingCartItems; private ICollection _addresses; + private ICollection _shoppingCartItems; [JsonIgnore] [JsonProperty("password")] @@ -19,7 +19,7 @@ public class CustomerDto : BaseCustomerDto #region Navigation properties /// - /// Gets or sets shopping cart items + /// Gets or sets shopping cart items /// [JsonProperty("shopping_cart_items")] [DoNotMap] @@ -34,23 +34,23 @@ public ICollection ShoppingCartItems return _shoppingCartItems; } - set { _shoppingCartItems = value; } + set => _shoppingCartItems = value; } /// - /// Default billing address + /// Default billing address /// [JsonProperty("billing_address")] public AddressDto BillingAddress { get; set; } /// - /// Default shipping address + /// Default shipping address /// [JsonProperty("shipping_address")] public AddressDto ShippingAddress { get; set; } /// - /// Gets or sets customer addresses + /// Gets or sets customer addresses /// [JsonProperty("addresses")] public ICollection Addresses @@ -64,8 +64,9 @@ public ICollection Addresses return _addresses; } - set { _addresses = value; } + set => _addresses = value; } + #endregion } } diff --git a/Nop.Plugin.Api/DTOs/Customers/CustomerForShoppingCartItemDto.cs b/Nop.Plugin.Api/DTOs/Customers/CustomerForShoppingCartItemDto.cs index 31ddaf9..6a14505 100644 --- a/Nop.Plugin.Api/DTOs/Customers/CustomerForShoppingCartItemDto.cs +++ b/Nop.Plugin.Api/DTOs/Customers/CustomerForShoppingCartItemDto.cs @@ -1,37 +1,32 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Customers +namespace Nop.Plugin.Api.DTO.Customers { // We need this DTO object to avoid loop in the entity to dto mappings. The difference is the missing ShoppingCartItems collection. [JsonObject(Title = "customers")] public class CustomerForShoppingCartItemDto : BaseCustomerDto { - private ICollection _addresses; - #region Navigation properties - + /// - /// Default billing address + /// Default billing address /// [JsonProperty("billing_address")] public AddressDto BillingAddress { get; set; } /// - /// Default shipping address + /// Default shipping address /// [JsonProperty("shipping_address")] public AddressDto ShippingAddress { get; set; } /// - /// Gets or sets customer addresses + /// Gets or sets customer addresses /// [JsonProperty("addresses")] - public ICollection Addresses - { - get { return _addresses; } - set { _addresses = value; } - } + public ICollection Addresses { get; set; } + #endregion } } diff --git a/Nop.Plugin.Api/DTOs/Customers/CustomersCountRootObject.cs b/Nop.Plugin.Api/DTOs/Customers/CustomersCountRootObject.cs index 9f84d7a..8ed770e 100644 --- a/Nop.Plugin.Api/DTOs/Customers/CustomersCountRootObject.cs +++ b/Nop.Plugin.Api/DTOs/Customers/CustomersCountRootObject.cs @@ -1,10 +1,10 @@ using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Customers +namespace Nop.Plugin.Api.DTO.Customers { public class CustomersCountRootObject { [JsonProperty("count")] - public int Count { get; set; } + public int Count { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Customers/CustomersRootObject.cs b/Nop.Plugin.Api/DTOs/Customers/CustomersRootObject.cs index aef1a99..41f66a2 100644 --- a/Nop.Plugin.Api/DTOs/Customers/CustomersRootObject.cs +++ b/Nop.Plugin.Api/DTOs/Customers/CustomersRootObject.cs @@ -2,15 +2,15 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Customers +namespace Nop.Plugin.Api.DTO.Customers { public class CustomersRootObject : ISerializableObject { public CustomersRootObject() { - Customers = new List(); + Customers = new List(); } - + [JsonProperty("customers")] public IList Customers { get; set; } @@ -21,7 +21,7 @@ public string GetPrimaryPropertyName() public Type GetPrimaryPropertyType() { - return typeof (CustomerDto); + return typeof(CustomerDto); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Customers/OrderCustomerDto.cs b/Nop.Plugin.Api/DTOs/Customers/OrderCustomerDto.cs index 4f11f87..af107e0 100644 --- a/Nop.Plugin.Api/DTOs/Customers/OrderCustomerDto.cs +++ b/Nop.Plugin.Api/DTOs/Customers/OrderCustomerDto.cs @@ -1,7 +1,6 @@ -namespace Nop.Plugin.Api.DTOs.Customers +namespace Nop.Plugin.Api.DTO.Customers { public class OrderCustomerDto : BaseCustomerDto { - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Errors/ErrorsRootObject.cs b/Nop.Plugin.Api/DTOs/Errors/ErrorsRootObject.cs index 8b5f66d..4966d6c 100644 --- a/Nop.Plugin.Api/DTOs/Errors/ErrorsRootObject.cs +++ b/Nop.Plugin.Api/DTOs/Errors/ErrorsRootObject.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Errors +namespace Nop.Plugin.Api.DTO.Errors { public class ErrorsRootObject : ISerializableObject { @@ -19,4 +19,4 @@ public Type GetPrimaryPropertyType() return Errors.GetType(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/ISerializableObject.cs b/Nop.Plugin.Api/DTOs/ISerializableObject.cs index b323e9c..687f505 100644 --- a/Nop.Plugin.Api/DTOs/ISerializableObject.cs +++ b/Nop.Plugin.Api/DTOs/ISerializableObject.cs @@ -1,10 +1,10 @@ using System; -namespace Nop.Plugin.Api.DTOs +namespace Nop.Plugin.Api.DTO { public interface ISerializableObject { string GetPrimaryPropertyName(); Type GetPrimaryPropertyType(); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Images/ImageDto.cs b/Nop.Plugin.Api/DTOs/Images/ImageDto.cs index e745115..d50b454 100644 --- a/Nop.Plugin.Api/DTOs/Images/ImageDto.cs +++ b/Nop.Plugin.Api/DTOs/Images/ImageDto.cs @@ -1,7 +1,7 @@ using Newtonsoft.Json; using Nop.Plugin.Api.Attributes; -namespace Nop.Plugin.Api.DTOs.Images +namespace Nop.Plugin.Api.DTO.Images { [ImageValidation] public class ImageDto @@ -18,4 +18,4 @@ public class ImageDto [JsonIgnore] public string MimeType { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Images/ImageMappingDto.cs b/Nop.Plugin.Api/DTOs/Images/ImageMappingDto.cs index 8b3b305..b49e7a6 100644 --- a/Nop.Plugin.Api/DTOs/Images/ImageMappingDto.cs +++ b/Nop.Plugin.Api/DTOs/Images/ImageMappingDto.cs @@ -1,7 +1,7 @@ using Newtonsoft.Json; using Nop.Plugin.Api.Attributes; -namespace Nop.Plugin.Api.DTOs.Images +namespace Nop.Plugin.Api.DTO.Images { [ImageValidation] public class ImageMappingDto : ImageDto @@ -15,4 +15,4 @@ public class ImageMappingDto : ImageDto [JsonProperty("position")] public int Position { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Languages/LanguageDto.cs b/Nop.Plugin.Api/DTOs/Languages/LanguageDto.cs index bab7703..a493e98 100644 --- a/Nop.Plugin.Api/DTOs/Languages/LanguageDto.cs +++ b/Nop.Plugin.Api/DTOs/Languages/LanguageDto.cs @@ -1,82 +1,71 @@ using System.Collections.Generic; using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; +using Nop.Plugin.Api.DTO.Base; -namespace Nop.Plugin.Api.DTOs.Languages +namespace Nop.Plugin.Api.DTO.Languages { [JsonObject(Title = "language")] public class LanguageDto : BaseDto { - private List _storeIds; - /// - /// Gets or sets the name + /// Gets or sets the name /// [JsonProperty("name")] public string Name { get; set; } /// - /// Gets or sets the language culture + /// Gets or sets the language culture /// [JsonProperty("language_culture")] public string LanguageCulture { get; set; } /// - /// Gets or sets the unique SEO code + /// Gets or sets the unique SEO code /// [JsonProperty("unique_seo_code")] public string UniqueSeoCode { get; set; } /// - /// Gets or sets the flag image file name + /// Gets or sets the flag image file name /// [JsonProperty("flag_image_file_name")] public string FlagImageFileName { get; set; } /// - /// Gets or sets a value indicating whether the language supports "Right-to-left" + /// Gets or sets a value indicating whether the language supports "Right-to-left" /// [JsonProperty("rtl")] public bool? Rtl { get; set; } /// - /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores + /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores /// [JsonProperty("limited_to_stores")] public bool? LimitedToStores { get; set; } /// - /// Gets or sets the identifier of the default currency for this language; 0 is set when we use the default currency display order + /// Gets or sets the identifier of the default currency for this language; 0 is set when we use the default currency + /// display order /// [JsonProperty("default_currency_id")] public int? DefaultCurrencyId { get; set; } /// - /// Gets or sets a value indicating whether the language is published + /// Gets or sets a value indicating whether the language is published /// [JsonProperty("published")] public bool? Published { get; set; } /// - /// Gets or sets the display order + /// Gets or sets the display order /// [JsonProperty("display_order")] public int? DisplayOrder { get; set; } /// - /// Gets or sets the store ids in which the language is enabled + /// Gets or sets the store ids in which the language is enabled /// [JsonProperty("store_ids")] - public List StoreIds - { - get - { - return _storeIds; - } - set - { - _storeIds = value; - } - } + public List StoreIds { get; set; } } } diff --git a/Nop.Plugin.Api/DTOs/Languages/LanguagesRootObject.cs b/Nop.Plugin.Api/DTOs/Languages/LanguagesRootObject.cs index 3d3f6be..e994b65 100644 --- a/Nop.Plugin.Api/DTOs/Languages/LanguagesRootObject.cs +++ b/Nop.Plugin.Api/DTOs/Languages/LanguagesRootObject.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Languages +namespace Nop.Plugin.Api.DTO.Languages { public class LanguagesRootObject : ISerializableObject { diff --git a/Nop.Plugin.Api/DTOs/Languages/LocalizedNameDto.cs b/Nop.Plugin.Api/DTOs/Languages/LocalizedNameDto.cs index f88b4a6..df181d7 100644 --- a/Nop.Plugin.Api/DTOs/Languages/LocalizedNameDto.cs +++ b/Nop.Plugin.Api/DTOs/Languages/LocalizedNameDto.cs @@ -1,17 +1,17 @@ using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Languages +namespace Nop.Plugin.Api.DTO.Languages { public class LocalizedNameDto { /// - /// Gets or sets the language identifier + /// Gets or sets the language identifier /// [JsonProperty("language_id")] public int? LanguageId { get; set; } /// - /// Gets or sets the localized name + /// Gets or sets the localized name /// [JsonProperty("localized_name")] public string LocalizedName { get; set; } diff --git a/Nop.Plugin.Api/DTOs/Manufacturers/DiscountManufacturerMappingDto.cs b/Nop.Plugin.Api/DTOs/Manufacturers/DiscountManufacturerMappingDto.cs index 7051ce9..ce8d54e 100644 --- a/Nop.Plugin.Api/DTOs/Manufacturers/DiscountManufacturerMappingDto.cs +++ b/Nop.Plugin.Api/DTOs/Manufacturers/DiscountManufacturerMappingDto.cs @@ -1,16 +1,14 @@ using Newtonsoft.Json; -using Nop.Core.Domain.Catalog; -using Nop.Core.Domain.Discounts; -using Nop.Plugin.Api.DTOs.Base; +using Nop.Plugin.Api.DTO.Base; -namespace Nop.Plugin.Api.DTOs.Manufacturers +namespace Nop.Plugin.Api.DTO.Manufacturers { [JsonObject(Title = "discount")] //[Validator(typeof(ProductDtoValidator))] public class DiscountManufacturerMappingDto : BaseDto { /// - /// Gets or sets the discount identifier + /// Gets or sets the discount identifier /// [JsonProperty("discount_id")] public int DiscountId { get; set; } diff --git a/Nop.Plugin.Api/DTOs/Manufacturers/ManufacturerDto.cs b/Nop.Plugin.Api/DTOs/Manufacturers/ManufacturerDto.cs index 984b796..e67a7e6 100644 --- a/Nop.Plugin.Api/DTOs/Manufacturers/ManufacturerDto.cs +++ b/Nop.Plugin.Api/DTOs/Manufacturers/ManufacturerDto.cs @@ -1,200 +1,144 @@ -using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; -using Nop.Plugin.Api.DTOs.Images; -using Nop.Plugin.Api.DTOs.Languages; -using Nop.Plugin.Api.Validators; -using System; +using System; using System.Collections.Generic; +using Newtonsoft.Json; +using Nop.Plugin.Api.DTO.Base; +using Nop.Plugin.Api.DTO.Images; +using Nop.Plugin.Api.DTO.Languages; -namespace Nop.Plugin.Api.DTOs.Manufacturers +namespace Nop.Plugin.Api.DTO.Manufacturers { [JsonObject(Title = "manufacturer")] + //[Validator(typeof(ManufacturerDtoValidator))] public class ManufacturerDto : BaseDto { - private ImageDto _imageDto; - private List _localizedNames; - private List _storeIds; - private List _discountIds; - private List _roleIds; - /// - /// Gets or sets the name + /// Gets or sets the name /// [JsonProperty("name")] public string Name { get; set; } /// - /// Gets or sets the localized names + /// Gets or sets the localized names /// [JsonProperty("localized_names")] - public List LocalizedNames - { - get - { - return _localizedNames; - } - set - { - _localizedNames = value; - } - } + public List LocalizedNames { get; set; } /// - /// Gets or sets the description + /// Gets or sets the description /// [JsonProperty("description")] public string Description { get; set; } /// - /// Gets or sets a value of used manufacturer template identifier + /// Gets or sets a value of used manufacturer template identifier /// [JsonProperty("manufacturer_template_id")] public int ManufacturerTemplateId { get; set; } /// - /// Gets or sets the meta keywords + /// Gets or sets the meta keywords /// [JsonProperty("meta_keywords")] public string MetaKeywords { get; set; } /// - /// Gets or sets the meta description + /// Gets or sets the meta description /// [JsonProperty("meta_description")] public string MetaDescription { get; set; } /// - /// Gets or sets the meta title + /// Gets or sets the meta title /// [JsonProperty("meta_title")] public string MetaTitle { get; set; } /// - /// Gets or sets the parent picture identifier + /// Gets or sets the parent picture identifier /// [JsonProperty("picture_id")] public int PictureId { get; set; } /// - /// Gets or sets the page size + /// Gets or sets the page size /// [JsonProperty("page_size")] public int PageSize { get; set; } /// - /// Gets or sets a value indicating whether customers can select the page size + /// Gets or sets a value indicating whether customers can select the page size /// [JsonProperty("allow_customers_to_select_page_size")] public bool AllowCustomersToSelectPageSize { get; set; } /// - /// Gets or sets the available customer selectable page size options + /// Gets or sets the available customer selectable page size options /// [JsonProperty("page_size_options")] public string PageSizeOptions { get; set; } /// - /// Gets or sets the available price ranges + /// Gets or sets the available price ranges /// [JsonProperty("price_ranges")] public string PriceRanges { get; set; } /// - /// Gets or sets a value indicating whether the entity is subject to ACL + /// Gets or sets a value indicating whether the entity is subject to ACL /// [JsonProperty("subject_to_acl")] public bool SubjectToAcl { get; set; } /// - /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores + /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores /// [JsonProperty("limited_to_stores")] public bool LimitedToStores { get; set; } /// - /// Gets or sets a value indicating whether the entity is published + /// Gets or sets a value indicating whether the entity is published /// [JsonProperty("published")] public bool Published { get; set; } /// - /// Gets or sets a value indicating whether the entity has been deleted + /// Gets or sets a value indicating whether the entity has been deleted /// [JsonProperty("deleted")] public bool Deleted { get; set; } /// - /// Gets or sets the display order + /// Gets or sets the display order /// [JsonProperty("display_order")] public int DisplayOrder { get; set; } /// - /// Gets or sets the date and time of instance creation + /// Gets or sets the date and time of instance creation /// [JsonProperty("created_on_utc")] public DateTime CreatedOnUtc { get; set; } /// - /// Gets or sets the date and time of instance update + /// Gets or sets the date and time of instance update /// [JsonProperty("updated_on_utc")] public DateTime UpdatedOnUtc { get; set; } [JsonProperty("role_ids")] - public List RoleIds - { - get - { - return _roleIds; - } - set - { - _roleIds = value; - } - } + public List RoleIds { get; set; } [JsonProperty("discount_ids")] - public List DiscountIds - { - get - { - return _discountIds; - } - set - { - _discountIds = value; - } - } + public List DiscountIds { get; set; } [JsonProperty("store_ids")] - public List StoreIds - { - get - { - return _storeIds; - } - set - { - _storeIds = value; - } - } + public List StoreIds { get; set; } [JsonProperty("image")] - public ImageDto Image - { - get - { - return _imageDto; - } - set - { - _imageDto = value; - } - } + public ImageDto Image { get; set; } [JsonProperty("se_name")] public string SeName { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Manufacturers/ManufacturersCountRootObject.cs b/Nop.Plugin.Api/DTOs/Manufacturers/ManufacturersCountRootObject.cs index 311fc40..f02b37e 100644 --- a/Nop.Plugin.Api/DTOs/Manufacturers/ManufacturersCountRootObject.cs +++ b/Nop.Plugin.Api/DTOs/Manufacturers/ManufacturersCountRootObject.cs @@ -1,10 +1,10 @@ using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Manufacturers +namespace Nop.Plugin.Api.DTO.Manufacturers { public class ManufacturersCountRootObject { [JsonProperty("count")] public int Count { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Manufacturers/ManufacturersRootObject.cs b/Nop.Plugin.Api/DTOs/Manufacturers/ManufacturersRootObject.cs index b264a77..5f3bb5d 100644 --- a/Nop.Plugin.Api/DTOs/Manufacturers/ManufacturersRootObject.cs +++ b/Nop.Plugin.Api/DTOs/Manufacturers/ManufacturersRootObject.cs @@ -1,8 +1,8 @@ -using Newtonsoft.Json; -using System; +using System; using System.Collections.Generic; +using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Manufacturers +namespace Nop.Plugin.Api.DTO.Manufacturers { public class ManufacturersRootObject : ISerializableObject { @@ -24,4 +24,4 @@ public Type GetPrimaryPropertyType() return typeof(ManufacturerDto); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/NewsLetterSubscriptions/NewsLetterSubscriptionDto.cs b/Nop.Plugin.Api/DTOs/NewsLetterSubscriptions/NewsLetterSubscriptionDto.cs index 3edfcdc..e07982c 100644 --- a/Nop.Plugin.Api/DTOs/NewsLetterSubscriptions/NewsLetterSubscriptionDto.cs +++ b/Nop.Plugin.Api/DTOs/NewsLetterSubscriptions/NewsLetterSubscriptionDto.cs @@ -1,34 +1,34 @@ using System; using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; +using Nop.Plugin.Api.DTO.Base; -namespace Nop.Plugin.Api.DTOs.Categories +namespace Nop.Plugin.Api.DTO.NewsLetterSubscriptions { [JsonObject(Title = "news_letter_subscription")] public class NewsLetterSubscriptionDto : BaseDto { /// - /// Gets or sets the email + /// Gets or sets the email /// [JsonProperty("email")] public string Email { get; set; } /// - /// Gets or sets whether the subscription is active + /// Gets or sets whether the subscription is active /// [JsonProperty("active")] public bool Active { get; set; } /// - /// Gets or sets whether the subscription is active + /// Gets or sets whether the subscription is active /// [JsonProperty("store_id")] public int StoreId { get; set; } /// - /// Gets or sets created on utc date + /// Gets or sets created on utc date /// [JsonProperty("created_on_utc")] public DateTime? CreatedOnUtc { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/NewsLetterSubscriptions/NewsLetterSubscriptionsRootObject.cs b/Nop.Plugin.Api/DTOs/NewsLetterSubscriptions/NewsLetterSubscriptionsRootObject.cs index 7a9b985..008df46 100644 --- a/Nop.Plugin.Api/DTOs/NewsLetterSubscriptions/NewsLetterSubscriptionsRootObject.cs +++ b/Nop.Plugin.Api/DTOs/NewsLetterSubscriptions/NewsLetterSubscriptionsRootObject.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Categories +namespace Nop.Plugin.Api.DTO.NewsLetterSubscriptions { public class NewsLetterSubscriptionsRootObject : ISerializableObject { @@ -21,7 +21,7 @@ public string GetPrimaryPropertyName() public Type GetPrimaryPropertyType() { - return typeof (NewsLetterSubscriptionDto); + return typeof(NewsLetterSubscriptionDto); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/OrderItems/OrderItemDto.cs b/Nop.Plugin.Api/DTOs/OrderItems/OrderItemDto.cs index 677b9ee..5a5e2bb 100644 --- a/Nop.Plugin.Api/DTOs/OrderItems/OrderItemDto.cs +++ b/Nop.Plugin.Api/DTOs/OrderItems/OrderItemDto.cs @@ -2,126 +2,114 @@ using System.Collections.Generic; using Newtonsoft.Json; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.DTOs.Base; -using Nop.Plugin.Api.DTOs.Products; -using Nop.Plugin.Api.Validators; +using Nop.Plugin.Api.DTO.Base; +using Nop.Plugin.Api.DTO.Products; -namespace Nop.Plugin.Api.DTOs.OrderItems +namespace Nop.Plugin.Api.DTO.OrderItems { + //[Validator(typeof(OrderItemDtoValidator))] [JsonObject(Title = "order_item")] public class OrderItemDto : BaseDto { - private ICollection _attributes; - /// - /// Gets or sets the selected attributes + /// Gets or sets the selected attributes /// [JsonProperty("product_attributes")] - public ICollection Attributes - { - get - { - return _attributes; - } - set - { - _attributes = value; - } - } + public ICollection Attributes { get; set; } /// - /// Gets or sets the quantity + /// Gets or sets the quantity /// [JsonProperty("quantity")] public int? Quantity { get; set; } /// - /// Gets or sets the unit price in primary store currency (incl tax) + /// Gets or sets the unit price in primary store currency (incl tax) /// [JsonProperty("unit_price_incl_tax")] public decimal? UnitPriceInclTax { get; set; } /// - /// Gets or sets the unit price in primary store currency (excl tax) + /// Gets or sets the unit price in primary store currency (excl tax) /// [JsonProperty("unit_price_excl_tax")] public decimal? UnitPriceExclTax { get; set; } /// - /// Gets or sets the price in primary store currency (incl tax) + /// Gets or sets the price in primary store currency (incl tax) /// [JsonProperty("price_incl_tax")] public decimal? PriceInclTax { get; set; } /// - /// Gets or sets the price in primary store currency (excl tax) + /// Gets or sets the price in primary store currency (excl tax) /// [JsonProperty("price_excl_tax")] public decimal? PriceExclTax { get; set; } /// - /// Gets or sets the discount amount (incl tax) + /// Gets or sets the discount amount (incl tax) /// [JsonProperty("discount_amount_incl_tax")] public decimal? DiscountAmountInclTax { get; set; } /// - /// Gets or sets the discount amount (excl tax) + /// Gets or sets the discount amount (excl tax) /// [JsonProperty("discount_amount_excl_tax")] public decimal? DiscountAmountExclTax { get; set; } /// - /// Gets or sets the original cost of this order item (when an order was placed), qty 1 + /// Gets or sets the original cost of this order item (when an order was placed), qty 1 /// [JsonProperty("original_product_cost")] public decimal? OriginalProductCost { get; set; } /// - /// Gets or sets the attribute description + /// Gets or sets the attribute description /// [JsonProperty("attribute_description")] public string AttributeDescription { get; set; } /// - /// Gets or sets the download count + /// Gets or sets the download count /// [JsonProperty("download_count")] public int? DownloadCount { get; set; } /// - /// Gets or sets a value indicating whether download is activated + /// Gets or sets a value indicating whether download is activated /// [JsonProperty("isDownload_activated")] public bool? IsDownloadActivated { get; set; } /// - /// Gets or sets a license download identifier (in case this is a downloadable product) + /// Gets or sets a license download identifier (in case this is a downloadable product) /// [JsonProperty("license_download_id")] public int? LicenseDownloadId { get; set; } /// - /// Gets or sets the total weight of one item - /// It's nullable for compatibility with the previous version of nopCommerce where was no such property + /// Gets or sets the total weight of one item + /// It's nullable for compatibility with the previous version of nopCommerce where was no such property /// [JsonProperty("item_weight")] public decimal? ItemWeight { get; set; } /// - /// Gets or sets the rental product start date (null if it's not a rental product) + /// Gets or sets the rental product start date (null if it's not a rental product) /// [JsonProperty("rental_start_date_utc")] public DateTime? RentalStartDateUtc { get; set; } /// - /// Gets or sets the rental product end date (null if it's not a rental product) + /// Gets or sets the rental product end date (null if it's not a rental product) /// [JsonProperty("rental_end_date_utc")] public DateTime? RentalEndDateUtc { get; set; } /// - /// Gets the product + /// Gets the product /// [JsonProperty("product")] [DoNotMap] @@ -130,4 +118,4 @@ public ICollection Attributes [JsonProperty("product_id")] public int? ProductId { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/OrderItems/OrderItemsCountRootObject.cs b/Nop.Plugin.Api/DTOs/OrderItems/OrderItemsCountRootObject.cs index c86212a..a32c1f2 100644 --- a/Nop.Plugin.Api/DTOs/OrderItems/OrderItemsCountRootObject.cs +++ b/Nop.Plugin.Api/DTOs/OrderItems/OrderItemsCountRootObject.cs @@ -1,10 +1,10 @@ using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.OrderItems +namespace Nop.Plugin.Api.DTO.OrderItems { public class OrderItemsCountRootObject { [JsonProperty("count")] public int Count { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/OrderItems/OrderItemsRootObject.cs b/Nop.Plugin.Api/DTOs/OrderItems/OrderItemsRootObject.cs index c6eba59..c6a1415 100644 --- a/Nop.Plugin.Api/DTOs/OrderItems/OrderItemsRootObject.cs +++ b/Nop.Plugin.Api/DTOs/OrderItems/OrderItemsRootObject.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.OrderItems +namespace Nop.Plugin.Api.DTO.OrderItems { public class OrderItemsRootObject : ISerializableObject { @@ -24,4 +24,4 @@ public Type GetPrimaryPropertyType() return typeof(OrderItemDto); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Orders/OrderDto.cs b/Nop.Plugin.Api/DTOs/Orders/OrderDto.cs index 3a482ac..c3a4b35 100644 --- a/Nop.Plugin.Api/DTOs/Orders/OrderDto.cs +++ b/Nop.Plugin.Api/DTOs/Orders/OrderDto.cs @@ -1,14 +1,14 @@ using System; using System.Collections.Generic; using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; -using Nop.Plugin.Api.DTOs.Customers; -using Nop.Plugin.Api.DTOs.OrderItems; -using Nop.Plugin.Api.Validators; +using Nop.Plugin.Api.DTO.Base; +using Nop.Plugin.Api.DTO.Customers; +using Nop.Plugin.Api.DTO.OrderItems; -namespace Nop.Plugin.Api.DTOs.Orders +namespace Nop.Plugin.Api.DTO.Orders { [JsonObject(Title = "order")] + //[Validator(typeof(OrderDtoValidator))] public class OrderDto : BaseDto { private ICollection _orderItems; @@ -17,223 +17,223 @@ public class OrderDto : BaseDto public int? StoreId { get; set; } /// - /// Gets or sets a value indicating whether a customer chose "pick up in store" shipping option + /// Gets or sets a value indicating whether a customer chose "pick up in store" shipping option /// [JsonProperty("pick_up_in_store")] public bool? PickUpInStore { get; set; } /// - /// Gets or sets the payment method system name + /// Gets or sets the payment method system name /// [JsonProperty("payment_method_system_name")] public string PaymentMethodSystemName { get; set; } /// - /// Gets or sets the customer currency code (at the moment of order placing) + /// Gets or sets the customer currency code (at the moment of order placing) /// [JsonProperty("customer_currency_code")] public string CustomerCurrencyCode { get; set; } /// - /// Gets or sets the currency rate + /// Gets or sets the currency rate /// [JsonProperty("currency_rate")] public decimal? CurrencyRate { get; set; } /// - /// Gets or sets the customer tax display type identifier + /// Gets or sets the customer tax display type identifier /// [JsonProperty("customer_tax_display_type_id")] public int? CustomerTaxDisplayTypeId { get; set; } /// - /// Gets or sets the VAT number (the European Union Value Added Tax) + /// Gets or sets the VAT number (the European Union Value Added Tax) /// [JsonProperty("vat_number")] public string VatNumber { get; set; } /// - /// Gets or sets the order subtotal (incl tax) + /// Gets or sets the order subtotal (incl tax) /// [JsonProperty("order_subtotal_incl_tax")] public decimal? OrderSubtotalInclTax { get; set; } /// - /// Gets or sets the order subtotal (excl tax) + /// Gets or sets the order subtotal (excl tax) /// [JsonProperty("order_subtotal_excl_tax")] public decimal? OrderSubtotalExclTax { get; set; } /// - /// Gets or sets the order subtotal discount (incl tax) + /// Gets or sets the order subtotal discount (incl tax) /// [JsonProperty("order_sub_total_discount_incl_tax")] public decimal? OrderSubTotalDiscountInclTax { get; set; } /// - /// Gets or sets the order subtotal discount (excl tax) + /// Gets or sets the order subtotal discount (excl tax) /// [JsonProperty("order_sub_total_discount_excl_tax")] public decimal? OrderSubTotalDiscountExclTax { get; set; } /// - /// Gets or sets the order shipping (incl tax) + /// Gets or sets the order shipping (incl tax) /// [JsonProperty("order_shipping_incl_tax")] public decimal? OrderShippingInclTax { get; set; } /// - /// Gets or sets the order shipping (excl tax) + /// Gets or sets the order shipping (excl tax) /// [JsonProperty("order_shipping_excl_tax")] public decimal? OrderShippingExclTax { get; set; } /// - /// Gets or sets the payment method additional fee (incl tax) + /// Gets or sets the payment method additional fee (incl tax) /// [JsonProperty("payment_method_additional_fee_incl_tax")] public decimal? PaymentMethodAdditionalFeeInclTax { get; set; } /// - /// Gets or sets the payment method additional fee (excl tax) + /// Gets or sets the payment method additional fee (excl tax) /// [JsonProperty("payment_method_additional_fee_excl_tax")] public decimal? PaymentMethodAdditionalFeeExclTax { get; set; } /// - /// Gets or sets the tax rates + /// Gets or sets the tax rates /// [JsonProperty("tax_rates")] public string TaxRates { get; set; } /// - /// Gets or sets the order tax + /// Gets or sets the order tax /// [JsonProperty("order_tax")] public decimal? OrderTax { get; set; } /// - /// Gets or sets the order discount (applied to order total) + /// Gets or sets the order discount (applied to order total) /// [JsonProperty("order_discount")] public decimal? OrderDiscount { get; set; } /// - /// Gets or sets the order total + /// Gets or sets the order total /// [JsonProperty("order_total")] public decimal? OrderTotal { get; set; } /// - /// Gets or sets the refunded amount + /// Gets or sets the refunded amount /// [JsonProperty("refunded_amount")] public decimal? RefundedAmount { get; set; } /// - /// Gets or sets the value indicating whether reward points were earned for this order + /// Gets or sets the value indicating whether reward points were earned for this order /// [JsonProperty("reward_points_were_added")] public bool? RewardPointsWereAdded { get; set; } /// - /// Gets or sets the checkout attribute description + /// Gets or sets the checkout attribute description /// [JsonProperty("checkout_attribute_description")] public string CheckoutAttributeDescription { get; set; } /// - /// Gets or sets the customer language identifier + /// Gets or sets the customer language identifier /// [JsonProperty("customer_language_id")] public int? CustomerLanguageId { get; set; } /// - /// Gets or sets the affiliate identifier + /// Gets or sets the affiliate identifier /// [JsonProperty("affiliate_id")] public int? AffiliateId { get; set; } /// - /// Gets or sets the customer IP address + /// Gets or sets the customer IP address /// [JsonProperty("customer_ip")] public string CustomerIp { get; set; } /// - /// Gets or sets the authorization transaction identifier + /// Gets or sets the authorization transaction identifier /// [JsonProperty("authorization_transaction_id")] public string AuthorizationTransactionId { get; set; } /// - /// Gets or sets the authorization transaction code + /// Gets or sets the authorization transaction code /// [JsonProperty("authorization_transaction_code")] public string AuthorizationTransactionCode { get; set; } /// - /// Gets or sets the authorization transaction result + /// Gets or sets the authorization transaction result /// [JsonProperty("authorization_transaction_result")] public string AuthorizationTransactionResult { get; set; } /// - /// Gets or sets the capture transaction identifier + /// Gets or sets the capture transaction identifier /// [JsonProperty("capture_transaction_id")] public string CaptureTransactionId { get; set; } /// - /// Gets or sets the capture transaction result + /// Gets or sets the capture transaction result /// [JsonProperty("capture_transaction_result")] public string CaptureTransactionResult { get; set; } /// - /// Gets or sets the subscription transaction identifier + /// Gets or sets the subscription transaction identifier /// [JsonProperty("subscription_transaction_id")] public string SubscriptionTransactionId { get; set; } /// - /// Gets or sets the paid date and time + /// Gets or sets the paid date and time /// [JsonProperty("paid_date_utc")] public DateTime? PaidDateUtc { get; set; } /// - /// Gets or sets the shipping method + /// Gets or sets the shipping method /// [JsonProperty("shipping_method")] public string ShippingMethod { get; set; } /// - /// Gets or sets the shipping rate computation method identifier + /// Gets or sets the shipping rate computation method identifier /// [JsonProperty("shipping_rate_computation_method_system_name")] public string ShippingRateComputationMethodSystemName { get; set; } - + /// - /// Gets or sets the serialized CustomValues (values from ProcessPaymentRequest) + /// Gets or sets the serialized CustomValues (values from ProcessPaymentRequest) /// [JsonProperty("custom_values_xml")] public string CustomValuesXml { get; set; } /// - /// Gets or sets a value indicating whether the entity has been deleted + /// Gets or sets a value indicating whether the entity has been deleted /// [JsonProperty("deleted")] public bool? Deleted { get; set; } /// - /// Gets or sets the date and time of order creation + /// Gets or sets the date and time of order creation /// [JsonProperty("created_on_utc")] public DateTime? CreatedOnUtc { get; set; } /// - /// Gets or sets the customer + /// Gets or sets the customer /// [JsonProperty("customer")] public OrderCustomerDto Customer { get; set; } @@ -242,19 +242,19 @@ public class OrderDto : BaseDto public int? CustomerId { get; set; } /// - /// Gets or sets the billing address + /// Gets or sets the billing address /// [JsonProperty("billing_address")] public AddressDto BillingAddress { get; set; } /// - /// Gets or sets the shipping address + /// Gets or sets the shipping address /// [JsonProperty("shipping_address")] public AddressDto ShippingAddress { get; set; } /// - /// Gets or sets order items + /// Gets or sets order items /// [JsonProperty("order_items")] public ICollection OrderItems @@ -268,30 +268,31 @@ public ICollection OrderItems return _orderItems; } - set { _orderItems = value; } + set => _orderItems = value; } /// - /// Gets or sets the order status + /// Gets or sets the order status /// [JsonProperty("order_status")] public string OrderStatus { get; set; } /// - /// Gets or sets the payment status + /// Gets or sets the payment status /// [JsonProperty("payment_status")] public string PaymentStatus { get; set; } /// - /// Gets or sets the shipping status + /// Gets or sets the shipping status /// [JsonProperty("shipping_status")] public string ShippingStatus { get; set; } + /// - /// Gets or sets the customer tax display type + /// Gets or sets the customer tax display type /// [JsonProperty("customer_tax_display_type")] public string CustomerTaxDisplayType { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Orders/OrdersCountRootObject.cs b/Nop.Plugin.Api/DTOs/Orders/OrdersCountRootObject.cs index 0d0544a..9fe78f9 100644 --- a/Nop.Plugin.Api/DTOs/Orders/OrdersCountRootObject.cs +++ b/Nop.Plugin.Api/DTOs/Orders/OrdersCountRootObject.cs @@ -1,10 +1,10 @@ using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Orders +namespace Nop.Plugin.Api.DTO.Orders { public class OrdersCountRootObject { [JsonProperty("count")] public int Count { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Orders/OrdersRootObject.cs b/Nop.Plugin.Api/DTOs/Orders/OrdersRootObject.cs index a08f28e..8f35c6a 100644 --- a/Nop.Plugin.Api/DTOs/Orders/OrdersRootObject.cs +++ b/Nop.Plugin.Api/DTOs/Orders/OrdersRootObject.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Orders +namespace Nop.Plugin.Api.DTO.Orders { public class OrdersRootObject : ISerializableObject { @@ -21,7 +21,7 @@ public string GetPrimaryPropertyName() public Type GetPrimaryPropertyType() { - return typeof (OrderDto); + return typeof(OrderDto); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Orders/SingleOrderRootObject.cs b/Nop.Plugin.Api/DTOs/Orders/SingleOrderRootObject.cs index 5bb4c2f..d3c11cf 100644 --- a/Nop.Plugin.Api/DTOs/Orders/SingleOrderRootObject.cs +++ b/Nop.Plugin.Api/DTOs/Orders/SingleOrderRootObject.cs @@ -1,10 +1,10 @@ using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Orders +namespace Nop.Plugin.Api.DTO.Orders { public class SingleOrderRootObject { [JsonProperty("order")] public OrderDto Order { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/ProductAttributes/ProductAttributeDto.cs b/Nop.Plugin.Api/DTOs/ProductAttributes/ProductAttributeDto.cs index b2118c9..d5edb9d 100644 --- a/Nop.Plugin.Api/DTOs/ProductAttributes/ProductAttributeDto.cs +++ b/Nop.Plugin.Api/DTOs/ProductAttributes/ProductAttributeDto.cs @@ -1,13 +1,14 @@ using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; +using Nop.Plugin.Api.DTO.Base; -namespace Nop.Plugin.Api.DTOs.ProductAttributes +namespace Nop.Plugin.Api.DTO.ProductAttributes { [JsonObject(Title = "product_attribute")] + //[Validator(typeof(ProductAttributeDtoValidator))] public class ProductAttributeDto : BaseDto { /// - /// Gets or sets the name + /// Gets or sets the name /// [JsonProperty("name")] public string Name { get; set; } @@ -29,9 +30,9 @@ public class ProductAttributeDto : BaseDto //} /// - /// Gets or sets the description + /// Gets or sets the description /// [JsonProperty("description")] public string Description { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/ProductAttributes/ProductAttributesCountRootObject.cs b/Nop.Plugin.Api/DTOs/ProductAttributes/ProductAttributesCountRootObject.cs index 64779ac..7959685 100644 --- a/Nop.Plugin.Api/DTOs/ProductAttributes/ProductAttributesCountRootObject.cs +++ b/Nop.Plugin.Api/DTOs/ProductAttributes/ProductAttributesCountRootObject.cs @@ -1,10 +1,10 @@ using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.ProductAttributes +namespace Nop.Plugin.Api.DTO.ProductAttributes { public class ProductAttributesCountRootObject { [JsonProperty("count")] public int Count { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/ProductAttributes/ProductAttributesRootObjectDto.cs b/Nop.Plugin.Api/DTOs/ProductAttributes/ProductAttributesRootObjectDto.cs index ff6a93f..4f1a482 100644 --- a/Nop.Plugin.Api/DTOs/ProductAttributes/ProductAttributesRootObjectDto.cs +++ b/Nop.Plugin.Api/DTOs/ProductAttributes/ProductAttributesRootObjectDto.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.ProductAttributes +namespace Nop.Plugin.Api.DTO.ProductAttributes { public class ProductAttributesRootObjectDto : ISerializableObject { @@ -21,7 +21,7 @@ public string GetPrimaryPropertyName() public Type GetPrimaryPropertyType() { - return typeof (ProductAttributeDto); + return typeof(ProductAttributeDto); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/ProductCategoryMappings/ProductCategoryMappingsCountRootObject.cs b/Nop.Plugin.Api/DTOs/ProductCategoryMappings/ProductCategoryMappingsCountRootObject.cs index 11ab458..01f31a9 100644 --- a/Nop.Plugin.Api/DTOs/ProductCategoryMappings/ProductCategoryMappingsCountRootObject.cs +++ b/Nop.Plugin.Api/DTOs/ProductCategoryMappings/ProductCategoryMappingsCountRootObject.cs @@ -1,10 +1,10 @@ using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.ProductCategoryMappings +namespace Nop.Plugin.Api.DTO.ProductCategoryMappings { public class ProductCategoryMappingsCountRootObject { [JsonProperty("count")] public int Count { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/ProductCategoryMappings/ProductCategoryMappingsDto.cs b/Nop.Plugin.Api/DTOs/ProductCategoryMappings/ProductCategoryMappingsDto.cs index 948f7f6..a325551 100644 --- a/Nop.Plugin.Api/DTOs/ProductCategoryMappings/ProductCategoryMappingsDto.cs +++ b/Nop.Plugin.Api/DTOs/ProductCategoryMappings/ProductCategoryMappingsDto.cs @@ -1,33 +1,34 @@ using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; +using Nop.Plugin.Api.DTO.Base; -namespace Nop.Plugin.Api.DTOs.ProductCategoryMappings +namespace Nop.Plugin.Api.DTO.ProductCategoryMappings { [JsonObject(Title = "product_category_mapping")] + //[Validator(typeof(ProductCategoryMappingDtoValidator))] public class ProductCategoryMappingDto : BaseDto { /// - /// Gets or sets the product identifier + /// Gets or sets the product identifier /// [JsonProperty("product_id")] public int? ProductId { get; set; } /// - /// Gets or sets the category identifier + /// Gets or sets the category identifier /// [JsonProperty("category_id")] public int? CategoryId { get; set; } /// - /// Gets or sets a value indicating whether the product is featured + /// Gets or sets a value indicating whether the product is featured /// [JsonProperty("is_featured_product")] public bool? IsFeaturedProduct { get; set; } /// - /// Gets or sets the display order + /// Gets or sets the display order /// [JsonProperty("display_order")] public int? DisplayOrder { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/ProductCategoryMappings/ProductCategoryMappingsRootObject.cs b/Nop.Plugin.Api/DTOs/ProductCategoryMappings/ProductCategoryMappingsRootObject.cs index 993e4d6..032476d 100644 --- a/Nop.Plugin.Api/DTOs/ProductCategoryMappings/ProductCategoryMappingsRootObject.cs +++ b/Nop.Plugin.Api/DTOs/ProductCategoryMappings/ProductCategoryMappingsRootObject.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.ProductCategoryMappings +namespace Nop.Plugin.Api.DTO.ProductCategoryMappings { public class ProductCategoryMappingsRootObject : ISerializableObject { @@ -21,7 +21,7 @@ public string GetPrimaryPropertyName() public Type GetPrimaryPropertyType() { - return typeof (ProductCategoryMappingDto); + return typeof(ProductCategoryMappingDto); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/ProductItemAttributeDto.cs b/Nop.Plugin.Api/DTOs/ProductItemAttributeDto.cs index e6d5f36..c0770f4 100644 --- a/Nop.Plugin.Api/DTOs/ProductItemAttributeDto.cs +++ b/Nop.Plugin.Api/DTOs/ProductItemAttributeDto.cs @@ -1,7 +1,7 @@ using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; +using Nop.Plugin.Api.DTO.Base; -namespace Nop.Plugin.Api.DTOs +namespace Nop.Plugin.Api.DTO { [JsonObject(Title = "attribute")] public class ProductItemAttributeDto : BaseDto diff --git a/Nop.Plugin.Api/DTOs/ProductManufacturerMappings/ProductManufacturerMappingsCountRootObject.cs b/Nop.Plugin.Api/DTOs/ProductManufacturerMappings/ProductManufacturerMappingsCountRootObject.cs index 19bcf87..63460fa 100644 --- a/Nop.Plugin.Api/DTOs/ProductManufacturerMappings/ProductManufacturerMappingsCountRootObject.cs +++ b/Nop.Plugin.Api/DTOs/ProductManufacturerMappings/ProductManufacturerMappingsCountRootObject.cs @@ -1,10 +1,10 @@ using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.ProductManufacturerMappings +namespace Nop.Plugin.Api.DTO.ProductManufacturerMappings { public class ProductManufacturerMappingsCountRootObject { [JsonProperty("count")] public int Count { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/ProductManufacturerMappings/ProductManufacturerMappingsDto.cs b/Nop.Plugin.Api/DTOs/ProductManufacturerMappings/ProductManufacturerMappingsDto.cs index 806c0e7..c2f4413 100644 --- a/Nop.Plugin.Api/DTOs/ProductManufacturerMappings/ProductManufacturerMappingsDto.cs +++ b/Nop.Plugin.Api/DTOs/ProductManufacturerMappings/ProductManufacturerMappingsDto.cs @@ -1,34 +1,34 @@ using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; -using Nop.Plugin.Api.Validators; +using Nop.Plugin.Api.DTO.Base; -namespace Nop.Plugin.Api.DTOs.ProductManufacturerMappings +namespace Nop.Plugin.Api.DTO.ProductManufacturerMappings { [JsonObject(Title = "product_manufacturer_mapping")] + //[Validator(typeof(ProductManufacturerMappingDtoValidator))] public class ProductManufacturerMappingsDto : BaseDto { /// - /// Gets or sets the product identifier + /// Gets or sets the product identifier /// [JsonProperty("product_id")] public int? ProductId { get; set; } /// - /// Gets or sets the manufacturer identifier + /// Gets or sets the manufacturer identifier /// [JsonProperty("manufacturer_id")] public int? ManufacturerId { get; set; } /// - /// Gets or sets a value indicating whether the product is featured + /// Gets or sets a value indicating whether the product is featured /// [JsonProperty("is_featured_product")] public bool? IsFeaturedProduct { get; set; } /// - /// Gets or sets the display order + /// Gets or sets the display order /// [JsonProperty("display_order")] public int? DisplayOrder { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/ProductManufacturerMappings/ProductManufacturerMappingsRootObject.cs b/Nop.Plugin.Api/DTOs/ProductManufacturerMappings/ProductManufacturerMappingsRootObject.cs index 6b5ac59..82665cc 100644 --- a/Nop.Plugin.Api/DTOs/ProductManufacturerMappings/ProductManufacturerMappingsRootObject.cs +++ b/Nop.Plugin.Api/DTOs/ProductManufacturerMappings/ProductManufacturerMappingsRootObject.cs @@ -1,8 +1,8 @@ -using Newtonsoft.Json; -using System; +using System; using System.Collections.Generic; +using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.ProductManufacturerMappings +namespace Nop.Plugin.Api.DTO.ProductManufacturerMappings { public class ProductManufacturerMappingsRootObject : ISerializableObject { @@ -21,7 +21,7 @@ public string GetPrimaryPropertyName() public Type GetPrimaryPropertyType() { - return typeof (ProductManufacturerMappingsDto); + return typeof(ProductManufacturerMappingsDto); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Products/ProductAttributeCombinationDto.cs b/Nop.Plugin.Api/DTOs/Products/ProductAttributeCombinationDto.cs index 1f65878..14d546c 100644 --- a/Nop.Plugin.Api/DTOs/Products/ProductAttributeCombinationDto.cs +++ b/Nop.Plugin.Api/DTOs/Products/ProductAttributeCombinationDto.cs @@ -1,58 +1,60 @@ using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; -using Nop.Plugin.Api.Validators; +using Nop.Plugin.Api.DTO.Base; -namespace Nop.Plugin.Api.DTOs.Products +namespace Nop.Plugin.Api.DTO.Products { [JsonObject(Title = "product_attribute_combination")] + //[Validator(typeof(ProductAttributeCombinationDtoValidator))] public class ProductAttributeCombinationDto : BaseDto { /// - /// Gets or sets the product identifier + /// Gets or sets the product identifier /// [JsonProperty("product_id")] public int ProductId { get; set; } /// - /// Gets or sets the attributes + /// Gets or sets the attributes /// [JsonProperty("attributes_xml")] public string AttributesXml { get; set; } /// - /// Gets or sets the stock quantity + /// Gets or sets the stock quantity /// [JsonProperty("stock_quantity")] public int StockQuantity { get; set; } /// - /// Gets or sets the SKU + /// Gets or sets the SKU /// [JsonProperty("sku")] public string Sku { get; set; } /// - /// Gets or sets the manufacturer part number + /// Gets or sets the manufacturer part number /// [JsonProperty("manufacturer_part_number")] public string ManufacturerPartNumber { get; set; } /// - /// Gets or sets the Global Trade Item Number (GTIN). These identifiers include UPC (in North America), EAN (in Europe), JAN (in Japan), and ISBN (for books). + /// Gets or sets the Global Trade Item Number (GTIN). These identifiers include UPC (in North America), EAN (in + /// Europe), JAN (in Japan), and ISBN (for books). /// [JsonProperty("gtin")] public string Gtin { get; set; } /// - /// Gets or sets the attribute combination price. This way a store owner can override the default product price when this attribute combination is added to the cart. For example, you can give a discount this way. + /// Gets or sets the attribute combination price. This way a store owner can override the default product price when + /// this attribute combination is added to the cart. For example, you can give a discount this way. /// [JsonProperty("overridden_price")] public decimal? OverriddenPrice { get; set; } /// - /// Gets or sets the identifier of picture associated with this combination + /// Gets or sets the identifier of picture associated with this combination /// [JsonProperty("picture_id")] public int PictureId { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Products/ProductAttributeMappingDto.cs b/Nop.Plugin.Api/DTOs/Products/ProductAttributeMappingDto.cs index 48f9db3..626e082 100644 --- a/Nop.Plugin.Api/DTOs/Products/ProductAttributeMappingDto.cs +++ b/Nop.Plugin.Api/DTOs/Products/ProductAttributeMappingDto.cs @@ -2,18 +2,16 @@ using System.Collections.Generic; using Newtonsoft.Json; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.DTOs.Base; +using Nop.Plugin.Api.DTO.Base; -namespace Nop.Plugin.Api.DTOs.Products +namespace Nop.Plugin.Api.DTO.Products { [JsonObject(Title = "attribute")] //[Validator(typeof(ProductDtoValidator))] public class ProductAttributeMappingDto : BaseDto { - private List _productAttributeValues; - /// - /// Gets or sets the product attribute identifier + /// Gets or sets the product attribute identifier /// [JsonProperty("product_attribute_id")] public int ProductAttributeId { get; set; } @@ -22,63 +20,56 @@ public class ProductAttributeMappingDto : BaseDto public string ProductAttributeName { get; set; } /// - /// Gets or sets a value a text prompt + /// Gets or sets a value a text prompt /// [JsonProperty("text_prompt")] public string TextPrompt { get; set; } /// - /// Gets or sets a value indicating whether the entity is required + /// Gets or sets a value indicating whether the entity is required /// [JsonProperty("is_required")] public bool IsRequired { get; set; } /// - /// Gets or sets the attribute control type identifier + /// Gets or sets the attribute control type identifier /// [JsonProperty("attribute_control_type_id")] public int AttributeControlTypeId { get; set; } /// - /// Gets or sets the display order + /// Gets or sets the display order /// [JsonProperty("display_order")] public int DisplayOrder { get; set; } /// - /// Gets or sets the default value (for textbox and multiline textbox) + /// Gets or sets the default value (for textbox and multiline textbox) /// [JsonProperty("default_value")] public string DefaultValue { get; set; } /// - /// Gets the attribute control type + /// Gets the attribute control type /// [JsonProperty("attribute_control_type_name")] public string AttributeControlType { - get - { - return ((AttributeControlType)this.AttributeControlTypeId).ToString(); - } + get => ((AttributeControlType) AttributeControlTypeId).ToString(); set { AttributeControlType attributeControlTypeId; if (Enum.TryParse(value, out attributeControlTypeId)) { - this.AttributeControlTypeId = (int)attributeControlTypeId; + AttributeControlTypeId = (int) attributeControlTypeId; } } } /// - /// Gets the product attribute values + /// Gets the product attribute values /// [JsonProperty("attribute_values")] - public List ProductAttributeValues - { - get { return _productAttributeValues; } - set { _productAttributeValues = value; } - } + public List ProductAttributeValues { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Products/ProductAttributeValueDto.cs b/Nop.Plugin.Api/DTOs/Products/ProductAttributeValueDto.cs index b8b0971..a6faa83 100644 --- a/Nop.Plugin.Api/DTOs/Products/ProductAttributeValueDto.cs +++ b/Nop.Plugin.Api/DTOs/Products/ProductAttributeValueDto.cs @@ -1,83 +1,84 @@ using System; using Newtonsoft.Json; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.DTOs.Base; -using Nop.Plugin.Api.DTOs.Images; +using Nop.Plugin.Api.DTO.Base; +using Nop.Plugin.Api.DTO.Images; -namespace Nop.Plugin.Api.DTOs.Products +namespace Nop.Plugin.Api.DTO.Products { [JsonObject(Title = "attribute_value")] //[Validator(typeof(ProductDtoValidator))] public class ProductAttributeValueDto : BaseDto { /// - /// Gets or sets the attribute value type identifier + /// Gets or sets the attribute value type identifier /// [JsonProperty("type_id")] public int? AttributeValueTypeId { get; set; } /// - /// Gets or sets the associated product identifier (used only with AttributeValueType.AssociatedToProduct) + /// Gets or sets the associated product identifier (used only with AttributeValueType.AssociatedToProduct) /// [JsonProperty("associated_product_id")] public int? AssociatedProductId { get; set; } /// - /// Gets or sets the product attribute name + /// Gets or sets the product attribute name /// [JsonProperty("name")] public string Name { get; set; } /// - /// Gets or sets the color RGB value (used with "Color squares" attribute type) + /// Gets or sets the color RGB value (used with "Color squares" attribute type) /// [JsonProperty("color_squares_rgb")] public string ColorSquaresRgb { get; set; } /// - /// Gets or sets the picture ID for image square (used with "Image squares" attribute type) + /// Gets or sets the picture ID for image square (used with "Image squares" attribute type) /// [JsonProperty("image_squares_image")] public ImageDto ImageSquaresImage { get; set; } /// - /// Gets or sets the price adjustment (used only with AttributeValueType.Simple) + /// Gets or sets the price adjustment (used only with AttributeValueType.Simple) /// [JsonProperty("price_adjustment")] public decimal? PriceAdjustment { get; set; } /// - /// Gets or sets the weight adjustment (used only with AttributeValueType.Simple) + /// Gets or sets the weight adjustment (used only with AttributeValueType.Simple) /// [JsonProperty("weight_adjustment")] public decimal? WeightAdjustment { get; set; } /// - /// Gets or sets the attibute value cost (used only with AttributeValueType.Simple) + /// Gets or sets the attibute value cost (used only with AttributeValueType.Simple) /// [JsonProperty("cost")] public decimal? Cost { get; set; } /// - /// Gets or sets the quantity of associated product (used only with AttributeValueType.AssociatedToProduct) + /// Gets or sets the quantity of associated product (used only with AttributeValueType.AssociatedToProduct) /// [JsonProperty("quantity")] public int? Quantity { get; set; } /// - /// Gets or sets a value indicating whether the value is pre-selected + /// Gets or sets a value indicating whether the value is pre-selected /// [JsonProperty("is_pre_selected")] public bool? IsPreSelected { get; set; } /// - /// Gets or sets the display order + /// Gets or sets the display order /// [JsonProperty("display_order")] public int? DisplayOrder { get; set; } /// - /// Gets or sets the picture (identifier) associated with this value. This picture should replace a product main picture once clicked (selected). + /// Gets or sets the picture (identifier) associated with this value. This picture should replace a product main + /// picture once clicked (selected). /// [JsonIgnore] public int? PictureId { get; set; } @@ -86,23 +87,20 @@ public class ProductAttributeValueDto : BaseDto public int? ProductPictureId { get; set; } /// - /// Gets or sets the attribute value type + /// Gets or sets the attribute value type /// [JsonProperty("type")] public string AttributeValueType { - get - { - return ((AttributeValueType)this.AttributeValueTypeId).ToString(); - } + get => ((AttributeValueType) AttributeValueTypeId).ToString(); set { AttributeValueType attributeValueTypeId; if (Enum.TryParse(value, out attributeValueTypeId)) { - this.AttributeValueTypeId = (int)attributeValueTypeId; + AttributeValueTypeId = (int) attributeValueTypeId; } } } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Products/ProductDto.cs b/Nop.Plugin.Api/DTOs/Products/ProductDto.cs index f1fdc66..5e59ddc 100644 --- a/Nop.Plugin.Api/DTOs/Products/ProductDto.cs +++ b/Nop.Plugin.Api/DTOs/Products/ProductDto.cs @@ -3,496 +3,528 @@ using Newtonsoft.Json; using Nop.Core.Domain.Catalog; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.DTOs.Base; -using Nop.Plugin.Api.DTOs.Images; -using Nop.Plugin.Api.DTOs.Languages; -using Nop.Plugin.Api.DTOs.SpecificationAttributes; -using Nop.Plugin.Api.Validators; +using Nop.Plugin.Api.DTO.Base; +using Nop.Plugin.Api.DTO.Images; +using Nop.Plugin.Api.DTO.Languages; +using Nop.Plugin.Api.DTO.SpecificationAttributes; -namespace Nop.Plugin.Api.DTOs.Products +namespace Nop.Plugin.Api.DTO.Products { [JsonObject(Title = "product")] + //[Validator(typeof(ProductDtoValidator))] public class ProductDto : BaseDto { private int? _productTypeId; - private List _storeIds; - private List _discountIds; - private List _roleIds; - private List _manufacturerIds; - private List _localizedNames; - private List _images; - private List _productAttributeMappings; - private List _productAttributeCombinations; - private List _productSpecificationAttributes; - private List _associatedProductIds; - private List _tags; - - /// - /// Gets or sets the values indicating whether this product is visible in catalog or search results. - /// It's used when this product is associated to some "grouped" one - /// This way associated products could be accessed/added/etc only from a grouped product details page + + /// + /// Gets or sets the values indicating whether this product is visible in catalog or search results. + /// It's used when this product is associated to some "grouped" one + /// This way associated products could be accessed/added/etc only from a grouped product details page /// [JsonProperty("visible_individually")] public bool? VisibleIndividually { get; set; } /// - /// Gets or sets the name + /// Gets or sets the name /// [JsonProperty("name")] public string Name { get; set; } /// - /// Gets or sets the localized names + /// Gets or sets the localized names /// [JsonProperty("localized_names")] - public List LocalizedNames - { - get - { - return _localizedNames; - } - set - { - _localizedNames = value; - } - } + public List LocalizedNames { get; set; } /// - /// Gets or sets the short description + /// Gets or sets the short description /// [JsonProperty("short_description")] public string ShortDescription { get; set; } + /// - /// Gets or sets the full description + /// Gets or sets the full description /// [JsonProperty("full_description")] public string FullDescription { get; set; } /// - /// Gets or sets a value indicating whether to show the product on home page + /// Gets or sets a value indicating whether to show the product on home page /// [JsonProperty("show_on_home_page")] public bool? ShowOnHomePage { get; set; } /// - /// Gets or sets the meta keywords + /// Gets or sets the meta keywords /// [JsonProperty("meta_keywords")] public string MetaKeywords { get; set; } + /// - /// Gets or sets the meta description + /// Gets or sets the meta description /// [JsonProperty("meta_description")] public string MetaDescription { get; set; } + /// - /// Gets or sets the meta title + /// Gets or sets the meta title /// [JsonProperty("meta_title")] public string MetaTitle { get; set; } /// - /// Gets or sets a value indicating whether the product allows customer reviews + /// Gets or sets a value indicating whether the product allows customer reviews /// [JsonProperty("allow_customer_reviews")] public bool? AllowCustomerReviews { get; set; } + /// - /// Gets or sets the rating sum (approved reviews) + /// Gets or sets the rating sum (approved reviews) /// [JsonProperty("approved_rating_sum")] public int? ApprovedRatingSum { get; set; } + /// - /// Gets or sets the rating sum (not approved reviews) + /// Gets or sets the rating sum (not approved reviews) /// [JsonProperty("not_approved_rating_sum")] public int? NotApprovedRatingSum { get; set; } + /// - /// Gets or sets the total rating votes (approved reviews) + /// Gets or sets the total rating votes (approved reviews) /// [JsonProperty("approved_total_reviews")] public int? ApprovedTotalReviews { get; set; } + /// - /// Gets or sets the total rating votes (not approved reviews) + /// Gets or sets the total rating votes (not approved reviews) /// [JsonProperty("not_approved_total_reviews")] public int? NotApprovedTotalReviews { get; set; } /// - /// Gets or sets the SKU + /// Gets or sets the SKU /// [JsonProperty("sku")] public string Sku { get; set; } + /// - /// Gets or sets the manufacturer part number + /// Gets or sets the manufacturer part number /// [JsonProperty("manufacturer_part_number")] public string ManufacturerPartNumber { get; set; } + /// - /// Gets or sets the Global Trade Item Number (GTIN). These identifiers include UPC (in North America), EAN (in Europe), JAN (in Japan), and ISBN (for books). + /// Gets or sets the Global Trade Item Number (GTIN). These identifiers include UPC (in North America), EAN (in + /// Europe), JAN (in Japan), and ISBN (for books). /// [JsonProperty("gtin")] public string Gtin { get; set; } /// - /// Gets or sets a value indicating whether the product is gift card + /// Gets or sets a value indicating whether the product is gift card /// [JsonProperty("is_gift_card")] public bool? IsGiftCard { get; set; } /// - /// Gets or sets a value indicating whether the product requires that other products are added to the cart (Product X requires Product Y) + /// Gets or sets a value indicating whether the product requires that other products are added to the cart (Product X + /// requires Product Y) /// [JsonProperty("require_other_products")] public bool? RequireOtherProducts { get; set; } /// - /// Gets or sets a value indicating whether required products are automatically added to the cart + /// Gets or sets a value indicating whether required products are automatically added to the cart /// [JsonProperty("automatically_add_required_products")] public bool? AutomaticallyAddRequiredProducts { get; set; } /// - /// Gets or sets a value indicating whether the product is download + /// Gets or sets a value indicating whether the product is download /// [JsonProperty("is_download")] public bool? IsDownload { get; set; } /// - /// Gets or sets a value indicating whether this downloadable product can be downloaded unlimited number of times + /// Gets or sets a value indicating whether this downloadable product can be downloaded unlimited number of times /// [JsonProperty("unlimited_downloads")] public bool? UnlimitedDownloads { get; set; } + /// - /// Gets or sets the maximum number of downloads + /// Gets or sets the maximum number of downloads /// [JsonProperty("max_number_of_downloads")] public int? MaxNumberOfDownloads { get; set; } + /// - /// Gets or sets the number of days during customers keeps access to the file. + /// Gets or sets the number of days during customers keeps access to the file. /// [JsonProperty("download_expiration_days")] public int? DownloadExpirationDays { get; set; } /// - /// Gets or sets a value indicating whether the product has a sample download file + /// Gets or sets a value indicating whether the product has a sample download file /// [JsonProperty("has_sample_download")] public bool? HasSampleDownload { get; set; } /// - /// Gets or sets a value indicating whether the product has user agreement + /// Gets or sets a value indicating whether the product has user agreement /// [JsonProperty("has_user_agreement")] public bool? HasUserAgreement { get; set; } /// - /// Gets or sets a value indicating whether the product is recurring + /// Gets or sets a value indicating whether the product is recurring /// [JsonProperty("is_recurring")] public bool? IsRecurring { get; set; } + /// - /// Gets or sets the cycle length + /// Gets or sets the cycle length /// [JsonProperty("recurring_cycle_length")] public int? RecurringCycleLength { get; set; } /// - /// Gets or sets the total cycles + /// Gets or sets the total cycles /// [JsonProperty("recurring_total_cycles")] public int? RecurringTotalCycles { get; set; } /// - /// Gets or sets a value indicating whether the product is rental + /// Gets or sets a value indicating whether the product is rental /// [JsonProperty("is_rental")] public bool? IsRental { get; set; } + /// - /// Gets or sets the rental length for some period (price for this period) + /// Gets or sets the rental length for some period (price for this period) /// [JsonProperty("rental_price_length")] public int? RentalPriceLength { get; set; } /// - /// Gets or sets a value indicating whether the entity is ship enabled + /// Gets or sets a value indicating whether the entity is ship enabled /// [JsonProperty("is_ship_enabled")] public bool? IsShipEnabled { get; set; } + /// - /// Gets or sets a value indicating whether the entity is free shipping + /// Gets or sets a value indicating whether the entity is free shipping /// [JsonProperty("is_free_shipping")] public bool? IsFreeShipping { get; set; } + /// - /// Gets or sets a value this product should be shipped separately (each item) + /// Gets or sets a value this product should be shipped separately (each item) /// [JsonProperty("ship_separately")] public bool? ShipSeparately { get; set; } + /// - /// Gets or sets the additional shipping charge + /// Gets or sets the additional shipping charge /// [JsonProperty("additional_shipping_charge")] public decimal? AdditionalShippingCharge { get; set; } /// - /// Gets or sets a value indicating whether the product is marked as tax exempt + /// Gets or sets a value indicating whether the product is marked as tax exempt /// [JsonProperty("is_tax_exempt")] public bool? IsTaxExempt { get; set; } /// - /// Gets or sets a value indicating whether the product is telecommunications or broadcasting or electronic services + /// Gets or sets a value indicating whether the product is telecommunications or broadcasting or electronic services /// [JsonProperty("is_telecommunications_or_broadcasting_or_electronic_services")] public bool? IsTelecommunicationsOrBroadcastingOrElectronicServices { get; set; } /// - /// Gets or sets a value indicating whether multiple warehouses are used for this product + /// Gets or sets a value indicating whether multiple warehouses are used for this product /// [JsonProperty("use_multiple_warehouses")] public bool? UseMultipleWarehouses { get; set; } /// - /// Gets or sets a value indicating how to manage inventory. - /// 0 - do not track inventory - /// 1 - track inventory - /// 2 - track invetory by attributes + /// Gets or sets a value indicating how to manage inventory. + /// 0 - do not track inventory + /// 1 - track inventory + /// 2 - track invetory by attributes /// [JsonProperty("manage_inventory_method_id")] public int? ManageInventoryMethodId { get; set; } /// - /// Gets or sets the stock quantity + /// Gets or sets the stock quantity /// [JsonProperty("stock_quantity")] public int? StockQuantity { get; set; } + /// - /// Gets or sets a value indicating whether to display stock availability + /// Gets or sets a value indicating whether to display stock availability /// [JsonProperty("display_stock_availability")] public bool? DisplayStockAvailability { get; set; } + /// - /// Gets or sets a value indicating whether to display stock quantity + /// Gets or sets a value indicating whether to display stock quantity /// [JsonProperty("display_stock_quantity")] public bool? DisplayStockQuantity { get; set; } + /// - /// Gets or sets the minimum stock quantity + /// Gets or sets the minimum stock quantity /// [JsonProperty("min_stock_quantity")] public int? MinStockQuantity { get; set; } /// - /// Gets or sets the quantity when admin should be notified + /// Gets or sets the quantity when admin should be notified /// [JsonProperty("notify_admin_for_quantity_below")] public int? NotifyAdminForQuantityBelow { get; set; } /// - /// Gets or sets a value indicating whether to back in stock subscriptions are allowed + /// Gets or sets a value indicating whether to back in stock subscriptions are allowed /// [JsonProperty("allow_back_in_stock_subscriptions")] public bool? AllowBackInStockSubscriptions { get; set; } + /// - /// Gets or sets the order minimum quantity + /// Gets or sets the order minimum quantity /// [JsonProperty("order_minimum_quantity")] public int? OrderMinimumQuantity { get; set; } + /// - /// Gets or sets the order maximum quantity + /// Gets or sets the order maximum quantity /// [JsonProperty("order_maximum_quantity")] public int? OrderMaximumQuantity { get; set; } + /// - /// Gets or sets the comma seperated list of allowed quantities. null or empty if any quantity is allowed + /// Gets or sets the comma seperated list of allowed quantities. null or empty if any quantity is allowed /// [JsonProperty("allowed_quantities")] public string AllowedQuantities { get; set; } + /// - /// Gets or sets a value indicating whether we allow adding to the cart/wishlist only attribute combinations that exist and have stock greater than zero. - /// This option is used only when we have "manage inventory" set to "track inventory by product attributes" + /// Gets or sets a value indicating whether we allow adding to the cart/wishlist only attribute combinations that exist + /// and have stock greater than zero. + /// This option is used only when we have "manage inventory" set to "track inventory by product attributes" /// [JsonProperty("allow_adding_only_existing_attribute_combinations")] public bool? AllowAddingOnlyExistingAttributeCombinations { get; set; } /// - /// Gets or sets a value indicating whether to disable buy (Add to cart) button + /// Gets or sets a value indicating whether to disable buy (Add to cart) button /// [JsonProperty("disable_buy_button")] public bool? DisableBuyButton { get; set; } + /// - /// Gets or sets a value indicating whether to disable "Add to wishlist" button + /// Gets or sets a value indicating whether to disable "Add to wishlist" button /// [JsonProperty("disable_wishlist_button")] public bool? DisableWishlistButton { get; set; } + /// - /// Gets or sets a value indicating whether this item is available for Pre-Order + /// Gets or sets a value indicating whether this item is available for Pre-Order /// [JsonProperty("available_for_pre_order")] public bool? AvailableForPreOrder { get; set; } + /// - /// Gets or sets the start date and time of the product availability (for pre-order products) + /// Gets or sets the start date and time of the product availability (for pre-order products) /// [JsonProperty("pre_order_availability_start_date_time_utc")] public DateTime? PreOrderAvailabilityStartDateTimeUtc { get; set; } + /// - /// Gets or sets a value indicating whether to show "Call for Pricing" or "Call for quote" instead of price + /// Gets or sets a value indicating whether to show "Call for Pricing" or "Call for quote" instead of price /// [JsonProperty("call_for_price")] public bool? CallForPrice { get; set; } + /// - /// Gets or sets the price + /// Gets or sets the price /// [JsonProperty("price")] public decimal? Price { get; set; } + /// - /// Gets or sets the old price + /// Gets or sets the old price /// [JsonProperty("old_price")] public decimal? OldPrice { get; set; } + /// - /// Gets or sets the product cost + /// Gets or sets the product cost /// [JsonProperty("product_cost")] public decimal? ProductCost { get; set; } + /// - /// Gets or sets the product special price + /// Gets or sets the product special price /// [JsonProperty("special_price")] public decimal? SpecialPrice { get; set; } + /// - /// Gets or sets the start date and time of the special price + /// Gets or sets the start date and time of the special price /// [JsonProperty("special_price_start_date_time_utc")] public DateTime? SpecialPriceStartDateTimeUtc { get; set; } + /// - /// Gets or sets the end date and time of the special price + /// Gets or sets the end date and time of the special price /// [JsonProperty("special_price_end_date_time_utc")] public DateTime? SpecialPriceEndDateTimeUtc { get; set; } + /// - /// Gets or sets a value indicating whether a customer enters price + /// Gets or sets a value indicating whether a customer enters price /// [JsonProperty("customer_enters_price")] public bool? CustomerEntersPrice { get; set; } + /// - /// Gets or sets the minimum price entered by a customer + /// Gets or sets the minimum price entered by a customer /// [JsonProperty("minimum_customer_entered_price")] public decimal? MinimumCustomerEnteredPrice { get; set; } + /// - /// Gets or sets the maximum price entered by a customer + /// Gets or sets the maximum price entered by a customer /// [JsonProperty("maximum_customer_entered_price")] public decimal? MaximumCustomerEnteredPrice { get; set; } /// - /// Gets or sets a value indicating whether base price (PAngV) is enabled. Used by German users. + /// Gets or sets a value indicating whether base price (PAngV) is enabled. Used by German users. /// [JsonProperty("baseprice_enabled")] public bool? BasepriceEnabled { get; set; } + /// - /// Gets or sets an amount in product for PAngV + /// Gets or sets an amount in product for PAngV /// [JsonProperty("baseprice_amount")] public decimal? BasepriceAmount { get; set; } /// - /// Gets or sets a reference amount for PAngV + /// Gets or sets a reference amount for PAngV /// [JsonProperty("baseprice_base_amount")] public decimal? BasepriceBaseAmount { get; set; } /// - /// Gets or sets a value indicating whether this product has tier prices configured - /// The same as if we run this.TierPrices.Count > 0 - /// We use this property for performance optimization: - /// if this property is set to false, then we do not need to load tier prices navigation property - /// + /// Gets or sets a value indicating whether this product has tier prices configured + /// + /// The same as if we run this.TierPrices.Count > 0 + /// We use this property for performance optimization: + /// if this property is set to false, then we do not need to load tier prices navigation property + /// /// [JsonProperty("has_tier_prices")] public bool? HasTierPrices { get; set; } + /// - /// Gets or sets a value indicating whether this product has discounts applied - /// The same as if we run this.AppliedDiscounts.Count > 0 - /// We use this property for performance optimization: - /// if this property is set to false, then we do not need to load Applied Discounts navigation property - /// + /// Gets or sets a value indicating whether this product has discounts applied + /// + /// The same as if we run this.AppliedDiscounts.Count > 0 + /// We use this property for performance optimization: + /// if this property is set to false, then we do not need to load Applied Discounts navigation property + /// /// [JsonProperty("has_discounts_applied")] public bool? HasDiscountsApplied { get; set; } /// - /// Gets or sets the weight + /// Gets or sets the weight /// [JsonProperty("weight")] public decimal? Weight { get; set; } + /// - /// Gets or sets the length + /// Gets or sets the length /// [JsonProperty("length")] public decimal? Length { get; set; } + /// - /// Gets or sets the width + /// Gets or sets the width /// [JsonProperty("width")] public decimal? Width { get; set; } + /// - /// Gets or sets the height + /// Gets or sets the height /// [JsonProperty("height")] public decimal? Height { get; set; } /// - /// Gets or sets the available start date and time + /// Gets or sets the available start date and time /// [JsonProperty("available_start_date_time_utc")] public DateTime? AvailableStartDateTimeUtc { get; set; } + /// - /// Gets or sets the available end date and time + /// Gets or sets the available end date and time /// [JsonProperty("available_end_date_time_utc")] public DateTime? AvailableEndDateTimeUtc { get; set; } /// - /// Gets or sets a display order. - /// This value is used when sorting associated products (used with "grouped" products) - /// This value is used when sorting home page products + /// Gets or sets a display order. + /// This value is used when sorting associated products (used with "grouped" products) + /// This value is used when sorting home page products /// [JsonProperty("display_order")] public int? DisplayOrder { get; set; } + /// - /// Gets or sets a value indicating whether the entity is published + /// Gets or sets a value indicating whether the entity is published /// [JsonProperty("published")] public bool? Published { get; set; } + /// - /// Gets or sets a value indicating whether the entity has been deleted + /// Gets or sets a value indicating whether the entity has been deleted /// [JsonProperty("deleted")] public bool? Deleted { get; set; } /// - /// Gets or sets the date and time of product creation + /// Gets or sets the date and time of product creation /// [JsonProperty("created_on_utc")] public DateTime? CreatedOnUtc { get; set; } + /// - /// Gets or sets the date and time of product update + /// Gets or sets the date and time of product update /// [JsonProperty("updated_on_utc")] public DateTime? UpdatedOnUtc { get; set; } /// - /// Gets or sets the product type + /// Gets or sets the product type /// - [ProductTypeValidationAttribute] + [ProductTypeValidation] [JsonProperty("product_type")] public string ProductType { get { - var productTypeId = this._productTypeId; - if (productTypeId != null) return ((ProductType)productTypeId).ToString(); + var productTypeId = _productTypeId; + if (productTypeId != null) + { + return ((ProductType) productTypeId).ToString(); + } return null; } @@ -501,9 +533,12 @@ public string ProductType ProductType productTypeId; if (Enum.TryParse(value, out productTypeId)) { - this._productTypeId = (int)productTypeId; + _productTypeId = (int) productTypeId; + } + else + { + _productTypeId = null; } - else this._productTypeId = null; } } @@ -511,136 +546,36 @@ public string ProductType public int? ParentGroupedProductId { get; set; } [JsonProperty("role_ids")] - public List RoleIds - { - get - { - return _roleIds; - } - set - { - _roleIds = value; - } - } + public List RoleIds { get; set; } [JsonProperty("discount_ids")] - public List DiscountIds - { - get - { - return _discountIds; - } - set - { - _discountIds = value; - } - } + public List DiscountIds { get; set; } [JsonProperty("store_ids")] - public List StoreIds - { - get - { - return _storeIds; - } - set - { - _storeIds = value; - } - } + public List StoreIds { get; set; } [JsonProperty("manufacturer_ids")] - public List ManufacturerIds - { - get - { - return _manufacturerIds; - } - set - { - _manufacturerIds = value; - } - } - + public List ManufacturerIds { get; set; } + [ImageCollectionValidation] [JsonProperty("images")] - public List Images - { - get - { - return _images; - } - set - { - _images = value; - } - } + public List Images { get; set; } [JsonProperty("attributes")] - public List ProductAttributeMappings - { - get - { - return _productAttributeMappings; - } - set - { - _productAttributeMappings = value; - } - } + public List ProductAttributeMappings { get; set; } [JsonProperty("product_attribute_combinations")] - public List ProductAttributeCombinations - { - get - { - return _productAttributeCombinations; - } - set - { - _productAttributeCombinations = value; - } - } + public List ProductAttributeCombinations { get; set; } [JsonProperty("product_specification_attributes")] - public List ProductSpecificationAttributes - { - get - { - return _productSpecificationAttributes; - } - set - { - _productSpecificationAttributes = value; - } - } + public List ProductSpecificationAttributes { get; set; } [JsonProperty("associated_product_ids")] - public List AssociatedProductIds - { - get - { - return _associatedProductIds; - } - set - { - _associatedProductIds = value; - } - } + public List AssociatedProductIds { get; set; } [JsonProperty("tags")] - public List Tags - { - get - { - return _tags; - } - set - { - _tags = value; - } - } + public List Tags { get; set; } [ValidateVendor] [JsonProperty("vendor_id")] @@ -649,4 +584,4 @@ public List Tags [JsonProperty("se_name")] public string SeName { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Products/ProductsCountRootObject.cs b/Nop.Plugin.Api/DTOs/Products/ProductsCountRootObject.cs index 4730d4b..c8f2713 100644 --- a/Nop.Plugin.Api/DTOs/Products/ProductsCountRootObject.cs +++ b/Nop.Plugin.Api/DTOs/Products/ProductsCountRootObject.cs @@ -1,10 +1,12 @@ -using Newtonsoft.Json; +using System; +using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Products +namespace Nop.Plugin.Api.DTO.Products { public class ProductsCountRootObject { [JsonProperty("count")] public int Count { get; set; } + } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Products/ProductsRootObjectDto.cs b/Nop.Plugin.Api/DTOs/Products/ProductsRootObjectDto.cs index bfed84f..bd4ecac 100644 --- a/Nop.Plugin.Api/DTOs/Products/ProductsRootObjectDto.cs +++ b/Nop.Plugin.Api/DTOs/Products/ProductsRootObjectDto.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Products +namespace Nop.Plugin.Api.DTO.Products { public class ProductsRootObjectDto : ISerializableObject { @@ -21,7 +21,7 @@ public string GetPrimaryPropertyName() public Type GetPrimaryPropertyType() { - return typeof (ProductDto); + return typeof(ProductDto); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/ShoppingCarts/ShoppingCartItemDto.cs b/Nop.Plugin.Api/DTOs/ShoppingCarts/ShoppingCartItemDto.cs index a7e9fa4..973bdf6 100644 --- a/Nop.Plugin.Api/DTOs/ShoppingCarts/ShoppingCartItemDto.cs +++ b/Nop.Plugin.Api/DTOs/ShoppingCarts/ShoppingCartItemDto.cs @@ -1,74 +1,63 @@ using System; +using System.Collections.Generic; using Newtonsoft.Json; using Nop.Core.Domain.Orders; -using Nop.Plugin.Api.DTOs.Customers; -using Nop.Plugin.Api.DTOs.Products; -using Nop.Plugin.Api.Validators; -using System.Collections.Generic; -using Nop.Plugin.Api.DTOs.Base; +using Nop.Plugin.Api.DTO.Base; +using Nop.Plugin.Api.DTO.Customers; +using Nop.Plugin.Api.DTO.Products; -namespace Nop.Plugin.Api.DTOs.ShoppingCarts +namespace Nop.Plugin.Api.DTO.ShoppingCarts { + //[Validator(typeof(ShoppingCartItemDtoValidator))] [JsonObject(Title = "shopping_cart_item")] public class ShoppingCartItemDto : BaseDto { private int? _shoppingCartTypeId; - private List _attributes; /// - /// Gets or sets the selected attributes + /// Gets or sets the selected attributes /// [JsonProperty("product_attributes")] - public List Attributes - { - get - { - return _attributes; - } - set - { - _attributes = value; - } - } + public List Attributes { get; set; } /// - /// Gets or sets the price enter by a customer + /// Gets or sets the price enter by a customer /// [JsonProperty("customer_entered_price")] public decimal? CustomerEnteredPrice { get; set; } /// - /// Gets or sets the quantity + /// Gets or sets the quantity /// [JsonProperty("quantity")] public int? Quantity { get; set; } /// - /// Gets or sets the rental product start date (null if it's not a rental product) + /// Gets or sets the rental product start date (null if it's not a rental product) /// [JsonProperty("rental_start_date_utc")] public DateTime? RentalStartDateUtc { get; set; } /// - /// Gets or sets the rental product end date (null if it's not a rental product) + /// Gets or sets the rental product end date (null if it's not a rental product) /// [JsonProperty("rental_end_date_utc")] public DateTime? RentalEndDateUtc { get; set; } /// - /// Gets or sets the date and time of instance creation + /// Gets or sets the date and time of instance creation /// [JsonProperty("created_on_utc")] public DateTime? CreatedOnUtc { get; set; } /// - /// Gets or sets the date and time of instance update + /// Gets or sets the date and time of instance update /// [JsonProperty("updated_on_utc")] public DateTime? UpdatedOnUtc { get; set; } /// - /// Gets the log type + /// Gets the log type /// [JsonProperty("shopping_cart_type")] public string ShoppingCartType @@ -77,7 +66,10 @@ public string ShoppingCartType { var shoppingCartTypeId = _shoppingCartTypeId; - if (shoppingCartTypeId != null) return ((ShoppingCartType)shoppingCartTypeId).ToString(); + if (shoppingCartTypeId != null) + { + return ((ShoppingCartType) shoppingCartTypeId).ToString(); + } return null; } @@ -86,9 +78,12 @@ public string ShoppingCartType ShoppingCartType shoppingCartType; if (Enum.TryParse(value, true, out shoppingCartType)) { - _shoppingCartTypeId = (int)shoppingCartType; + _shoppingCartTypeId = (int) shoppingCartType; + } + else + { + _shoppingCartTypeId = null; } - else _shoppingCartTypeId = null; } } @@ -96,7 +91,7 @@ public string ShoppingCartType public int? ProductId { get; set; } /// - /// Gets or sets the product + /// Gets or sets the product /// [JsonProperty("product")] public ProductDto ProductDto { get; set; } @@ -105,9 +100,9 @@ public string ShoppingCartType public int? CustomerId { get; set; } /// - /// Gets or sets the customer + /// Gets or sets the customer /// [JsonProperty("customer")] public CustomerForShoppingCartItemDto CustomerDto { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/ShoppingCarts/ShoppingCartItemsRootObject.cs b/Nop.Plugin.Api/DTOs/ShoppingCarts/ShoppingCartItemsRootObject.cs index 4983112..8c0c410 100644 --- a/Nop.Plugin.Api/DTOs/ShoppingCarts/ShoppingCartItemsRootObject.cs +++ b/Nop.Plugin.Api/DTOs/ShoppingCarts/ShoppingCartItemsRootObject.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.ShoppingCarts +namespace Nop.Plugin.Api.DTO.ShoppingCarts { public class ShoppingCartItemsRootObject : ISerializableObject { @@ -21,7 +21,7 @@ public string GetPrimaryPropertyName() public Type GetPrimaryPropertyType() { - return typeof (ShoppingCartItemDto); + return typeof(ShoppingCartItemDto); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/SpecificationAttributes/ProductSpecificationAttributeDto.cs b/Nop.Plugin.Api/DTOs/SpecificationAttributes/ProductSpecificationAttributeDto.cs index 0fcc808..5aa63e1 100644 --- a/Nop.Plugin.Api/DTOs/SpecificationAttributes/ProductSpecificationAttributeDto.cs +++ b/Nop.Plugin.Api/DTOs/SpecificationAttributes/ProductSpecificationAttributeDto.cs @@ -1,81 +1,75 @@ -using Newtonsoft.Json; +using System; +using Newtonsoft.Json; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.Validators; -using System; -namespace Nop.Plugin.Api.DTOs.SpecificationAttributes +namespace Nop.Plugin.Api.DTO.SpecificationAttributes { [JsonObject(Title = "product_specification_attribute")] + //[Validator(typeof(ProductSpecificationAttributeDtoValidator))] public class ProductSpecificationAttributeDto { /// - /// Gets or sets the id + /// Gets or sets the id /// [JsonProperty("id")] public int Id { get; set; } /// - /// Gets or sets the product id + /// Gets or sets the product id /// [JsonProperty("product_id")] public int ProductId { get; set; } /// - /// Gets or sets the attribute type ID + /// Gets or sets the attribute type ID /// [JsonProperty("attribute_type_id")] public int AttributeTypeId { get; set; } /// - /// Gets or sets the specification attribute identifier + /// Gets or sets the specification attribute identifier /// [JsonProperty("specification_attribute_option_id")] public int SpecificationAttributeOptionId { get; set; } /// - /// Gets or sets the custom value + /// Gets or sets the custom value /// [JsonProperty("custom_value")] public string CustomValue { get; set; } /// - /// Gets or sets whether the attribute can be filtered by + /// Gets or sets whether the attribute can be filtered by /// [JsonProperty("allow_filtering")] public bool AllowFiltering { get; set; } /// - /// Gets or sets whether the attribute will be shown on the product page + /// Gets or sets whether the attribute will be shown on the product page /// [JsonProperty("show_on_product_page")] public bool ShowOnProductPage { get; set; } /// - /// Gets or sets the display order + /// Gets or sets the display order /// [JsonProperty("display_order")] public int DisplayOrder { get; set; } /// - /// Gets the attribute control type by casting the AttributeTypeId; sets the AttributeTypeId + /// Gets the attribute control type by casting the AttributeTypeId; sets the AttributeTypeId /// [JsonProperty("attribute_type")] public string AttributeType { - get - { - return ((SpecificationAttributeType)AttributeTypeId).ToString(); - } - set - { - AttributeTypeId = (int)Enum.Parse(typeof(SpecificationAttributeType), value); - } + get => ((SpecificationAttributeType) AttributeTypeId).ToString(); + set => AttributeTypeId = (int) Enum.Parse(typeof(SpecificationAttributeType), value); } /// - /// Gets or sets the specification attribute + /// Gets or sets the specification attribute /// [JsonProperty("specification_attribute_option")] public virtual SpecificationAttributeOptionDto SpecificationAttributeOption { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/SpecificationAttributes/ProductSpecificationAttributesCountRootObject.cs b/Nop.Plugin.Api/DTOs/SpecificationAttributes/ProductSpecificationAttributesCountRootObject.cs index 0cb3250..6f9efea 100644 --- a/Nop.Plugin.Api/DTOs/SpecificationAttributes/ProductSpecificationAttributesCountRootObject.cs +++ b/Nop.Plugin.Api/DTOs/SpecificationAttributes/ProductSpecificationAttributesCountRootObject.cs @@ -1,10 +1,10 @@ using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.SpecificationAttributes +namespace Nop.Plugin.Api.DTO.SpecificationAttributes { public class ProductSpecificationAttributesCountRootObject { [JsonProperty("count")] public int Count { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/SpecificationAttributes/ProductSpecificationAttributesRootObjectDto.cs b/Nop.Plugin.Api/DTOs/SpecificationAttributes/ProductSpecificationAttributesRootObjectDto.cs index e4df467..f67f67d 100644 --- a/Nop.Plugin.Api/DTOs/SpecificationAttributes/ProductSpecificationAttributesRootObjectDto.cs +++ b/Nop.Plugin.Api/DTOs/SpecificationAttributes/ProductSpecificationAttributesRootObjectDto.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.SpecificationAttributes +namespace Nop.Plugin.Api.DTO.SpecificationAttributes { public class ProductSpecificationAttributesRootObjectDto : ISerializableObject { @@ -21,7 +21,7 @@ public string GetPrimaryPropertyName() public Type GetPrimaryPropertyType() { - return typeof (ProductSpecificationAttributeDto); + return typeof(ProductSpecificationAttributeDto); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributeDto.cs b/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributeDto.cs index c6b59c2..03cba38 100644 --- a/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributeDto.cs +++ b/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributeDto.cs @@ -1,34 +1,34 @@ -using Newtonsoft.Json; -using Nop.Plugin.Api.Validators; -using System.Collections.Generic; +using System.Collections.Generic; +using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.SpecificationAttributes +namespace Nop.Plugin.Api.DTO.SpecificationAttributes { [JsonObject(Title = "specification_attribute")] + //[Validator(typeof(SpecificationAttributeDtoValidator))] public class SpecificationAttributeDto { /// - /// Gets or sets the id + /// Gets or sets the id /// [JsonProperty("id")] public int Id { get; set; } /// - /// Gets or sets the name + /// Gets or sets the name /// [JsonProperty("name")] public string Name { get; set; } /// - /// Gets or sets the display order + /// Gets or sets the display order /// [JsonProperty("display_order")] public int DisplayOrder { get; set; } /// - /// Gets or sets the specification attribute options + /// Gets or sets the specification attribute options /// [JsonProperty("specification_attribute_options")] public List SpecificationAttributeOptions { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributeOptionDto.cs b/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributeOptionDto.cs index ca13b93..44501a1 100644 --- a/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributeOptionDto.cs +++ b/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributeOptionDto.cs @@ -1,39 +1,39 @@ using Newtonsoft.Json; -using Nop.Plugin.Api.Validators; -namespace Nop.Plugin.Api.DTOs.SpecificationAttributes +namespace Nop.Plugin.Api.DTO.SpecificationAttributes { [JsonObject(Title = "specification_attribute_option")] + //[Validator(typeof(SpecificationAttributeOptionDtoValidator))] public class SpecificationAttributeOptionDto { /// - /// Gets or sets the id + /// Gets or sets the id /// [JsonProperty("id")] public int Id { get; set; } /// - /// Gets or sets the specification attribute identifier + /// Gets or sets the specification attribute identifier /// [JsonProperty("specification_attribute_id")] public int SpecificationAttributeId { get; set; } /// - /// Gets or sets the name + /// Gets or sets the name /// [JsonProperty("name")] public string Name { get; set; } /// - /// Gets or sets the color RGB value (used when you want to display "Color squares" instead of text) + /// Gets or sets the color RGB value (used when you want to display "Color squares" instead of text) /// [JsonProperty("color_squares_rgb")] public string ColorSquaresRgb { get; set; } /// - /// Gets or sets the display order + /// Gets or sets the display order /// [JsonProperty("display_order")] public int DisplayOrder { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributesCountRootObject.cs b/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributesCountRootObject.cs index 4961ee3..8dd235a 100644 --- a/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributesCountRootObject.cs +++ b/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributesCountRootObject.cs @@ -1,10 +1,10 @@ using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.SpecificationAttributes +namespace Nop.Plugin.Api.DTO.SpecificationAttributes { public class SpecificationAttributesCountRootObject { [JsonProperty("count")] public int Count { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributesRootObjectDto.cs b/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributesRootObjectDto.cs index 654a00a..502aec3 100644 --- a/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributesRootObjectDto.cs +++ b/Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributesRootObjectDto.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.SpecificationAttributes +namespace Nop.Plugin.Api.DTO.SpecificationAttributes { public class SpecificationAttributesRootObjectDto : ISerializableObject { @@ -21,7 +21,7 @@ public string GetPrimaryPropertyName() public Type GetPrimaryPropertyType() { - return typeof (SpecificationAttributeDto); + return typeof(SpecificationAttributeDto); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/DTOs/Stores/StoreDto.cs b/Nop.Plugin.Api/DTOs/Stores/StoreDto.cs index a1a7a1a..7744ac9 100644 --- a/Nop.Plugin.Api/DTOs/Stores/StoreDto.cs +++ b/Nop.Plugin.Api/DTOs/Stores/StoreDto.cs @@ -1,98 +1,87 @@ using System.Collections.Generic; using Newtonsoft.Json; -using Nop.Plugin.Api.DTOs.Base; +using Nop.Plugin.Api.DTO.Base; -namespace Nop.Plugin.Api.DTOs.Stores +namespace Nop.Plugin.Api.DTO.Stores { [JsonObject(Title = "store")] public class StoreDto : BaseDto { - private List _languageIds; - /// - /// Gets or sets the store name + /// Gets or sets the store name /// [JsonProperty("name")] public string Name { get; set; } /// - /// Gets or sets the store URL + /// Gets or sets the store URL /// [JsonProperty("url")] public string Url { get; set; } /// - /// Gets or sets a value indicating whether SSL is enabled + /// Gets or sets a value indicating whether SSL is enabled /// [JsonProperty("ssl_enabled")] public bool? SslEnabled { get; set; } /// - /// Gets or sets the store secure URL (HTTPS) + /// Gets or sets the store secure URL (HTTPS) /// [JsonProperty("secure_url")] public string SecureUrl { get; set; } /// - /// Gets or sets the comma separated list of possible HTTP_HOST values + /// Gets or sets the comma separated list of possible HTTP_HOST values /// [JsonProperty("hosts")] public string Hosts { get; set; } /// - /// Gets or sets the identifier of the default language for this store; 0 is set when we use the default language display order + /// Gets or sets the identifier of the default language for this store; 0 is set when we use the default language + /// display order /// [JsonProperty("default_language_id")] public int? DefaultLanguageId { get; set; } /// - /// Gets or sets the identifier of the language IDs for this store + /// Gets or sets the identifier of the language IDs for this store /// [JsonProperty("language_ids")] - public List LanguageIds - { - get - { - return _languageIds; - } - set - { - _languageIds = value; - } - } + public List LanguageIds { get; set; } /// - /// Gets or sets the display order + /// Gets or sets the display order /// [JsonProperty("display_order")] public int? DisplayOrder { get; set; } /// - /// Gets or sets the company name + /// Gets or sets the company name /// [JsonProperty("company_name")] public string CompanyName { get; set; } /// - /// Gets or sets the company address + /// Gets or sets the company address /// [JsonProperty("company_address")] public string CompanyAddress { get; set; } /// - /// Gets or sets the store phone number + /// Gets or sets the store phone number /// [JsonProperty("company_phone_number")] public string CompanyPhoneNumber { get; set; } /// - /// Gets or sets the company VAT (used in Europe Union countries) + /// Gets or sets the company VAT (used in Europe Union countries) /// [JsonProperty("company_vat")] public string CompanyVat { get; set; } /// - /// Get or set the currency format + /// Get or set the currency format /// [JsonProperty("primary_currency_display_locale")] public string PrimaryCurrencyDisplayLocale { get; set; } diff --git a/Nop.Plugin.Api/DTOs/Stores/StoresRootObject.cs b/Nop.Plugin.Api/DTOs/Stores/StoresRootObject.cs index 2ec14b1..e030f54 100644 --- a/Nop.Plugin.Api/DTOs/Stores/StoresRootObject.cs +++ b/Nop.Plugin.Api/DTOs/Stores/StoresRootObject.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using Newtonsoft.Json; -namespace Nop.Plugin.Api.DTOs.Stores +namespace Nop.Plugin.Api.DTO.Stores { public class StoresRootObject : ISerializableObject { diff --git a/Nop.Plugin.Api/Data/ApiObjectContext.cs b/Nop.Plugin.Api/Data/ApiObjectContext.cs deleted file mode 100644 index 27c54b8..0000000 --- a/Nop.Plugin.Api/Data/ApiObjectContext.cs +++ /dev/null @@ -1,118 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Nop.Core; -using Nop.Data; -using Nop.Data.Extensions; -using Nop.Plugin.Api.DataMappings; -using System; -using System.Linq; - -namespace Nop.Plugin.Api.Data -{ - public class ApiObjectContext : DbContext, IDbContext - { - public ApiObjectContext(DbContextOptions options) - : base(options) - { - } - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.ApplyConfiguration(new WebHooksMap()); - - //disable EdmMetadata generation - //modelBuilder.Conventions.Remove(); - base.OnModelCreating(modelBuilder); - } - - //TODO: Upgrade 4.10 Check this! - //public string CreateDatabaseScript() - //{ - // return ((IObjectContextAdapter)this).ObjectContext.CreateDatabaseScript(); - //} - - /// - /// Install - /// - public void Install() - { - //TODO: Upgrade 4.10 Check this! - //create the table - //var dbScript = CreateDatabaseScript(); - //Database.ExecuteSqlCommand(dbScript); - SaveChanges(); - } - - /// - /// Uninstall - /// - public void Uninstall() - { - this.DropPluginTable(nameof(Domain.WebHooks)); - } - - /// - /// Creates a DbSet that can be used to query and save instances of entity - /// - /// Entity type - /// A set for the given entity type - public virtual new DbSet Set() where TEntity : BaseEntity - { - return base.Set(); - } - - /// - /// Generate a script to create all tables for the current model - /// - /// A SQL script - public virtual string GenerateCreateScript() - { - return this.Database.GenerateCreateScript(); - } - - public IQueryable QueryFromSql(string sql, params object[] parameters) where TQuery : class - { - throw new NotImplementedException(); - } - - /// - /// Creates a LINQ query for the entity based on a raw SQL query - /// - /// Entity type - /// The raw SQL query - /// The values to be assigned to parameters - /// An IQueryable representing the raw SQL query - public virtual IQueryable EntityFromSql(string sql, params object[] parameters) where TEntity : BaseEntity - { - throw new NotImplementedException(); - } - - /// - /// Executes the given SQL against the database - /// - /// The SQL to execute - /// true - the transaction creation is not ensured; false - the transaction creation is ensured. - /// The timeout to use for command. Note that the command timeout is distinct from the connection timeout, which is commonly set on the database connection string - /// Parameters to use with the SQL - /// The number of rows affected - public virtual int ExecuteSqlCommand(RawSqlString sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters) - { - using (var transaction = this.Database.BeginTransaction()) - { - var result = this.Database.ExecuteSqlCommand(sql, parameters); - transaction.Commit(); - - return result; - } - } - - /// - /// Detach an entity from the context - /// - /// Entity type - /// Entity - public virtual void Detach(TEntity entity) where TEntity : BaseEntity - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/DataMappings/WebHooksMap.cs b/Nop.Plugin.Api/DataMappings/WebHooksMap.cs deleted file mode 100644 index c7f3415..0000000 --- a/Nop.Plugin.Api/DataMappings/WebHooksMap.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using Nop.Data.Mapping; - -namespace Nop.Plugin.Api.DataMappings -{ - public class WebHooksMap : NopEntityTypeConfiguration - { - public override void Configure(EntityTypeBuilder builder) - { - builder.ToTable("WebHooks", "WebHooks"); - builder.HasKey(wh => new { wh.User, wh.Id }); - - builder.Property(wh => wh.ProtectedData).IsRequired(); - builder.Property(wh => wh.RowVer).IsRowVersion(); - } - } -} diff --git a/Nop.Plugin.Api/DataStructures/ApiList.cs b/Nop.Plugin.Api/DataStructures/ApiList.cs index 4c49337..16364f6 100644 --- a/Nop.Plugin.Api/DataStructures/ApiList.cs +++ b/Nop.Plugin.Api/DataStructures/ApiList.cs @@ -5,14 +5,14 @@ namespace Nop.Plugin.Api.DataStructures { public class ApiList : List { - public int PageIndex { get; private set; } - public int PageSize { get; private set; } - public ApiList(IQueryable source, int pageIndex, int pageSize) { PageSize = pageSize; PageIndex = pageIndex; AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList()); } + + public int PageIndex { get; } + public int PageSize { get; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Delta/Delta.cs b/Nop.Plugin.Api/Delta/Delta.cs index be6a313..9fabb00 100644 --- a/Nop.Plugin.Api/Delta/Delta.cs +++ b/Nop.Plugin.Api/Delta/Delta.cs @@ -9,55 +9,33 @@ namespace Nop.Plugin.Api.Delta { public class Delta where TDto : class, new() { - private TDto _dto; - - private readonly IMappingHelper _mappingHelper = new MappingHelper(); - private readonly Dictionary _changedJsonPropertyNames; - - private readonly IJsonPropertyMapper _jsonPropertyMapper; - - public Dictionary ObjectPropertyNameValuePairs = new Dictionary(); - - private Dictionary _propertyValuePairs; - private Dictionary PropertyValuePairs - { - get - { - if (_propertyValuePairs == null) - { - _propertyValuePairs = GetPropertyValuePairs(typeof(TDto), _changedJsonPropertyNames); - } + private readonly IJsonPropertyMapper _jsonPropertyMapper; - return _propertyValuePairs; - } - } + private readonly IMappingHelper _mappingHelper = new MappingHelper(); + private TDto _dto; - public TDto Dto - { - get - { - if (_dto == null) - { - _dto = new TDto(); - } + private Dictionary _propertyValuePairs; - return _dto; - } - } + public Dictionary ObjectPropertyNameValuePairs = new Dictionary(); - public Delta(Dictionary passedChangedJsonPropertyValuePaires) + public Delta(Dictionary passedChangedJsonPropertyValuePairs) { _jsonPropertyMapper = EngineContext.Current.Resolve(); - _changedJsonPropertyNames = passedChangedJsonPropertyValuePaires; + _changedJsonPropertyNames = passedChangedJsonPropertyValuePairs; _mappingHelper.SetValues(PropertyValuePairs, Dto, typeof(TDto), ObjectPropertyNameValuePairs, true); } + private Dictionary PropertyValuePairs => + _propertyValuePairs ?? (_propertyValuePairs = GetPropertyValuePairs(typeof(TDto), _changedJsonPropertyNames)); + + public TDto Dto => _dto ?? (_dto = new TDto()); + public void Merge(TEntity entity, bool mergeComplexTypeCollections = true) { - _mappingHelper.SetValues(PropertyValuePairs, entity, entity.GetType(), null,mergeComplexTypeCollections); + _mappingHelper.SetValues(PropertyValuePairs, entity, entity.GetType(), null, mergeComplexTypeCollections); } public void Merge(object dto, TEntity entity, bool mergeComplexTypeCollections = true) @@ -69,12 +47,14 @@ public void Merge(object dto, TEntity entity, bool mergeComplexTypeColl } } - private Dictionary GetPropertyValuePairs(Type type, Dictionary changedJsonPropertyNames) + private Dictionary GetPropertyValuePairs(Type type, Dictionary changedJsonPropertyNames) { var propertyValuePairs = new Dictionary(); if (changedJsonPropertyNames == null) + { return propertyValuePairs; + } var typeMap = _jsonPropertyMapper.GetMap(type); @@ -101,10 +81,12 @@ private Dictionary GetPropertyValuePairs(Type type, Dictionary; + var collection = changedProperty.Value as IEnumerable; var collectionElementsType = propertyType.GetGenericArguments()[0]; var resultCollection = new List(); @@ -122,7 +104,7 @@ private Dictionary GetPropertyValuePairs(Type type, Dictionary; - resultCollection.Add(GetPropertyValuePairs(collectionElementsType,itemDictionary)); + resultCollection.Add(GetPropertyValuePairs(collectionElementsType, itemDictionary)); } } @@ -145,4 +127,4 @@ private Dictionary GetPropertyValuePairs(Type type, Dictionary { public Address Initialize() { - var address = new Address() - { - CreatedOnUtc = DateTime.UtcNow - }; + var address = new Address + { + CreatedOnUtc = DateTime.UtcNow + }; return address; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Factories/CategoryFactory.cs b/Nop.Plugin.Api/Factories/CategoryFactory.cs index 00e861d..5d299bc 100644 --- a/Nop.Plugin.Api/Factories/CategoryFactory.cs +++ b/Nop.Plugin.Api/Factories/CategoryFactory.cs @@ -7,8 +7,8 @@ namespace Nop.Plugin.Api.Factories { public class CategoryFactory : IFactory { - private readonly ICategoryTemplateService _categoryTemplateService; private readonly CatalogSettings _catalogSettings; + private readonly ICategoryTemplateService _categoryTemplateService; public CategoryFactory(ICategoryTemplateService categoryTemplateService, CatalogSettings catalogSettings) { @@ -28,7 +28,7 @@ public Category Initialize() { defaultCategory.CategoryTemplateId = firstTemplate.Id; } - + //default values defaultCategory.PageSize = _catalogSettings.DefaultCategoryPageSize; defaultCategory.PageSizeOptions = _catalogSettings.DefaultCategoryPageSizeOptions; @@ -42,4 +42,4 @@ public Category Initialize() return defaultCategory; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Factories/CustomerFactory.cs b/Nop.Plugin.Api/Factories/CustomerFactory.cs index 9b40977..bd8d22b 100644 --- a/Nop.Plugin.Api/Factories/CustomerFactory.cs +++ b/Nop.Plugin.Api/Factories/CustomerFactory.cs @@ -7,15 +7,15 @@ public class CustomerFactory : IFactory { public Customer Initialize() { - var defaultCustomer = new Customer() - { - CustomerGuid = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow, - LastActivityDateUtc = DateTime.UtcNow, - Active = true - }; + var defaultCustomer = new Customer + { + CustomerGuid = Guid.NewGuid(), + CreatedOnUtc = DateTime.UtcNow, + LastActivityDateUtc = DateTime.UtcNow, + Active = true + }; return defaultCustomer; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Factories/IFactory.cs b/Nop.Plugin.Api/Factories/IFactory.cs index 5c7ed4e..30f4fcd 100644 --- a/Nop.Plugin.Api/Factories/IFactory.cs +++ b/Nop.Plugin.Api/Factories/IFactory.cs @@ -4,4 +4,4 @@ public interface IFactory { T Initialize(); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Factories/ManufacturerFactory.cs b/Nop.Plugin.Api/Factories/ManufacturerFactory.cs index cc4bd2f..bfa240e 100644 --- a/Nop.Plugin.Api/Factories/ManufacturerFactory.cs +++ b/Nop.Plugin.Api/Factories/ManufacturerFactory.cs @@ -1,5 +1,5 @@ -using Nop.Core.Domain.Catalog; -using System; +using System; +using Nop.Core.Domain.Catalog; namespace Nop.Plugin.Api.Factories { @@ -29,4 +29,4 @@ public Manufacturer Initialize() return defaultManufacturer; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Factories/OrderFactory.cs b/Nop.Plugin.Api/Factories/OrderFactory.cs index b8a3dca..7e42d61 100644 --- a/Nop.Plugin.Api/Factories/OrderFactory.cs +++ b/Nop.Plugin.Api/Factories/OrderFactory.cs @@ -20,4 +20,4 @@ public Order Initialize() return order; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Factories/ProductFactory.cs b/Nop.Plugin.Api/Factories/ProductFactory.cs index 39631de..d1710d3 100644 --- a/Nop.Plugin.Api/Factories/ProductFactory.cs +++ b/Nop.Plugin.Api/Factories/ProductFactory.cs @@ -19,7 +19,7 @@ public ProductFactory(IMeasureService measureService, MeasureSettings measureSet public Product Initialize() { var defaultProduct = new Product(); - + defaultProduct.Weight = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId).Ratio; defaultProduct.CreatedOnUtc = DateTime.UtcNow; @@ -36,14 +36,14 @@ public Product Initialize() defaultProduct.NotifyAdminForQuantityBelow = 1; defaultProduct.OrderMinimumQuantity = 1; defaultProduct.OrderMaximumQuantity = 10000; - + defaultProduct.UnlimitedDownloads = true; defaultProduct.IsShipEnabled = true; defaultProduct.AllowCustomerReviews = true; defaultProduct.Published = true; defaultProduct.VisibleIndividually = true; - + return defaultProduct; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Factories/ShoppingCartItemFactory.cs b/Nop.Plugin.Api/Factories/ShoppingCartItemFactory.cs index f4e69dd..c664c7f 100644 --- a/Nop.Plugin.Api/Factories/ShoppingCartItemFactory.cs +++ b/Nop.Plugin.Api/Factories/ShoppingCartItemFactory.cs @@ -15,4 +15,4 @@ public ShoppingCartItem Initialize() return newShoppingCartItem; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Helpers/CryptoHelper.cs b/Nop.Plugin.Api/Helpers/CryptoHelper.cs deleted file mode 100644 index 4a00119..0000000 --- a/Nop.Plugin.Api/Helpers/CryptoHelper.cs +++ /dev/null @@ -1,106 +0,0 @@ -using Nop.Core.Infrastructure; - -namespace Nop.Plugin.Api.Helpers -{ - using Microsoft.IdentityModel.Tokens; - using Newtonsoft.Json; - using System.IO; - using System.Security.Cryptography; - using Nop.Core; - using Microsoft.Extensions.DependencyInjection; - - - public static class CryptoHelper - { - // Need to ensure that the key would be the same through the application lifetime. - private static RsaSecurityKey _key; - private const string TokenSigningKeyFileName = "api-token-signing-key.json"; - - public static RsaSecurityKey CreateRsaSecurityKey() - { - if (_key == null) - { - string pathToKey = CommonHelper.DefaultFileProvider.MapPath($"~/App_Data/{TokenSigningKeyFileName}"); - - if (!File.Exists(pathToKey)) - { - // generate random parameters - var randomParameters = GetRandomParameters(); - - var rsaParams = new RSAParametersWithPrivate(); - rsaParams.SetParameters(randomParameters); - string serializedParameters = JsonConvert.SerializeObject(rsaParams); - - // create file and save the key - File.WriteAllText(pathToKey, serializedParameters); - } - - // load the key - if (!File.Exists(pathToKey)) - throw new FileNotFoundException("Check configuration - cannot find auth key file: " + pathToKey); - - var keyParams = JsonConvert.DeserializeObject(File.ReadAllText(pathToKey)); - - // create signing key by the key above - _key = new RsaSecurityKey(keyParams.ToRSAParameters()); - } - - return _key; - } - - public static RSAParameters GetRandomParameters() - { - using (var rsa = new RSACryptoServiceProvider(2048)) - { - try - { - return rsa.ExportParameters(true); - } - finally - { - rsa.PersistKeyInCsp = false; - } - } - } - - // https://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample/blob/master/src/TokenAuthExampleWebApplication/RSAKeyUtils.cs - private class RSAParametersWithPrivate - { - public byte[] D { get; set; } - public byte[] DP { get; set; } - public byte[] DQ { get; set; } - public byte[] Exponent { get; set; } - public byte[] InverseQ { get; set; } - public byte[] Modulus { get; set; } - public byte[] P { get; set; } - public byte[] Q { get; set; } - - public void SetParameters(RSAParameters p) - { - D = p.D; - DP = p.DP; - DQ = p.DQ; - Exponent = p.Exponent; - InverseQ = p.InverseQ; - Modulus = p.Modulus; - P = p.P; - Q = p.Q; - } - public RSAParameters ToRSAParameters() - { - return new RSAParameters() - { - D = this.D, - DP = this.DP, - DQ = this.DQ, - Exponent = this.Exponent, - InverseQ = this.InverseQ, - Modulus = this.Modulus, - P = this.P, - Q = this.Q - - }; - } - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Helpers/CustomerRolesHelper.cs b/Nop.Plugin.Api/Helpers/CustomerRolesHelper.cs index 7c08b03..9186179 100644 --- a/Nop.Plugin.Api/Helpers/CustomerRolesHelper.cs +++ b/Nop.Plugin.Api/Helpers/CustomerRolesHelper.cs @@ -1,20 +1,19 @@ -using Nop.Core.Caching; +using System.Collections.Generic; +using System.Linq; +using Nop.Core.Caching; using Nop.Core.Domain.Customers; using Nop.Services.Customers; -using System.Collections.Generic; -using System.Linq; namespace Nop.Plugin.Api.Helpers { public class CustomerRolesHelper : ICustomerRolesHelper { - private const string CUSTOMERROLES_ALL_BASE_KEY = "Nop.customerrole.all"; - private const string CUSTOMERROLES_ALL_KEY = CUSTOMERROLES_ALL_BASE_KEY + "-{0}"; + private const string CUSTOMERROLES_ALL_KEY = "Nop.customerrole.all-{0}"; + private readonly IStaticCacheManager _cacheManager; private readonly ICustomerService _customerService; - private readonly ICacheManager _cacheManager; - public CustomerRolesHelper(ICustomerService customerService, ICacheManager cacheManager) + public CustomerRolesHelper(ICustomerService customerService, IStaticCacheManager cacheManager) { _customerService = customerService; _cacheManager = cacheManager; @@ -22,9 +21,9 @@ public CustomerRolesHelper(ICustomerService customerService, ICacheManager cache public IList GetValidCustomerRoles(List roleIds) { - // This is needed because the caching messeup the entity framework context - // and when you try to send something TO the database it throws an exeption. - _cacheManager.RemoveByPrefix(CUSTOMERROLES_ALL_BASE_KEY); + // This is needed because the caching messes up the entity framework context + // and when you try to send something TO the database it throws an exception. + _cacheManager.RemoveByPrefix(CUSTOMERROLES_ALL_KEY); var allCustomerRoles = _customerService.GetAllCustomerRoles(true); var newCustomerRoles = new List(); @@ -48,5 +47,6 @@ public bool IsInRegisteredRole(IList customerRoles) { return customerRoles.FirstOrDefault(cr => cr.SystemName == NopCustomerDefaults.RegisteredRoleName) != null; } + } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Helpers/DTOHelper.cs b/Nop.Plugin.Api/Helpers/DTOHelper.cs index 395ab62..f0fde98 100644 --- a/Nop.Plugin.Api/Helpers/DTOHelper.cs +++ b/Nop.Plugin.Api/Helpers/DTOHelper.cs @@ -1,34 +1,35 @@ -using Nop.Core; +using System.Collections.Generic; +using System.Linq; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Directory; using Nop.Core.Domain.Localization; using Nop.Core.Domain.Media; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Stores; -using Nop.Plugin.Api.DTOs.Categories; -using Nop.Plugin.Api.DTOs.Customers; -using Nop.Plugin.Api.DTOs.Images; -using Nop.Plugin.Api.DTOs.Languages; -using Nop.Plugin.Api.DTOs.OrderItems; -using Nop.Plugin.Api.DTOs.Orders; -using Nop.Plugin.Api.DTOs.Manufacturers; -using Nop.Plugin.Api.DTOs.ProductAttributes; -using Nop.Plugin.Api.DTOs.Products; -using Nop.Plugin.Api.DTOs.ShoppingCarts; -using Nop.Plugin.Api.DTOs.SpecificationAttributes; -using Nop.Plugin.Api.DTOs.Stores; +using Nop.Plugin.Api.DTO.Categories; +using Nop.Plugin.Api.DTO.Images; +using Nop.Plugin.Api.DTO.Languages; +using Nop.Plugin.Api.DTO.Manufacturers; +using Nop.Plugin.Api.DTO.OrderItems; +using Nop.Plugin.Api.DTO.Orders; +using Nop.Plugin.Api.DTO.ProductAttributes; +using Nop.Plugin.Api.DTO.Products; +using Nop.Plugin.Api.DTO.ShoppingCarts; +using Nop.Plugin.Api.DTO.SpecificationAttributes; +using Nop.Plugin.Api.DTO.Stores; using Nop.Plugin.Api.MappingExtensions; using Nop.Plugin.Api.Services; +//using Nop.Plugin.Api.Services; using Nop.Services.Catalog; +using Nop.Services.Customers; using Nop.Services.Directory; +using Nop.Services.Discounts; using Nop.Services.Localization; using Nop.Services.Media; +using Nop.Services.Orders; using Nop.Services.Security; using Nop.Services.Seo; using Nop.Services.Stores; -using System; -using System.Collections.Generic; -using System.Linq; namespace Nop.Plugin.Api.Helpers { @@ -37,40 +38,52 @@ public class DTOHelper : IDTOHelper private readonly IAclService _aclService; private readonly ICurrencyService _currencyService; private readonly CurrencySettings _currencySettings; - private readonly ICustomerApiService _customerApiService; + private readonly ICustomerService _customerService; private readonly ILanguageService _languageService; private readonly ILocalizationService _localizationService; private readonly IPictureService _pictureService; - private readonly IProductAttributeConverter _productAttributeConverter; + private readonly IProductAttributeParser _productAttributeParser; private readonly IProductAttributeService _productAttributeService; private readonly IProductService _productService; private readonly IProductTagService _productTagService; + private readonly IDiscountService _discountService; + private readonly IManufacturerService _manufacturerService; + private readonly IOrderService _orderService; + private readonly IProductAttributeConverter _productAttributeConverter; + private readonly IShoppingCartService _shoppingCartService; + private readonly IProductService _productPictureService; private readonly IStoreMappingService _storeMappingService; private readonly IStoreService _storeService; private readonly IUrlRecordService _urlRecordService; - public DTOHelper(IProductService productService, + public DTOHelper( + IProductService productService, IAclService aclService, IStoreMappingService storeMappingService, IPictureService pictureService, IProductAttributeService productAttributeService, - ICustomerApiService customerApiService, - IProductAttributeConverter productAttributeConverter, + ICustomerService customerApiService, + IProductAttributeParser productAttributeParser, ILanguageService languageService, ICurrencyService currencyService, CurrencySettings currencySettings, IStoreService storeService, ILocalizationService localizationService, IUrlRecordService urlRecordService, - IProductTagService productTagService) + IProductTagService productTagService, + IDiscountService discountService, + IManufacturerService manufacturerService, + IOrderService orderService, + IProductAttributeConverter productAttributeConverter, + IShoppingCartService shoppingCartService) { _productService = productService; _aclService = aclService; _storeMappingService = storeMappingService; _pictureService = pictureService; _productAttributeService = productAttributeService; - _customerApiService = customerApiService; - _productAttributeConverter = productAttributeConverter; + _customerService = customerApiService; + _productAttributeParser = productAttributeParser; _languageService = languageService; _currencyService = currencyService; _currencySettings = currencySettings; @@ -78,27 +91,32 @@ public DTOHelper(IProductService productService, _localizationService = localizationService; _urlRecordService = urlRecordService; _productTagService = productTagService; + _discountService = discountService; + _manufacturerService = manufacturerService; + _orderService = orderService; + _productAttributeConverter = productAttributeConverter; + _shoppingCartService = shoppingCartService; } public ProductDto PrepareProductDTO(Product product) { var productDto = product.ToDto(); - - PrepareProductImages(product.ProductPictures, productDto); + var productPictures = _productService.GetProductPicturesByProductId(product.Id); + PrepareProductImages(productPictures, productDto); productDto.SeName = _urlRecordService.GetSeName(product); - productDto.DiscountIds = product.AppliedDiscounts.Select(discount => discount.Id).ToList(); - productDto.ManufacturerIds = product.ProductManufacturers.Select(pm => pm.ManufacturerId).ToList(); + productDto.DiscountIds = _discountService.GetAppliedDiscounts(product).Select(discount => discount.Id).ToList(); + productDto.ManufacturerIds = _manufacturerService.GetProductManufacturersByProductId(product.Id).Select(pm => pm.Id).ToList(); productDto.RoleIds = _aclService.GetAclRecords(product).Select(acl => acl.CustomerRoleId).ToList(); productDto.StoreIds = _storeMappingService.GetStoreMappings(product).Select(mapping => mapping.StoreId) - .ToList(); + .ToList(); productDto.Tags = _productTagService.GetAllProductTagsByProductId(product.Id).Select(tag => tag.Name) - .ToList(); + .ToList(); productDto.AssociatedProductIds = _productService.GetAssociatedProducts(product.Id, showHidden: true) - .Select(associatedProduct => associatedProduct.Id) - .ToList(); + .Select(associatedProduct => associatedProduct.Id) + .ToList(); var allLanguages = _languageService.GetAllLanguages(); @@ -107,10 +125,10 @@ public ProductDto PrepareProductDTO(Product product) foreach (var language in allLanguages) { var localizedNameDto = new LocalizedNameDto - { - LanguageId = language.Id, - LocalizedName = _localizationService.GetLocalized(product, x => x.Name, language.Id) - }; + { + LanguageId = language.Id, + LocalizedName = _localizationService.GetLocalized(product, x => x.Name, language.Id) + }; productDto.LocalizedNames.Add(localizedNameDto); } @@ -131,10 +149,10 @@ public CategoryDto PrepareCategoryDTO(Category category) } categoryDto.SeName = _urlRecordService.GetSeName(category); - categoryDto.DiscountIds = category.AppliedDiscounts.Select(discount => discount.Id).ToList(); + categoryDto.DiscountIds = _discountService.GetAppliedDiscounts(category).Select(discount => discount.Id).ToList(); categoryDto.RoleIds = _aclService.GetAclRecords(category).Select(acl => acl.CustomerRoleId).ToList(); categoryDto.StoreIds = _storeMappingService.GetStoreMappings(category).Select(mapping => mapping.StoreId) - .ToList(); + .ToList(); var allLanguages = _languageService.GetAllLanguages(); @@ -143,10 +161,10 @@ public CategoryDto PrepareCategoryDTO(Category category) foreach (var language in allLanguages) { var localizedNameDto = new LocalizedNameDto - { - LanguageId = language.Id, - LocalizedName = _localizationService.GetLocalized(category, x => x.Name, language.Id) - }; + { + LanguageId = language.Id, + LocalizedName = _localizationService.GetLocalized(category, x => x.Name, language.Id) + }; categoryDto.LocalizedNames.Add(localizedNameDto); } @@ -158,9 +176,9 @@ public OrderDto PrepareOrderDTO(Order order) { var orderDto = order.ToDto(); - orderDto.OrderItems = order.OrderItems.Select(PrepareOrderItemDTO).ToList(); + orderDto.OrderItems = _orderService.GetOrderItems(order.Id).Select(PrepareOrderItemDTO).ToList(); - var customerDto = _customerApiService.GetCustomerById(order.Customer.Id); + var customerDto = _customerService.GetCustomerById(order.CustomerId); if (customerDto != null) { @@ -173,8 +191,8 @@ public OrderDto PrepareOrderDTO(Order order) public ShoppingCartItemDto PrepareShoppingCartItemDTO(ShoppingCartItem shoppingCartItem) { var dto = shoppingCartItem.ToDto(); - dto.ProductDto = PrepareProductDTO(shoppingCartItem.Product); - dto.CustomerDto = shoppingCartItem.Customer.ToCustomerForShoppingCartItemDto(); + dto.ProductDto = PrepareProductDTO(_productService.GetProductById(shoppingCartItem.ProductId)); + dto.CustomerDto = _customerService.GetCustomerById(shoppingCartItem.CustomerId).ToCustomerForShoppingCartItemDto(); dto.Attributes = _productAttributeConverter.Parse(shoppingCartItem.AttributesXml); return dto; } @@ -182,7 +200,7 @@ public ShoppingCartItemDto PrepareShoppingCartItemDTO(ShoppingCartItem shoppingC public OrderItemDto PrepareOrderItemDTO(OrderItem orderItem) { var dto = orderItem.ToDto(); - dto.Product = PrepareProductDTO(orderItem.Product); + dto.Product = PrepareProductDTO(_productService.GetProductById(orderItem.ProductId)); dto.Attributes = _productAttributeConverter.Parse(orderItem.AttributesXml); return dto; } @@ -203,12 +221,12 @@ public StoreDto PrepareStoreDTO(Store store) return storeDto; } - public LanguageDto PrepateLanguageDto(Language language) + public LanguageDto PrepareLanguageDto(Language language) { var languageDto = language.ToDto(); languageDto.StoreIds = _storeMappingService.GetStoreMappings(language).Select(mapping => mapping.StoreId) - .ToList(); + .ToList(); if (languageDto.StoreIds.Count == 0) { @@ -223,6 +241,52 @@ public ProductAttributeDto PrepareProductAttributeDTO(ProductAttribute productAt return productAttribute.ToDto(); } + public ProductSpecificationAttributeDto PrepareProductSpecificationAttributeDto(ProductSpecificationAttribute productSpecificationAttribute) + { + return productSpecificationAttribute.ToDto(); + } + + public SpecificationAttributeDto PrepareSpecificationAttributeDto(SpecificationAttribute specificationAttribute) + { + return specificationAttribute.ToDto(); + } + + public ManufacturerDto PrepareManufacturerDto(Manufacturer manufacturer) + { + var manufacturerDto = manufacturer.ToDto(); + + var picture = _pictureService.GetPictureById(manufacturer.PictureId); + var imageDto = PrepareImageDto(picture); + + if (imageDto != null) + { + manufacturerDto.Image = imageDto; + } + + manufacturerDto.SeName = _urlRecordService.GetSeName(manufacturer); + manufacturerDto.DiscountIds = _discountService.GetAppliedDiscounts(manufacturer).Select(discount => discount.Id).ToList(); + manufacturerDto.RoleIds = _aclService.GetAclRecords(manufacturer).Select(acl => acl.CustomerRoleId).ToList(); + manufacturerDto.StoreIds = _storeMappingService.GetStoreMappings(manufacturer).Select(mapping => mapping.StoreId) + .ToList(); + + var allLanguages = _languageService.GetAllLanguages(); + + manufacturerDto.LocalizedNames = new List(); + + foreach (var language in allLanguages) + { + var localizedNameDto = new LocalizedNameDto + { + LanguageId = language.Id, + LocalizedName = _localizationService.GetLocalized(manufacturer, x => x.Name, language.Id) + }; + + manufacturerDto.LocalizedNames.Add(localizedNameDto); + } + + return manufacturerDto; + } + private void PrepareProductImages(IEnumerable productPictures, ProductDto productDto) { if (productDto.Images == null) @@ -233,18 +297,18 @@ private void PrepareProductImages(IEnumerable productPictures, P // Here we prepare the resulted dto image. foreach (var productPicture in productPictures) { - var imageDto = PrepareImageDto(productPicture.Picture); + var imageDto = PrepareImageDto(_pictureService.GetPictureById(productPicture.PictureId)); if (imageDto != null) { var productImageDto = new ImageMappingDto - { - Id = productPicture.Id, - PictureId = productPicture.PictureId, - Position = productPicture.DisplayOrder, - Src = imageDto.Src, - Attachment = imageDto.Attachment - }; + { + Id = productPicture.Id, + PictureId = productPicture.PictureId, + Position = productPicture.DisplayOrder, + Src = imageDto.Src, + Attachment = imageDto.Attachment + }; productDto.Images.Add(productImageDto); } @@ -260,16 +324,17 @@ protected ImageDto PrepareImageDto(Picture picture) // We don't use the image from the passed dto directly // because the picture may be passed with src and the result should only include the base64 format. image = new ImageDto - { - //Attachment = Convert.ToBase64String(picture.PictureBinary), - Src = _pictureService.GetPictureUrl(picture) - }; + { + //Attachment = Convert.ToBase64String(picture.PictureBinary), + //Src = _pictureService.GetPictureUrl(picture) + }; } return image; } - private void PrepareProductAttributes(IEnumerable productAttributeMappings, + private void PrepareProductAttributes( + IEnumerable productAttributeMappings, ProductDto productDto) { if (productDto.ProductAttributeMappings == null) @@ -297,25 +362,31 @@ private ProductAttributeMappingDto PrepareProductAttributeMappingDto( if (productAttributeMapping != null) { productAttributeMappingDto = new ProductAttributeMappingDto - { - Id = productAttributeMapping.Id, - ProductAttributeId = productAttributeMapping.ProductAttributeId, - ProductAttributeName = _productAttributeService - .GetProductAttributeById(productAttributeMapping.ProductAttributeId).Name, - TextPrompt = productAttributeMapping.TextPrompt, - DefaultValue = productAttributeMapping.DefaultValue, - AttributeControlTypeId = productAttributeMapping.AttributeControlTypeId, - DisplayOrder = productAttributeMapping.DisplayOrder, - IsRequired = productAttributeMapping.IsRequired, - ProductAttributeValues = productAttributeMapping.ProductAttributeValues - .Select(x => PrepareProductAttributeValueDto(x, productAttributeMapping.Product)).ToList() - }; + { + Id = productAttributeMapping.Id, + ProductAttributeId = productAttributeMapping.ProductAttributeId, + ProductAttributeName = _productAttributeService + .GetProductAttributeById(productAttributeMapping.ProductAttributeId).Name, + TextPrompt = productAttributeMapping.TextPrompt, + DefaultValue = productAttributeMapping.DefaultValue, + AttributeControlTypeId = productAttributeMapping.AttributeControlTypeId, + DisplayOrder = productAttributeMapping.DisplayOrder, + IsRequired = productAttributeMapping.IsRequired, + //TODO: Somnath + //ProductAttributeValues = _productAttributeService.GetProductAttributeValueById(productAttributeMapping.Id). + // .Select(x => + // PrepareProductAttributeValueDto(x, + // productAttributeMapping + // .Product)) + // .ToList() + }; } return productAttributeMappingDto; } - private ProductAttributeValueDto PrepareProductAttributeValueDto(ProductAttributeValue productAttributeValue, + private ProductAttributeValueDto PrepareProductAttributeValueDto( + ProductAttributeValue productAttributeValue, Product product) { ProductAttributeValueDto productAttributeValueDto = null; @@ -337,7 +408,7 @@ private ProductAttributeValueDto PrepareProductAttributeValueDto(ProductAttribut // This is needed since if you delete the product picture mapping from the nopCommerce administrationthe // then the attribute value is not updated and it will point to a picture that has been deleted var productPicture = - product.ProductPictures.FirstOrDefault(pp => pp.PictureId == productAttributeValue.PictureId); + _productPictureService.GetProductPicturesByProductId(product.Id).FirstOrDefault(pp => pp.PictureId == productAttributeValue.PictureId); if (productPicture != null) { productAttributeValueDto.ProductPictureId = productPicture.Id; @@ -347,8 +418,9 @@ private ProductAttributeValueDto PrepareProductAttributeValueDto(ProductAttribut return productAttributeValueDto; } - - private void PrepareProductAttributeCombinations(IEnumerable productAttributeCombinations, + + private void PrepareProductAttributeCombinations( + IEnumerable productAttributeCombinations, ProductDto productDto) { productDto.ProductAttributeCombinations = productDto.ProductAttributeCombinations ?? new List(); @@ -371,11 +443,13 @@ private ProductAttributeCombinationDto PrepareProductAttributeCombinationDto(Pro public void PrepareProductSpecificationAttributes(IEnumerable productSpecificationAttributes, ProductDto productDto) { if (productDto.ProductSpecificationAttributes == null) + { productDto.ProductSpecificationAttributes = new List(); + } foreach (var productSpecificationAttribute in productSpecificationAttributes) { - ProductSpecificationAttributeDto productSpecificationAttributeDto = PrepareProductSpecificationAttributeDto(productSpecificationAttribute); + var productSpecificationAttributeDto = PrepareProductSpecificationAttributeDto(productSpecificationAttribute); if (productSpecificationAttributeDto != null) { @@ -383,51 +457,5 @@ public void PrepareProductSpecificationAttributes(IEnumerable discount.Id).ToList(); - manufacturerDto.RoleIds = _aclService.GetAclRecords(manufacturer).Select(acl => acl.CustomerRoleId).ToList(); - manufacturerDto.StoreIds = _storeMappingService.GetStoreMappings(manufacturer).Select(mapping => mapping.StoreId) - .ToList(); - - var allLanguages = _languageService.GetAllLanguages(); - - manufacturerDto.LocalizedNames = new List(); - - foreach (var language in allLanguages) - { - var localizedNameDto = new LocalizedNameDto - { - LanguageId = language.Id, - LocalizedName = _localizationService.GetLocalized(manufacturer, x => x.Name, language.Id) - }; - - manufacturerDto.LocalizedNames.Add(localizedNameDto); - } - - return manufacturerDto; - } } -} \ No newline at end of file +} diff --git "a/Nop.Plugin.Api/Helpers/IConfigMan\320\260gerHelper.cs" "b/Nop.Plugin.Api/Helpers/IConfigMan\320\260gerHelper.cs" deleted file mode 100644 index b845f0b..0000000 --- "a/Nop.Plugin.Api/Helpers/IConfigMan\320\260gerHelper.cs" +++ /dev/null @@ -1,11 +0,0 @@ -using Nop.Core.Data; - -namespace Nop.Plugin.Api.Helpers -{ - public interface IConfigManagerHelper - { - void AddBindingRedirects(); - void AddConnectionString(); - DataSettings DataSettings { get; } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Helpers/ICustomerRolesHelper.cs b/Nop.Plugin.Api/Helpers/ICustomerRolesHelper.cs index 8ae6c93..29f5389 100644 --- a/Nop.Plugin.Api/Helpers/ICustomerRolesHelper.cs +++ b/Nop.Plugin.Api/Helpers/ICustomerRolesHelper.cs @@ -9,4 +9,4 @@ public interface ICustomerRolesHelper bool IsInGuestsRole(IList customerRoles); bool IsInRegisteredRole(IList customerRoles); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Helpers/IDTOHelper.cs b/Nop.Plugin.Api/Helpers/IDTOHelper.cs index 9f89596..eec52b7 100644 --- a/Nop.Plugin.Api/Helpers/IDTOHelper.cs +++ b/Nop.Plugin.Api/Helpers/IDTOHelper.cs @@ -2,16 +2,16 @@ using Nop.Core.Domain.Localization; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Stores; -using Nop.Plugin.Api.DTOs.Categories; -using Nop.Plugin.Api.DTOs.Languages; -using Nop.Plugin.Api.DTOs.Manufacturers; -using Nop.Plugin.Api.DTOs.OrderItems; -using Nop.Plugin.Api.DTOs.Orders; -using Nop.Plugin.Api.DTOs.ProductAttributes; -using Nop.Plugin.Api.DTOs.Products; -using Nop.Plugin.Api.DTOs.ShoppingCarts; -using Nop.Plugin.Api.DTOs.SpecificationAttributes; -using Nop.Plugin.Api.DTOs.Stores; +using Nop.Plugin.Api.DTO.Categories; +using Nop.Plugin.Api.DTO.Languages; +using Nop.Plugin.Api.DTO.Manufacturers; +using Nop.Plugin.Api.DTO.OrderItems; +using Nop.Plugin.Api.DTO.Orders; +using Nop.Plugin.Api.DTO.ProductAttributes; +using Nop.Plugin.Api.DTO.Products; +using Nop.Plugin.Api.DTO.ShoppingCarts; +using Nop.Plugin.Api.DTO.SpecificationAttributes; +using Nop.Plugin.Api.DTO.Stores; namespace Nop.Plugin.Api.Helpers { @@ -23,10 +23,10 @@ public interface IDTOHelper ShoppingCartItemDto PrepareShoppingCartItemDTO(ShoppingCartItem shoppingCartItem); OrderItemDto PrepareOrderItemDTO(OrderItem orderItem); StoreDto PrepareStoreDTO(Store store); - LanguageDto PrepateLanguageDto(Language language); + LanguageDto PrepareLanguageDto(Language language); ProductAttributeDto PrepareProductAttributeDTO(ProductAttribute productAttribute); ProductSpecificationAttributeDto PrepareProductSpecificationAttributeDto(ProductSpecificationAttribute productSpecificationAttribute); SpecificationAttributeDto PrepareSpecificationAttributeDto(SpecificationAttribute specificationAttribute); ManufacturerDto PrepareManufacturerDto(Manufacturer manufacturer); - } -} \ No newline at end of file + } +} diff --git a/Nop.Plugin.Api/Helpers/IJsonHelper.cs b/Nop.Plugin.Api/Helpers/IJsonHelper.cs index 256dae1..c8e807d 100644 --- a/Nop.Plugin.Api/Helpers/IJsonHelper.cs +++ b/Nop.Plugin.Api/Helpers/IJsonHelper.cs @@ -1,5 +1,4 @@ -using Microsoft.AspNetCore.Http; -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; namespace Nop.Plugin.Api.Helpers @@ -9,4 +8,4 @@ public interface IJsonHelper Dictionary GetRequestJsonDictionaryFromStream(Stream stream, bool rewindStream); string GetRootPropertyName() where T : class, new(); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Helpers/IMappingHelper.cs b/Nop.Plugin.Api/Helpers/IMappingHelper.cs index ddd8c0a..0c710a4 100644 --- a/Nop.Plugin.Api/Helpers/IMappingHelper.cs +++ b/Nop.Plugin.Api/Helpers/IMappingHelper.cs @@ -5,7 +5,10 @@ namespace Nop.Plugin.Api.Helpers { public interface IMappingHelper { - void SetValues(Dictionary propertyNameValuePairs, object objectToBeUpdated, Type objectToBeUpdatedType, Dictionary objectPropertyNameValuePairs, bool handleComplexTypeCollections = false); + void SetValues( + Dictionary propertyNameValuePairs, object objectToBeUpdated, Type objectToBeUpdatedType, + Dictionary objectPropertyNameValuePairs, bool handleComplexTypeCollections = false); + void Merge(object source, object destination); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Helpers/JTokenHelper.cs b/Nop.Plugin.Api/Helpers/JTokenHelper.cs index cf96693..9fe185c 100644 --- a/Nop.Plugin.Api/Helpers/JTokenHelper.cs +++ b/Nop.Plugin.Api/Helpers/JTokenHelper.cs @@ -1,8 +1,8 @@ -namespace Nop.Plugin.Api.Helpers -{ - using System.Collections.Generic; - using Newtonsoft.Json.Linq; +using System.Collections.Generic; +using Newtonsoft.Json.Linq; +namespace Nop.Plugin.Api.Helpers +{ public static class JTokenHelper { public static JToken RemoveEmptyChildrenAndFilterByFields(this JToken token, IList jsonFields, int level = 1) @@ -65,7 +65,7 @@ public static JToken RemoveEmptyChildrenAndFilterByFields(this JToken token, ILi private static bool IsEmptyOrDefault(this JToken token) { - return (token.Type == JTokenType.Array && !token.HasValues) || (token.Type == JTokenType.Object && !token.HasValues); + return token.Type == JTokenType.Array && !token.HasValues || token.Type == JTokenType.Object && !token.HasValues; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Helpers/JsonHelper.cs b/Nop.Plugin.Api/Helpers/JsonHelper.cs index 1fac1cb..5113d98 100644 --- a/Nop.Plugin.Api/Helpers/JsonHelper.cs +++ b/Nop.Plugin.Api/Helpers/JsonHelper.cs @@ -3,7 +3,6 @@ using System.IO; using System.Linq; using System.Text; -using Microsoft.AspNetCore.Http; using Newtonsoft.Json.Linq; using Nop.Services.Localization; @@ -11,15 +10,6 @@ namespace Nop.Plugin.Api.Helpers { public class JsonHelper : IJsonHelper { - - #region Private Fields - - private readonly ILocalizationService _localizationService; - - private readonly int _languageId; - - #endregion - #region Constructors public JsonHelper(ILanguageService languageService, ILocalizationService localizationService) @@ -27,11 +17,21 @@ public JsonHelper(ILanguageService languageService, ILocalizationService localiz _localizationService = localizationService; var language = languageService.GetAllLanguages().FirstOrDefault(); - _languageId = language != null ? language.Id : 0; + _languageId = language != null + ? language.Id + : 0; } #endregion + #region Private Fields + + private readonly ILocalizationService _localizationService; + + private readonly int _languageId; + + #endregion + #region Public Methods public Dictionary GetRequestJsonDictionaryFromStream(Stream stream, bool rewindStream) @@ -101,7 +101,7 @@ private object ToObject(JToken token) return token.Select(ToObject).ToList(); default: - return ((JValue)token).Value; + return ((JValue) token).Value; } } @@ -122,6 +122,5 @@ private string GetRequestBodyString(Stream stream, bool rewindStream) } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Helpers/MappingHelper.cs b/Nop.Plugin.Api/Helpers/MappingHelper.cs index 54aa952..af204c1 100644 --- a/Nop.Plugin.Api/Helpers/MappingHelper.cs +++ b/Nop.Plugin.Api/Helpers/MappingHelper.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.ComponentModel; +using System.Globalization; using System.Linq; using System.Reflection; using Nop.Core.Infrastructure; @@ -15,13 +16,14 @@ public class MappingHelper : IMappingHelper public void Merge(object source, object destination) { var sourcePropertyValuePairs = source.GetType() - .GetProperties() - .ToDictionary(property => property.Name, property => property.GetValue(source)); + .GetProperties() + .ToDictionary(property => property.Name, property => property.GetValue(source)); - SetValues(sourcePropertyValuePairs, destination, destination.GetType(),null); + SetValues(sourcePropertyValuePairs, destination, destination.GetType(), null); } - public void SetValues(Dictionary propertyNameValuePairs, object objectToBeUpdated, + public void SetValues( + Dictionary propertyNameValuePairs, object objectToBeUpdated, Type propertyType, Dictionary objectPropertyNameValuePairs, bool handleComplexTypeCollections = false) { objectPropertyNameValuePairs?.Add(objectToBeUpdated, propertyNameValuePairs); @@ -37,17 +39,19 @@ private void ConvertAndSetValueIfValid(object objectToBeUpdated, PropertyInfo ob { var converter = TypeDescriptor.GetConverter(objectProperty.PropertyType); - var propertyValueAsString = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}", propertyValue); + var propertyValueAsString = string.Format(CultureInfo.InvariantCulture, "{0}", propertyValue); - if (converter.IsValid(propertyValueAsString)) - { - var convertedValue = converter.ConvertFromInvariantString(propertyValueAsString); - - objectProperty.SetValue(objectToBeUpdated, convertedValue); - } + if (converter.IsValid(propertyValueAsString)) + { + var convertedValue = converter.ConvertFromInvariantString(propertyValueAsString); + + objectProperty.SetValue(objectToBeUpdated, convertedValue); + } } - private void SetValue(object objectToBeUpdated, KeyValuePair propertyNameValuePair, Dictionary objectPropertyNameValuePairs, bool handleComplexTypeCollections) + private void SetValue( + object objectToBeUpdated, KeyValuePair propertyNameValuePair, Dictionary objectPropertyNameValuePairs, + bool handleComplexTypeCollections) { var propertyName = propertyNameValuePair.Key; var propertyValue = propertyNameValuePair.Value; @@ -57,7 +61,7 @@ private void SetValue(object objectToBeUpdated, KeyValuePair pro if (propertyToUpdate != null) { // This case handles nested properties. - if (propertyValue != null && propertyValue is Dictionary) + if (propertyValue is Dictionary) { var valueToUpdate = propertyToUpdate.GetValue(objectToBeUpdated); @@ -65,8 +69,8 @@ private void SetValue(object objectToBeUpdated, KeyValuePair pro { // Check if there is registered factory for this type. var factoryType = typeof(IFactory<>); - var factoryTypeForCurrentProperty = factoryType.MakeGenericType(new Type[] { propertyToUpdate.PropertyType }); - var initializerFactory = ((NopEngine)EngineContext.Current).ServiceProvider.GetService(factoryTypeForCurrentProperty); + var factoryTypeForCurrentProperty = factoryType.MakeGenericType(propertyToUpdate.PropertyType); + var initializerFactory = ((NopEngine) EngineContext.Current).ServiceProvider.GetService(factoryTypeForCurrentProperty); if (initializerFactory != null) { @@ -83,16 +87,14 @@ private void SetValue(object objectToBeUpdated, KeyValuePair pro } // We need to use GetValue method to get the actual instance of the jsonProperty. objectProperty is the jsonProperty info. - SetValues((Dictionary)propertyValue, valueToUpdate, - propertyToUpdate.PropertyType, objectPropertyNameValuePairs); + SetValues((Dictionary) propertyValue, valueToUpdate, + propertyToUpdate.PropertyType, objectPropertyNameValuePairs); // We expect the nested properties to be classes which are refrence types. return; } - // This case hadles collections. - else if (propertyValue != null && propertyValue is ICollection) + // This case handles collections. + if (propertyValue is ICollection propertyValueAsCollection) { - var propertyValueAsCollection = propertyValue as ICollection; - var collectionElementsType = propertyToUpdate.PropertyType.GetGenericArguments()[0]; var collection = propertyToUpdate.GetValue(objectToBeUpdated); @@ -125,8 +127,8 @@ private void SetValue(object objectToBeUpdated, KeyValuePair pro if (handleComplexTypeCollections) { AddOrUpdateComplexItemInCollection(item as Dictionary, - collection as IList, - collectionElementsType, objectPropertyNameValuePairs, handleComplexTypeCollections); + collection as IList, + collectionElementsType, objectPropertyNameValuePairs, handleComplexTypeCollections); } } else @@ -138,7 +140,7 @@ private void SetValue(object objectToBeUpdated, KeyValuePair pro return; } - // This is where the new value is beeing set to the object jsonProperty using the SetValue function part of System.Reflection. + // This is where the new value is being set to the object jsonProperty using the SetValue function part of System.Reflection. if (propertyValue == null) { propertyToUpdate.SetValue(objectToBeUpdated, null); @@ -155,7 +157,7 @@ private void SetValue(object objectToBeUpdated, KeyValuePair pro } } - private void AddBaseItemInCollection(object newItem, IList collection, Type collectionElementsType) + private static void AddBaseItemInCollection(object newItem, IList collection, Type collectionElementsType) { var converter = TypeDescriptor.GetConverter(collectionElementsType); @@ -167,7 +169,8 @@ private void AddBaseItemInCollection(object newItem, IList collection, Type coll } } - private void AddOrUpdateComplexItemInCollection(Dictionary newProperties, IList collection, Type collectionElementsType, + private void AddOrUpdateComplexItemInCollection( + Dictionary newProperties, IList collection, Type collectionElementsType, Dictionary objectPropertyNameValuePairs, bool handleComplexTypeCollections) { if (newProperties.ContainsKey("Id")) @@ -181,9 +184,9 @@ private void AddOrUpdateComplexItemInCollection(Dictionary newPr foreach (var item in collection) { if (int.Parse(item.GetType() - .GetProperty("Id", BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) - .GetValue(item) - .ToString()) == id) + .GetProperty("Id", BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) + .GetValue(item) + .ToString()) == id) { itemToBeUpdated = item; break; @@ -208,7 +211,9 @@ private void AddOrUpdateComplexItemInCollection(Dictionary newPr } } - private void AddNewItemInCollection(Dictionary newProperties, IList collection, Type collectionElementsType,Dictionary objectPropertyNameValuePairs, bool handleComplexTypeCollections) + private void AddNewItemInCollection( + Dictionary newProperties, IList collection, Type collectionElementsType, Dictionary objectPropertyNameValuePairs, + bool handleComplexTypeCollections) { var newInstance = Activator.CreateInstance(collectionElementsType); @@ -221,7 +226,7 @@ private void AddNewItemInCollection(Dictionary newProperties, IL collection.Add(newInstance); } - private IList CreateEmptyList(Type listItemType) + private static IList CreateEmptyList(Type listItemType) { var listType = typeof(List<>); var constructedListType = listType.MakeGenericType(listItemType); @@ -231,7 +236,7 @@ private IList CreateEmptyList(Type listItemType) } // We need this method, because the default value of DateTime is not in the sql server DateTime range and we will get an exception if we use it. - private void SetEveryDatePropertyThatIsNotSetToDateTimeUtcNow(Dictionary newProperties, PropertyInfo[] properties) + private static void SetEveryDatePropertyThatIsNotSetToDateTimeUtcNow(Dictionary newProperties, PropertyInfo[] properties) { foreach (var property in properties) { @@ -258,4 +263,4 @@ private void SetEveryDatePropertyThatIsNotSetToDateTimeUtcNow(Dictionary { hasChanged = true; }; - - var runtime = appConfig.XPathSelectElement("configuration//runtime"); - - if (runtime == null) - { - runtime = new XElement("runtime"); - appConfig.XPathSelectElement("configuration")?.Add(runtime); - } - - // Required by Swagger - //AddAssemblyBinding(runtime, "Microsoft.AspNetCore.StaticFiles", "adb9793829ddae60", "0.0.0.0-2.0.0.0", "2.0.0.0"); - //AddAssemblyBinding(runtime, "Microsoft.Extensions.FileProviders.Embedded", "adb9793829ddae60", "0.0.0.0-2.0.0.0", "2.0.0.0"); - //AddAssemblyBinding(runtime, "Microsoft.AspNetCore.Mvc.Formatters.Json", "adb9793829ddae60", "0.0.0.0-2.0.0.0", "2.0.0.0"); - - // Required by WebHooks - AddAssemblyBinding(runtime, "Microsoft.AspNetCore.DataProtection.Abstractions", "adb9793829ddae60", "0.0.0.0-2.0.0.0", "2.0.0.0"); - - if (hasChanged) - { - // only save when changes have been made - try - { - appConfig.Save(nopWebAssemblyConfigLocation); - - //TODO: Upgrade 4.10 Check this! - //System.Configuration.ConfigurationManager.RefreshSection("runtime"); - } - catch (Exception) - { - // we should do nothing here as throwing an exception breaks nopCommerce. - // The right thing to do is to write a message in the Log that the user needs to provide Write access to Web.config - // but doing this will lead to many warnings in the Log added after each restart. - // So it is better to do nothing here. - //throw new NopException( - // "nopCommerce needs to be restarted due to a configuration change, but was unable to do so." + - // Environment.NewLine + - // "To prevent this issue in the future, a change to the web server configuration is required:" + - // Environment.NewLine + - // "- give the application write access to the 'web.config' file."); - } - } - } - } - - public DataSettings DataSettings { get; } - - public void AddConnectionString() - { - var hasChanged = false; - - // load web.config - XDocument appConfig = null; - - var nopWebAssemblyConfigLocation = $"{Assembly.GetEntryAssembly().Location}.config"; - - using (var fs = System.IO.File.OpenRead(nopWebAssemblyConfigLocation)) - { - appConfig = XDocument.Load(fs); - } - - if (appConfig != null) - { - appConfig.Changed += (o, e) => { hasChanged = true; }; - - var connectionStrings = appConfig.XPathSelectElement("configuration//connectionStrings"); - - if (connectionStrings == null) - { - var configuration = appConfig.XPathSelectElement("configuration"); - connectionStrings = new XElement("connectionStrings"); - configuration.Add(connectionStrings); - } - - var connectionStringFromNop = DataSettings.DataConnectionString; - - var element = appConfig.XPathSelectElement("configuration//connectionStrings//add[@name='MS_SqlStoreConnectionString']"); - - // create the connection string if not exists - if (element == null) - { - element = new XElement("add"); - element.SetAttributeValue("name", "MS_SqlStoreConnectionString"); - element.SetAttributeValue("connectionString", connectionStringFromNop); - element.SetAttributeValue("providerName", "System.Data.SqlClient"); - connectionStrings.Add(element); - } - else - { - // Check if the connection string is changed. - // If so update the connection string in the config. - var connectionStringInConfig = element.Attribute("connectionString").Value; - - if (!String.Equals(connectionStringFromNop, connectionStringInConfig, StringComparison.InvariantCultureIgnoreCase)) - { - element.SetAttributeValue("connectionString", connectionStringFromNop); - } - } - - if (hasChanged) - { - // only save when changes have been made - try - { - appConfig.Save(nopWebAssemblyConfigLocation); - - //TODO: Upgrade 4.1. Check this! - //System.Configuration.ConfigurationManager.RefreshSection("connectionStrings"); - } - catch - { - // we should do nothing here as throwing an exception breaks nopCommerce. - // The right thing to do is to write a message in the Log that the user needs to provide Write access to Web.config - // but doing this will lead to many warnings in the Log added after each restart. - // So it is better to do nothing here. - //throw new NopException( - // "nopCommerce needs to be restarted due to a configuration change, but was unable to do so." + - // Environment.NewLine + - // "To prevent this issue in the future, a change to the web server configuration is required:" + - // Environment.NewLine + - // "- give the application write access to the 'web.config' file."); - } - } - } - } - - private void AddAssemblyBinding(XElement runtime, string name, string publicToken, string oldVersion, string newVersion) - { - var xmlNamespaceManager = new XmlNamespaceManager(new NameTable()); - xmlNamespaceManager.AddNamespace("bind", "urn:schemas-microsoft-com:asm.v1"); - - var assemblyBindingElement = runtime.XPathSelectElement( - $"bind:assemblyBinding//bind:dependentAssembly//bind:assemblyIdentity[@name='{name}']", xmlNamespaceManager); - - // create the binding redirect if it does not exist - if (assemblyBindingElement == null) - { - assemblyBindingElement = XElement.Parse($@" - - - - - - - "); - - runtime.Add(assemblyBindingElement); - } - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Helpers/ReflectionHelper.cs b/Nop.Plugin.Api/Helpers/ReflectionHelper.cs index f593736..c9444c3 100644 --- a/Nop.Plugin.Api/Helpers/ReflectionHelper.cs +++ b/Nop.Plugin.Api/Helpers/ReflectionHelper.cs @@ -10,7 +10,7 @@ public static bool HasProperty(string propertyName, Type type) { return type.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) != null; } - + public static JsonObjectAttribute GetJsonObjectAttribute(Type objectType) { var jsonObject = objectType.GetCustomAttribute(typeof(JsonObjectAttribute)) as JsonObjectAttribute; @@ -19,6 +19,10 @@ public static JsonObjectAttribute GetJsonObjectAttribute(Type objectType) } public static Type GetGenericElementType(Type type) - => type.HasElementType ? type.GetElementType() : type.GetTypeInfo().GenericTypeArguments[0]; + { + return type.HasElementType + ? type.GetElementType() + : type.GetTypeInfo().GenericTypeArguments[0]; + } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeCallbackEndpoint.cs b/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeCallbackEndpoint.cs deleted file mode 100644 index 3fe5995..0000000 --- a/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeCallbackEndpoint.cs +++ /dev/null @@ -1,63 +0,0 @@ -namespace Nop.Plugin.Api.IdentityServer.Endpoints -{ - using System.Net; - using System.Threading.Tasks; - using IdentityServer4.Endpoints.Results; - using IdentityServer4.Extensions; - using IdentityServer4.Hosting; - using IdentityServer4.Models; - using IdentityServer4.ResponseHandling; - using IdentityServer4.Services; - using IdentityServer4.Stores; - using IdentityServer4.Validation; - using Microsoft.AspNetCore.Http; - - public class AuthorizeCallbackEndpoint : AuthorizeEndpointBase - { - private readonly IConsentMessageStore _consentResponseStore; - - public AuthorizeCallbackEndpoint( - IEventService events, - IAuthorizeRequestValidator validator, - IAuthorizeInteractionResponseGenerator interactionGenerator, - IAuthorizeResponseGenerator authorizeResponseGenerator, - IUserSession userSession, - IConsentMessageStore consentResponseStore) : base(events, userSession, validator, authorizeResponseGenerator, interactionGenerator) - { - _consentResponseStore = consentResponseStore; - } - - public override async Task ProcessAsync(HttpContext context) - { - if (context.Request.Method != "GET") - { - return new StatusCodeResult(HttpStatusCode.MethodNotAllowed); - } - - var parameters = context.Request.Query.AsNameValueCollection(); - - var user = await UserSession.GetUserAsync(); - var consentRequest = new ConsentRequest(parameters, user?.GetSubjectId()); - var consent = await _consentResponseStore.ReadAsync(consentRequest.Id); - - if (consent != null && consent.Data == null) - { - return await CreateErrorResultAsync("consent message is missing data"); - } - - try - { - var result = await ProcessAuthorizeRequestAsync(parameters, user, consent?.Data); - - return result; - } - finally - { - if (consent != null) - { - await _consentResponseStore.DeleteAsync(consentRequest.Id); - } - } - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeEndpoint.cs b/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeEndpoint.cs deleted file mode 100644 index b331710..0000000 --- a/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeEndpoint.cs +++ /dev/null @@ -1,53 +0,0 @@ -namespace Nop.Plugin.Api.IdentityServer.Endpoints -{ - using System.Collections.Specialized; - using System.Net; - using System.Threading.Tasks; - using IdentityServer4.Endpoints.Results; - using IdentityServer4.Hosting; - using IdentityServer4.ResponseHandling; - using IdentityServer4.Services; - using IdentityServer4.Validation; - using Microsoft.AspNetCore.Http; - - public class AuthorizeEndpoint : AuthorizeEndpointBase - { - public AuthorizeEndpoint( - IEventService events, - IAuthorizeRequestValidator validator, - IAuthorizeInteractionResponseGenerator interactionGenerator, - IAuthorizeResponseGenerator authorizeResponseGenerator, - IUserSession userSession) - : base(events, userSession, validator, authorizeResponseGenerator, interactionGenerator) - { - } - - public override async Task ProcessAsync(HttpContext context) - { - NameValueCollection values; - - if (context.Request.Method == "GET") - { - values = context.Request.Query.AsNameValueCollection(); - } - else if (context.Request.Method == "POST") - { - if (!context.Request.HasFormContentType) - { - return new StatusCodeResult(HttpStatusCode.UnsupportedMediaType); - } - - values = context.Request.Form.AsNameValueCollection(); - } - else - { - return new StatusCodeResult(HttpStatusCode.MethodNotAllowed); - } - - var user = await UserSession.GetUserAsync(); - var result = await ProcessAuthorizeRequestAsync(values, user, null); - - return result; - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeEndpointBase.cs b/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeEndpointBase.cs deleted file mode 100644 index 35fd26e..0000000 --- a/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeEndpointBase.cs +++ /dev/null @@ -1,125 +0,0 @@ -namespace Nop.Plugin.Api.IdentityServer.Endpoints -{ - using System.Collections.Specialized; - using System.Security.Claims; - using System.Threading.Tasks; - using IdentityModel; - using IdentityServer4.Endpoints.Results; - using IdentityServer4.Events; - using IdentityServer4.Hosting; - using IdentityServer4.Models; - using IdentityServer4.ResponseHandling; - using IdentityServer4.Services; - using IdentityServer4.Validation; - using Microsoft.AspNetCore.Http; - - public abstract class AuthorizeEndpointBase : IEndpointHandler - { - private readonly IEventService _events; - private readonly IAuthorizeRequestValidator _validator; - private readonly IAuthorizeResponseGenerator _authorizeResponseGenerator; - private readonly IAuthorizeInteractionResponseGenerator _interactionGenerator; - - protected IUserSession UserSession { get; private set; } - - protected AuthorizeEndpointBase(IEventService events, IUserSession userSession, IAuthorizeRequestValidator validator, IAuthorizeResponseGenerator authorizeResponseGenerator, IAuthorizeInteractionResponseGenerator interactionGenerator) - { - _events = events; - UserSession = userSession; - _validator = validator; - _authorizeResponseGenerator = authorizeResponseGenerator; - _interactionGenerator = interactionGenerator; - } - - protected async Task CreateErrorResultAsync( - string logMessage, - ValidatedAuthorizeRequest request = null, - string error = OidcConstants.AuthorizeErrors.ServerError, - string errorDescription = null) - { - await RaiseFailureEventAsync(request, error, errorDescription); - - return new AuthorizeResult(new AuthorizeResponse - { - Request = request, - Error = error, - ErrorDescription = errorDescription - }); - } - - public abstract Task ProcessAsync(HttpContext context); - - protected Task RaiseResponseEventAsync(AuthorizeResponse response) - { - if (!response.IsError) - { - return _events.RaiseAsync(new TokenIssuedSuccessEvent(response)); - } - else - { - return RaiseFailureEventAsync(response.Request, response.Error, response.ErrorDescription); - } - } - - protected Task RaiseFailureEventAsync(ValidatedAuthorizeRequest request, string error, string errorDescription) - { - return _events.RaiseAsync(new TokenIssuedFailureEvent(request, error, errorDescription)); - } - - protected async Task ProcessAuthorizeRequestAsync(NameValueCollection parameters, ClaimsPrincipal user, ConsentResponse consent) - { - // validate request - var result = await _validator.ValidateAsync(parameters, user); - if (result.IsError) - { - return await CreateErrorResultAsync( - "Request validation failed", - result.ValidatedRequest, - result.Error, - result.ErrorDescription); - } - - var request = result.ValidatedRequest; - - // determine user interaction - var interactionResult = await _interactionGenerator.ProcessInteractionAsync(request, consent); - if (interactionResult.IsError) - { - return await CreateErrorResultAsync("Interaction generator error", request, interactionResult.Error); - } - if (interactionResult.IsLogin) - { - return new LoginPageResult(request); - } - if (interactionResult.IsConsent) - { - return new ConsentPageResult(request); - } - if (interactionResult.IsRedirect) - { - return new CustomRedirectResult(request, interactionResult.RedirectUrl); - } - - var response = await _authorizeResponseGenerator.CreateResponseAsync(request); - - await RaiseResponseEventAsync(response); - - return new AuthorizeResult(response); - } - - protected async Task CreateErrorResultAsync( - ValidatedAuthorizeRequest request = null, - string error = OidcConstants.AuthorizeErrors.ServerError, - string errorDescription = null) - { - await RaiseFailureEventAsync(request, error, errorDescription); - - return new AuthorizeResult(new AuthorizeResponse - { - Request = request, - Error = error, - ErrorDescription = errorDescription - }); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeResponseExtensions.cs b/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeResponseExtensions.cs deleted file mode 100644 index c4ae808..0000000 --- a/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeResponseExtensions.cs +++ /dev/null @@ -1,62 +0,0 @@ -namespace Nop.Plugin.Api.IdentityServer.Endpoints -{ - using IdentityServer4.ResponseHandling; - using System.Collections.Specialized; - using Nop.Plugin.Api.IdentityServer.Extensions; - - public static class AuthorizeResponseExtensions - { - public static NameValueCollection ToNameValueCollection(this AuthorizeResponse response) - { - var collection = new NameValueCollection(); - - if (response.IsError) - { - if (response.Error.IsPresent()) - { - collection.Add("error", response.Error); - } - if (response.ErrorDescription.IsPresent()) - { - collection.Add("error_description", response.ErrorDescription); - } - } - else - { - if (response.Code.IsPresent()) - { - collection.Add("code", response.Code); - } - - if (response.IdentityToken.IsPresent()) - { - collection.Add("id_token", response.IdentityToken); - } - - if (response.AccessToken.IsPresent()) - { - collection.Add("access_token", response.AccessToken); - collection.Add("token_type", "Bearer"); - collection.Add("expires_in", response.AccessTokenLifetime.ToString()); - } - - if (response.Scope.IsPresent()) - { - collection.Add("scope", response.Scope); - } - } - - if (response.State.IsPresent()) - { - collection.Add("state", response.State); - } - - if (response.SessionState.IsPresent()) - { - collection.Add("session_state", response.SessionState); - } - - return collection; - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeResult.cs b/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeResult.cs deleted file mode 100644 index 86a823e..0000000 --- a/Nop.Plugin.Api/IdentityServer/Endpoints/AuthorizeResult.cs +++ /dev/null @@ -1,198 +0,0 @@ -namespace Nop.Plugin.Api.IdentityServer.Endpoints -{ - using System; - using System.Threading.Tasks; - using IdentityModel; - using IdentityServer4.Configuration; - using IdentityServer4.Hosting; - using IdentityServer4.Models; - using IdentityServer4.ResponseHandling; - using IdentityServer4.Services; - using IdentityServer4.Stores; - using Microsoft.AspNetCore.Authentication; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.DependencyInjection; - using Nop.Plugin.Api.IdentityServer.Extensions; - - public class AuthorizeResult : IEndpointResult - { - public AuthorizeResponse Response { get; } - - public AuthorizeResult(AuthorizeResponse response) - { - Response = response ?? throw new ArgumentNullException(nameof(response)); - } - - internal AuthorizeResult( - AuthorizeResponse response, - IdentityServerOptions options, - IUserSession userSession, - IMessageStore errorMessageStore, - ISystemClock clock) - : this(response) - { - _options = options; - _userSession = userSession; - _errorMessageStore = errorMessageStore; - _clock = clock; - } - - private IdentityServerOptions _options; - private IUserSession _userSession; - private IMessageStore _errorMessageStore; - private ISystemClock _clock; - - private void Init(HttpContext context) - { - _options = _options ?? context.RequestServices.GetRequiredService(); - _userSession = _userSession ?? context.RequestServices.GetRequiredService(); - _errorMessageStore = _errorMessageStore ?? context.RequestServices.GetRequiredService>(); - _clock = _clock ?? context.RequestServices.GetRequiredService(); - } - - public async Task ExecuteAsync(HttpContext context) - { - Init(context); - - if (Response.IsError) - { - await ProcessErrorAsync(context); - } - else - { - await ProcessResponseAsync(context); - } - } - - private async Task ProcessErrorAsync(HttpContext context) - { - // these are the conditions where we can send a response - // back directly to the client, otherwise we're only showing the error UI - var isPromptNoneError = Response.Error == OidcConstants.AuthorizeErrors.AccountSelectionRequired || - Response.Error == OidcConstants.AuthorizeErrors.LoginRequired || - Response.Error == OidcConstants.AuthorizeErrors.ConsentRequired || - Response.Error == OidcConstants.AuthorizeErrors.InteractionRequired; - - if (Response.Error == OidcConstants.AuthorizeErrors.AccessDenied || - (isPromptNoneError && Response.Request?.PromptMode == OidcConstants.PromptModes.None) - ) - { - // this scenario we can return back to the client - await ProcessResponseAsync(context); - } - else - { - // we now know we must show error page - await RedirectToErrorPageAsync(context); - } - } - - protected async Task ProcessResponseAsync(HttpContext context) - { - if (!Response.IsError) - { - // success response -- track client authorization for sign-out - //_logger.LogDebug("Adding client {0} to client list cookie for subject {1}", request.ClientId, request.Subject.GetSubjectId()); - await _userSession.AddClientIdAsync(Response.Request.ClientId); - } - - await RenderAuthorizeResponseAsync(context); - } - - private async Task RenderAuthorizeResponseAsync(HttpContext context) - { - if (Response.Request.ResponseMode == OidcConstants.ResponseModes.Query || - Response.Request.ResponseMode == OidcConstants.ResponseModes.Fragment) - { - context.Response.SetNoCache(); - context.Response.Redirect(BuildRedirectUri()); - } - else if (Response.Request.ResponseMode == OidcConstants.ResponseModes.FormPost) - { - context.Response.SetNoCache(); - AddSecurityHeaders(context); - await context.Response.WriteHtmlAsync(GetFormPostHtml()); - } - else - { - //_logger.LogError("Unsupported response mode."); - throw new InvalidOperationException("Unsupported response mode"); - } - } - - private void AddSecurityHeaders(HttpContext context) - { - var formOrigin = Response.Request.RedirectUri.GetOrigin(); - var csp = $"default-src 'none'; frame-ancestors {formOrigin}; form-action {formOrigin}; script-src 'sha256-VuNUSJ59bpCpw62HM2JG/hCyGiqoPN3NqGvNXQPU+rY='; "; - - if (!context.Response.Headers.ContainsKey("Content-Security-Policy")) - { - context.Response.Headers.Add("Content-Security-Policy", csp); - } - - if (!context.Response.Headers.ContainsKey("X-Content-Security-Policy")) - { - context.Response.Headers.Add("X-Content-Security-Policy", csp); - } - - var referrer_policy = "no-referrer"; - if (!context.Response.Headers.ContainsKey("Referrer-Policy")) - { - context.Response.Headers.Add("Referrer-Policy", referrer_policy); - } - } - - private string BuildRedirectUri() - { - var uri = Response.RedirectUri; - var query = Response.ToNameValueCollection().ToQueryString(); - - if (Response.Request.ResponseMode == OidcConstants.ResponseModes.Query) - { - uri = uri.AddQueryString(query); - } - else - { - uri = uri.AddHashFragment(query); - } - - if (Response.IsError && !uri.Contains("#")) - { - // https://tools.ietf.org/html/draft-bradley-oauth-open-redirector-00 - uri += "#_=_"; - } - - return uri; - } - - private const string FormPostHtml = "
{body}
"; - - private string GetFormPostHtml() - { - var html = FormPostHtml; - - html = html.Replace("{uri}", Response.Request.RedirectUri); - html = html.Replace("{body}", Response.ToNameValueCollection().ToFormPost()); - - return html; - } - - private async Task RedirectToErrorPageAsync(HttpContext context) - { - var errorModel = new ErrorMessage - { - RequestId = context.TraceIdentifier, - Error = Response.Error, - ErrorDescription = Response.ErrorDescription - }; - - var message = new Message(errorModel, _clock.UtcNow.UtcDateTime); - var id = await _errorMessageStore.WriteAsync(message); - - var errorUrl = _options.UserInteraction.ErrorUrl; - - var url = errorUrl.AddQueryString(_options.UserInteraction.ErrorIdParameter, id); - context.Response.RedirectToAbsoluteUrl(url); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/IdentityServer/Endpoints/TokenEndpoint.cs b/Nop.Plugin.Api/IdentityServer/Endpoints/TokenEndpoint.cs deleted file mode 100644 index 415fa14..0000000 --- a/Nop.Plugin.Api/IdentityServer/Endpoints/TokenEndpoint.cs +++ /dev/null @@ -1,97 +0,0 @@ -namespace Nop.Plugin.Api.IdentityServer.Endpoints -{ - using System.Collections.Generic; - using System.Threading.Tasks; - using IdentityModel; - using IdentityServer4.Events; - using IdentityServer4.Hosting; - using IdentityServer4.ResponseHandling; - using IdentityServer4.Services; - using IdentityServer4.Validation; - using Microsoft.AspNetCore.Http; - - public class TokenEndpoint : IEndpointHandler - { - private readonly IClientSecretValidator _clientValidator; - private readonly ITokenRequestValidator _requestValidator; - private readonly ITokenResponseGenerator _responseGenerator; - private readonly IEventService _events; - - /// - /// Initializes a new instance of the class. - /// - /// The client validator. - /// The request validator. - /// The response generator. - /// The events. - /// The logger. - public TokenEndpoint( - IClientSecretValidator clientValidator, - ITokenRequestValidator requestValidator, - ITokenResponseGenerator responseGenerator, - IEventService events) - { - _clientValidator = clientValidator; - _requestValidator = requestValidator; - _responseGenerator = responseGenerator; - _events = events; - } - - /// - /// Processes the request. - /// - /// The HTTP context. - /// - public async Task ProcessAsync(HttpContext context) - { - // validate HTTP - if (context.Request.Method != "POST" || !context.Request.HasFormContentType) - { - return Error(OidcConstants.TokenErrors.InvalidRequest); - } - - return await ProcessTokenRequestAsync(context); - } - - private async Task ProcessTokenRequestAsync(HttpContext context) - { - // validate client - var clientResult = await _clientValidator.ValidateAsync(context); - - if (clientResult.Client == null) - { - return Error(OidcConstants.TokenErrors.InvalidClient); - } - - // validate request - var form = (await context.Request.ReadFormAsync()).AsNameValueCollection(); - var requestResult = await _requestValidator.ValidateRequestAsync(form, clientResult); - - if (requestResult.IsError) - { - await _events.RaiseAsync(new TokenIssuedFailureEvent(requestResult)); - return Error(requestResult.Error, requestResult.ErrorDescription, requestResult.CustomResponse); - } - - // create response - var response = await _responseGenerator.ProcessAsync(requestResult); - - await _events.RaiseAsync(new TokenIssuedSuccessEvent(response, requestResult)); - - // return result - return new TokenResult(response); - } - - private TokenErrorResult Error(string error, string errorDescription = null, Dictionary custom = null) - { - var response = new TokenErrorResponse - { - Error = error, - ErrorDescription = errorDescription, - Custom = custom - }; - - return new TokenErrorResult(response); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/IdentityServer/Endpoints/TokenErrorResult.cs b/Nop.Plugin.Api/IdentityServer/Endpoints/TokenErrorResult.cs deleted file mode 100644 index 42a2c17..0000000 --- a/Nop.Plugin.Api/IdentityServer/Endpoints/TokenErrorResult.cs +++ /dev/null @@ -1,53 +0,0 @@ -namespace Nop.Plugin.Api.IdentityServer.Endpoints -{ - using System; - using System.Threading.Tasks; - using IdentityServer4.Extensions; - using IdentityServer4.Hosting; - using IdentityServer4.ResponseHandling; - using Microsoft.AspNetCore.Http; - using Nop.Plugin.Api.IdentityServer.Extensions; - using Nop.Plugin.Api.IdentityServer.Infrastructure; - - public class TokenErrorResult : IEndpointResult - { - public TokenErrorResponse Response { get; } - - public TokenErrorResult(TokenErrorResponse error) - { - if (error.Error.IsMissing()) throw new ArgumentNullException("Error must be set", nameof(error.Error)); - - Response = error; - } - - public async Task ExecuteAsync(HttpContext context) - { - context.Response.StatusCode = 400; - context.Response.SetNoCache(); - - var dto = new ResultDto - { - error = Response.Error, - error_description = Response.ErrorDescription - }; - - if (Response.Custom.IsNullOrEmpty()) - { - await context.Response.WriteJsonAsync(dto); - } - else - { - var jobject = ObjectSerializer.ToJObject(dto); - jobject.AddDictionary(Response.Custom); - - await context.Response.WriteJsonAsync(jobject); - } - } - - internal class ResultDto - { - public string error { get; set; } - public string error_description { get; set; } - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/IdentityServer/Endpoints/TokenResult.cs b/Nop.Plugin.Api/IdentityServer/Endpoints/TokenResult.cs deleted file mode 100644 index 3598a12..0000000 --- a/Nop.Plugin.Api/IdentityServer/Endpoints/TokenResult.cs +++ /dev/null @@ -1,58 +0,0 @@ -namespace Nop.Plugin.Api.IdentityServer.Endpoints -{ - using System; - using System.Threading.Tasks; - using IdentityModel; - using IdentityServer4.Extensions; - using IdentityServer4.Hosting; - using IdentityServer4.ResponseHandling; - using Microsoft.AspNetCore.Http; - using Nop.Plugin.Api.IdentityServer.Infrastructure; - - public class TokenResult : IEndpointResult - { - public TokenResponse Response { get; set; } - - public TokenResult(TokenResponse response) - { - if (response == null) throw new ArgumentNullException(nameof(response)); - - Response = response; - } - - public async Task ExecuteAsync(HttpContext context) - { - context.Response.SetNoCache(); - - var dto = new ResultDto - { - id_token = Response.IdentityToken, - access_token = Response.AccessToken, - refresh_token = Response.RefreshToken, - expires_in = Response.AccessTokenLifetime, - token_type = OidcConstants.TokenResponse.BearerTokenType - }; - - if (Response.Custom.IsNullOrEmpty()) - { - await context.Response.WriteJsonAsync(dto); - } - else - { - var jobject = ObjectSerializer.ToJObject(dto); - jobject.AddDictionary(Response.Custom); - - await context.Response.WriteJsonAsync(jobject); - } - } - - internal class ResultDto - { - public string id_token { get; set; } - public string access_token { get; set; } - public int expires_in { get; set; } - public string token_type { get; set; } - public string refresh_token { get; set; } - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/IdentityServer/Extensions/NameValueCollectionExtensions.cs b/Nop.Plugin.Api/IdentityServer/Extensions/NameValueCollectionExtensions.cs deleted file mode 100644 index 9452d0a..0000000 --- a/Nop.Plugin.Api/IdentityServer/Extensions/NameValueCollectionExtensions.cs +++ /dev/null @@ -1,143 +0,0 @@ -namespace Nop.Plugin.Api.IdentityServer.Extensions -{ - using System; - using System.Collections.Generic; - using System.Collections.Specialized; - using System.Linq; - using System.Text; - using System.Text.Encodings.Web; - - public static class NameValueCollectionExtensions - { - public static string ToQueryString(this NameValueCollection collection) - { - if (collection.Count == 0) - { - return String.Empty; - } - - var builder = new StringBuilder(128); - var first = true; - foreach (string name in collection) - { - var values = collection.GetValues(name); - if (values == null || values.Length == 0) - { - first = AppendNameValuePair(builder, first, true, name, String.Empty); - } - else - { - foreach (var value in values) - { - first = AppendNameValuePair(builder, first, true, name, value); - } - } - } - - return builder.ToString(); - } - - public static string ToFormPost(this NameValueCollection collection) - { - var builder = new StringBuilder(128); - const string inputFieldFormat = "\n"; - - foreach (string name in collection) - { - var values = collection.GetValues(name); - var value = values.First(); - value = HtmlEncoder.Default.Encode(value); - builder.AppendFormat(inputFieldFormat, name, value); - } - - return builder.ToString(); - } - - public static NameValueCollection ToNameValueCollection(this Dictionary data) - { - var result = new NameValueCollection(); - - if (data == null || data.Count == 0) - { - return result; - } - - foreach (var name in data.Keys) - { - var value = data[name]; - if (value != null) - { - result.Add(name, value); - } - } - - return result; - } - - public static Dictionary ToDictionary(this NameValueCollection collection) - { - return collection.ToScrubbedDictionary(); - } - - public static Dictionary ToScrubbedDictionary(this NameValueCollection collection, params string[] nameFilter) - { - var dict = new Dictionary(); - - if (collection == null || collection.Count == 0) - { - return dict; - } - - foreach (string name in collection) - { - var value = collection.Get(name); - if (value != null) - { - if (nameFilter.Contains(name)) - { - value = "***REDACTED***"; - } - dict.Add(name, value); - } - } - - return dict; - } - - internal static string ConvertFormUrlEncodedSpacesToUrlEncodedSpaces(string str) - { - if ((str != null) && (str.IndexOf('+') >= 0)) - { - str = str.Replace("+", "%20"); - } - return str; - } - - private static bool AppendNameValuePair(StringBuilder builder, bool first, bool urlEncode, string name, string value) - { - var effectiveName = name ?? String.Empty; - var encodedName = urlEncode ? UrlEncoder.Default.Encode(effectiveName) : effectiveName; - - var effectiveValue = value ?? String.Empty; - var encodedValue = urlEncode ? UrlEncoder.Default.Encode(effectiveValue) : effectiveValue; - encodedValue = ConvertFormUrlEncodedSpacesToUrlEncodedSpaces(encodedValue); - - if (first) - { - first = false; - } - else - { - builder.Append("&"); - } - - builder.Append(encodedName); - if (!String.IsNullOrEmpty(encodedValue)) - { - builder.Append("="); - builder.Append(encodedValue); - } - return first; - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/IdentityServer/Extensions/StringsExtensions.cs b/Nop.Plugin.Api/IdentityServer/Extensions/StringsExtensions.cs deleted file mode 100644 index 8875385..0000000 --- a/Nop.Plugin.Api/IdentityServer/Extensions/StringsExtensions.cs +++ /dev/null @@ -1,222 +0,0 @@ -namespace Nop.Plugin.Api.IdentityServer.Extensions -{ - using System; - using System.Collections.Generic; - using System.Collections.Specialized; - using System.Diagnostics; - using System.Linq; - using System.Text; - using System.Text.Encodings.Web; - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.WebUtilities; - - internal static class StringExtensions - { - [DebuggerStepThrough] - public static string ToSpaceSeparatedString(this IEnumerable list) - { - if (list == null) - { - return ""; - } - - var sb = new StringBuilder(100); - - foreach (var element in list) - { - sb.Append(element + " "); - } - - return sb.ToString().Trim(); - } - - [DebuggerStepThrough] - public static IEnumerable FromSpaceSeparatedString(this string input) - { - input = input.Trim(); - return input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); - } - - public static List ParseScopesString(this string scopes) - { - if (scopes.IsMissing()) - { - return null; - } - - scopes = scopes.Trim(); - var parsedScopes = scopes.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList(); - - if (parsedScopes.Any()) - { - parsedScopes.Sort(); - return parsedScopes; - } - - return null; - } - - [DebuggerStepThrough] - public static bool IsMissing(this string value) - { - return string.IsNullOrWhiteSpace(value); - } - - [DebuggerStepThrough] - public static bool IsMissingOrTooLong(this string value, int maxLength) - { - if (string.IsNullOrWhiteSpace(value)) - { - return true; - } - if (value.Length > maxLength) - { - return true; - } - - return false; - } - - [DebuggerStepThrough] - public static bool IsPresent(this string value) - { - return !string.IsNullOrWhiteSpace(value); - } - - [DebuggerStepThrough] - public static string EnsureLeadingSlash(this string url) - { - if (!url.StartsWith("/")) - { - return "/" + url; - } - - return url; - } - - [DebuggerStepThrough] - public static string EnsureTrailingSlash(this string url) - { - if (!url.EndsWith("/")) - { - return url + "/"; - } - - return url; - } - - [DebuggerStepThrough] - public static string RemoveLeadingSlash(this string url) - { - if (url != null && url.StartsWith("/")) - { - url = url.Substring(1); - } - - return url; - } - - [DebuggerStepThrough] - public static string RemoveTrailingSlash(this string url) - { - if (url != null && url.EndsWith("/")) - { - url = url.Substring(0, url.Length - 1); - } - - return url; - } - - [DebuggerStepThrough] - public static string CleanUrlPath(this string url) - { - if (String.IsNullOrWhiteSpace(url)) url = "/"; - - if (url != "/" && url.EndsWith("/")) - { - url = url.Substring(0, url.Length - 1); - } - - return url; - } - - [DebuggerStepThrough] - public static bool IsLocalUrl(this string url) - { - return - !String.IsNullOrEmpty(url) && - - // Allows "/" or "/foo" but not "//" or "/\". - ((url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'))) || - - // Allows "~/" or "~/foo". - (url.Length > 1 && url[0] == '~' && url[1] == '/')); - } - - [DebuggerStepThrough] - public static string AddQueryString(this string url, string query) - { - if (!url.Contains("?")) - { - url += "?"; - } - else if (!url.EndsWith("&")) - { - url += "&"; - } - - return url + query; - } - - [DebuggerStepThrough] - public static string AddQueryString(this string url, string name, string value) - { - return url.AddQueryString(name + "=" + UrlEncoder.Default.Encode(value)); - } - - [DebuggerStepThrough] - public static string AddHashFragment(this string url, string query) - { - if (!url.Contains("#")) - { - url += "#"; - } - - return url + query; - } - - [DebuggerStepThrough] - public static NameValueCollection ReadQueryStringAsNameValueCollection(this string url) - { - if (url != null) - { - var idx = url.IndexOf('?'); - if (idx >= 0) - { - url = url.Substring(idx + 1); - } - var query = QueryHelpers.ParseNullableQuery(url); - if (query != null) - { - return query.AsNameValueCollection(); - } - } - - return new NameValueCollection(); - } - - public static string GetOrigin(this string url) - { - if (url != null) - { - var uri = new Uri(url); - if (uri.Scheme == "http" || uri.Scheme == "https") - { - return $"{uri.Scheme}://{uri.Authority}"; - } - } - - return null; - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/IdentityServer/Generators/CustomAuthorizeInteractionResponseGenerator.cs b/Nop.Plugin.Api/IdentityServer/Generators/CustomAuthorizeInteractionResponseGenerator.cs deleted file mode 100644 index 34cfb7b..0000000 --- a/Nop.Plugin.Api/IdentityServer/Generators/CustomAuthorizeInteractionResponseGenerator.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. -// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. - - -namespace Nop.Plugin.Api.IdentityServer.Generators -{ - using System; - using System.Threading.Tasks; - using IdentityModel; - using IdentityServer4; - using IdentityServer4.Extensions; - using IdentityServer4.Models; - using IdentityServer4.ResponseHandling; - using IdentityServer4.Services; - using IdentityServer4.Validation; - using Microsoft.AspNetCore.Authentication; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Logging; - using IAuthenticationService = Microsoft.AspNetCore.Authentication.IAuthenticationService; - - public class NopApiAuthorizeInteractionResponseGenerator : IAuthorizeInteractionResponseGenerator - { - /// - /// The logger. - /// - protected readonly ILogger Logger; - - /// - /// The consent service. - /// - protected readonly IConsentService Consent; - - /// - /// The profile service. - /// - protected readonly IProfileService Profile; - - /// - /// The clock - /// - protected readonly ISystemClock Clock; - - private readonly IHttpContextAccessor _httpContextAccessor; - - private readonly IAuthenticationService _authenticationService; - - /// - /// Initializes a new instance of the class. - /// - /// The clock. - /// The logger. - /// The consent. - /// The profile. - public NopApiAuthorizeInteractionResponseGenerator( - ISystemClock clock, - ILogger logger, - IConsentService consent, - IProfileService profile, IHttpContextAccessor httpContextAccessor, IAuthenticationService authenticationService) - { - Clock = clock; - Logger = logger; - Consent = consent; - Profile = profile; - _httpContextAccessor = httpContextAccessor; - _authenticationService = authenticationService; - } - - /// - /// Processes the interaction logic. - /// - /// The request. - /// The consent. - /// - public virtual async Task ProcessInteractionAsync(ValidatedAuthorizeRequest request, ConsentResponse consent = null) - { - Logger.LogTrace("ProcessInteractionAsync"); - - if (consent != null && consent.Granted == false && request.Subject.IsAuthenticated() == false) - { - // special case when anonymous user has issued a deny prior to authenticating - Logger.LogInformation("Error: User denied consent"); - return new InteractionResponse - { - Error = OidcConstants.AuthorizeErrors.AccessDenied - }; - } - - var identityServerUser = new IdentityServerUser(request.ClientId) - { - DisplayName = request.Client.ClientName, - AdditionalClaims = request.ClientClaims, - AuthenticationTime = new DateTime?(DateTime.UtcNow) - }; - - request.Subject = identityServerUser.CreatePrincipal(); - - var authenticationProperties = new AuthenticationProperties - { - IsPersistent = true, - IssuedUtc = DateTime.UtcNow - }; - - await _httpContextAccessor.HttpContext.SignInAsync(IdentityServerConstants.DefaultCookieAuthenticationScheme, request.Subject, authenticationProperties); - - var result = new InteractionResponse(); - - return result; - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/IdentityServer/Infrastructure/ObjectSerializer.cs b/Nop.Plugin.Api/IdentityServer/Infrastructure/ObjectSerializer.cs deleted file mode 100644 index a056644..0000000 --- a/Nop.Plugin.Api/IdentityServer/Infrastructure/ObjectSerializer.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace Nop.Plugin.Api.IdentityServer.Infrastructure -{ - using IdentityServer4.Infrastructure; - using Newtonsoft.Json; - using Newtonsoft.Json.Linq; - - public class ObjectSerializer - { - private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings - { - DefaultValueHandling = DefaultValueHandling.Ignore, - NullValueHandling = NullValueHandling.Ignore - }; - - private static readonly JsonSerializer Serializer = new JsonSerializer - { - DefaultValueHandling = DefaultValueHandling.Ignore, - NullValueHandling = NullValueHandling.Ignore - }; - - static ObjectSerializer() - { - Settings.Converters.Add(new NameValueCollectionConverter()); - } - - public static string ToString(object o) - { - return JsonConvert.SerializeObject(o, Settings); - } - - public static T FromString(string value) - { - return JsonConvert.DeserializeObject(value, Settings); - } - - public static JObject ToJObject(object o) - { - return JObject.FromObject(o, Serializer); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/IdentityServer/Middlewares/IdentityServerScopeParameterMiddleware.cs b/Nop.Plugin.Api/IdentityServer/Middlewares/IdentityServerScopeParameterMiddleware.cs deleted file mode 100644 index 74ab622..0000000 --- a/Nop.Plugin.Api/IdentityServer/Middlewares/IdentityServerScopeParameterMiddleware.cs +++ /dev/null @@ -1,60 +0,0 @@ -namespace Nop.Plugin.Api.IdentityServer.Middlewares -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Http.Internal; - using Microsoft.Extensions.Primitives; - - public class IdentityServerScopeParameterMiddleware - { - private readonly RequestDelegate _next; - - public IdentityServerScopeParameterMiddleware(RequestDelegate next) - { - _next = next; - } - - public async Task Invoke(HttpContext context) - { - if (context.Request.Path.Value.Equals("/connect/authorize", StringComparison.InvariantCultureIgnoreCase) || - context.Request.Path.Value.Equals("/oauth/authorize", StringComparison.InvariantCultureIgnoreCase)) - { - // Make sure we have "nop_api" and "offline_access" scope - - var queryValues = new Dictionary(); - - foreach (var item in context.Request.Query) - { - if (item.Key == "scope") - { - string scopeValue = item.Value; - - if (!scopeValue.Contains("nop_api offline_access")) - { - // add our scope instead since we don't support other scopes - queryValues.Add(item.Key, "nop_api offline_access"); - continue; - } - } - - queryValues.Add(item.Key, item.Value); - } - - if (!queryValues.ContainsKey("scope")) - { - // if no scope is specified we add it - queryValues.Add("scope", "nop_api offline_access"); - } - - var newQueryCollection = new QueryCollection(queryValues); - - context.Request.Query = newQueryCollection; - - } - - await _next(context); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/IdentityServer/Services/ProfileService.cs b/Nop.Plugin.Api/IdentityServer/Services/ProfileService.cs deleted file mode 100644 index 57c5069..0000000 --- a/Nop.Plugin.Api/IdentityServer/Services/ProfileService.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace Nop.Plugin.Api.IdentityServer.Services -{ - using System.Linq; - using System.Threading.Tasks; - using IdentityServer4.Models; - using IdentityServer4.Services; - using Nop.Plugin.Api.Services; - - public class ProfileService : IProfileService - { - private readonly IClientService _clientService; - - public ProfileService(IClientService clientService) - { - _clientService = clientService; - } - - // TODO: test this - public Task GetProfileDataAsync(ProfileDataRequestContext context) - { - var sub = context.Subject.Claims.FirstOrDefault(x => x.Type == "sub"); - - var userId = 0; - - if (int.TryParse(sub?.Value, out userId)) - { - // TODO: do we need claims?? - //IdentityServer4.EntityFramework.Entities.Client client = _clientService.GetClientByClientId(userId.ToString()); - //context.IssuedClaims = context.Subject.Claims.ToList(); - //context.IssuedClaims.Add(new Claim(type: ClaimTypes.NameIdentifier, value: client.Id.ToString())); - //context.IssuedClaims.Add(new Claim(type: ClaimTypes.Name, value: client.ClientName)); - } - - return Task.CompletedTask; - } - - public Task IsActiveAsync(IsActiveContext context) - { - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Infrastructure/ApiPlugin.cs b/Nop.Plugin.Api/Infrastructure/ApiPlugin.cs new file mode 100644 index 0000000..93d8258 --- /dev/null +++ b/Nop.Plugin.Api/Infrastructure/ApiPlugin.cs @@ -0,0 +1,152 @@ +using Nop.Core; +using Nop.Core.Domain.Customers; +using Nop.Plugin.Api.Domain; +using Nop.Services.Configuration; +using Nop.Services.Customers; +using Nop.Services.Localization; +using Nop.Services.Plugins; +using Nop.Web.Framework.Menu; + +namespace Nop.Plugin.Api.Infrastructure +{ + public class ApiPlugin : BasePlugin + { + private readonly ICustomerService _customerService; + private readonly ILocalizationService _localizationService; + private readonly ISettingService _settingService; + private readonly IWebHelper _webHelper; + private readonly IWorkContext _workContext; + + public ApiPlugin( + ISettingService settingService, + IWorkContext workContext, + ICustomerService customerService, + ILocalizationService localizationService, + IWebHelper webHelper) + { + _settingService = settingService; + _workContext = workContext; + _customerService = customerService; + _localizationService = localizationService; + _webHelper = webHelper; + } + + public override void Install() + { + //locales + + _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api", "Api plugin"); + _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Menu.ManageClients", "Manage Api Clients"); + _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Configure", "Configure Web Api"); + _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.GeneralSettings", "General Settings"); + _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.EnableApi", "Enable Api"); + _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.EnableApi.Hint", + "By checking this settings you can Enable/Disable the Web Api"); + + _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Menu.Title", "API"); + _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Menu.Settings.Title", "Settings"); + + _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Page.Settings.Title", "Api Settings"); + + + _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Settings.GeneralSettingsTitle", "General Settings"); + _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Api.Admin.Edit", "Edit"); + + _localizationService.AddOrUpdatePluginLocaleResource("Api.Categories.Fields.Id.Invalid", "Id is invalid"); + _localizationService.AddOrUpdatePluginLocaleResource("Api.InvalidPropertyType", "Invalid Property Type"); + _localizationService.AddOrUpdatePluginLocaleResource("Api.InvalidType", "Invalid {0} type"); + _localizationService.AddOrUpdatePluginLocaleResource("Api.InvalidRequest", "Invalid request"); + _localizationService.AddOrUpdatePluginLocaleResource("Api.InvalidRootProperty", "Invalid root property"); + _localizationService.AddOrUpdatePluginLocaleResource("Api.NoJsonProvided", "No Json provided"); + _localizationService.AddOrUpdatePluginLocaleResource("Api.InvalidJsonFormat", "Json format is invalid"); + _localizationService.AddOrUpdatePluginLocaleResource("Api.Category.InvalidImageAttachmentFormat", "Invalid image attachment base64 format"); + _localizationService.AddOrUpdatePluginLocaleResource("Api.Category.InvalidImageSrc", "Invalid image source"); + _localizationService.AddOrUpdatePluginLocaleResource("Api.Category.InvalidImageSrcType", "You have provided an invalid image source/attachment "); + + _settingService.SaveSetting(new ApiSettings()); + + var apiRole = _customerService.GetCustomerRoleBySystemName(Constants.Roles.ApiRoleSystemName); + + if (apiRole == null) + { + apiRole = new CustomerRole + { + Name = Constants.Roles.ApiRoleName, + Active = true, + SystemName = Constants.Roles.ApiRoleSystemName + }; + + _customerService.InsertCustomerRole(apiRole); + } + else if (apiRole.Active == false) + { + apiRole.Active = true; + _customerService.UpdateCustomerRole(apiRole); + } + + + base.Install(); + + // Changes to Web.Config trigger application restart. + // This doesn't appear to affect the Install function, but just to be safe we will made web.config changes after the plugin was installed. + //_webConfigMangerHelper.AddConfiguration(); + } + + public override void Uninstall() + { + //locales + _localizationService.DeletePluginLocaleResources("Plugins.Api"); + + //_localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Menu.Title"); + //_localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Menu.Settings.Title"); + + //_localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Configure"); + //_localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.GeneralSettings"); + //_localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.EnableApi"); + //_localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.EnableApi.Hint"); + + //_localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Settings.GeneralSettingsTitle"); + //_localizationService.DeletePluginLocaleResource("Plugins.Api.Admin.Edit"); + + + var apiRole = _customerService.GetCustomerRoleBySystemName(Constants.Roles.ApiRoleSystemName); + if (apiRole != null) + { + apiRole.Active = false; + _customerService.UpdateCustomerRole(apiRole); + } + + + base.Uninstall(); + } + + public void ManageSiteMap(SiteMapNode rootNode) + { + var pluginMenuName = _localizationService.GetResource("Plugins.Api.Admin.Menu.Title", _workContext.WorkingLanguage.Id, defaultValue: "API"); + + var settingsMenuName = _localizationService.GetResource("Plugins.Api.Admin.Menu.Settings.Title", _workContext.WorkingLanguage.Id, defaultValue: "API"); + + const string adminUrlPart = "Admin/"; + + var pluginMainMenu = new SiteMapNode + { + Title = pluginMenuName, + Visible = true, + SystemName = "Api-Main-Menu", + IconClass = "fa-genderless" + }; + + pluginMainMenu.ChildNodes.Add(new SiteMapNode + { + Title = settingsMenuName, + Url = _webHelper.GetStoreLocation() + adminUrlPart + "ApiAdmin/Settings", + Visible = true, + SystemName = "Api-Settings-Menu", + IconClass = "fa-genderless" + }); + + + rootNode.ChildNodes.Add(pluginMainMenu); + } + } +} diff --git a/Nop.Plugin.Api/Infrastructure/ApiStartup.cs b/Nop.Plugin.Api/Infrastructure/ApiStartup.cs new file mode 100644 index 0000000..7e93df9 --- /dev/null +++ b/Nop.Plugin.Api/Infrastructure/ApiStartup.cs @@ -0,0 +1,148 @@ +using System; +using System.IdentityModel.Tokens.Jwt; +using System.Text; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Rewrite; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; +using Nop.Core.Infrastructure; +using Nop.Plugin.Api.Authorization.Policies; +using Nop.Plugin.Api.Authorization.Requirements; +using Nop.Plugin.Api.Configuration; +using Nop.Web.Framework.Infrastructure.Extensions; + +namespace Nop.Plugin.Api.Infrastructure +{ + public class ApiStartup : INopStartup + { + public void ConfigureServices(IServiceCollection services, IConfiguration configuration) + { + services.Configure(x => x.AllowSynchronousIO = true) + .Configure(x => x.AllowSynchronousIO = true); + + var apiConfigSection = configuration.GetSection("Api"); + + if (apiConfigSection != null) + { + var apiConfig = services.ConfigureStartupConfig(apiConfigSection); + + if (!string.IsNullOrEmpty(apiConfig.SecurityKey)) + { + services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + + }) + .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtBearerOptions => + { + jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = + new SymmetricSecurityKey(Encoding.UTF8.GetBytes(apiConfig.SecurityKey)), + ValidateIssuer = false, // ValidIssuer = "The name of the issuer", + ValidateAudience = false, // ValidAudience = "The name of the audience", + ValidateLifetime = + true, // validate the expiration and not before values in the token + ClockSkew = TimeSpan.FromMinutes(apiConfig.AllowedClockSkewInMinutes) + }; + }); + + JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); + AddAuthorizationPipeline(services); + services.AddHostedService(); + + } + } + + } + + public void Configure(IApplicationBuilder app) + { + var rewriteOptions = new RewriteOptions() + .AddRewrite("api/token", "/token", true); + + app.UseRewriter(rewriteOptions); + + + + app.UseCors(x => x + .AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader()); + + // Need to enable rewind so we can read the request body multiple times + // This should eventually be refactored, but both JsonModelBinder and all of the DTO validators need to read this stream. + //app.UseWhen(x => x.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase), + // builder => + // { + // builder.Use(async (context, next) => + // { + // Console.WriteLine("API Call"); + // context.Request.EnableBuffering(); + // await next(); + // }); + // }); + + app.MapWhen( + context => (context.Request.Path + .StartsWithSegments(new PathString("/api")) + ), + a => + { + + a.Use(async (context, next) => + { + Console.WriteLine("API Call"); + + context.Request.EnableBuffering(); + await next(); + }); + + a.UseExceptionHandler("/api/error/500/Error"); + + a.UseRouting(); + a.UseAuthentication(); + a.UseAuthorization(); + a.UseEndpoints(endpoints => + { + endpoints + .MapControllers(); + }); + + + } + ); + } + + public int Order => 1; + + private static void AddAuthorizationPipeline(IServiceCollection services) + { + services.AddAuthorization(options => + { + options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, + policy => + { + policy.Requirements.Add(new ActiveApiPluginRequirement()); + policy.Requirements.Add(new AuthorizationSchemeRequirement()); + policy.Requirements.Add(new CustomerRoleRequirement()); + policy.RequireAuthenticatedUser(); + + }); + }); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + + } + } +} diff --git a/Nop.Plugin.Api/Infrastructure/Constants.cs b/Nop.Plugin.Api/Infrastructure/Constants.cs new file mode 100644 index 0000000..f6ac0a0 --- /dev/null +++ b/Nop.Plugin.Api/Infrastructure/Constants.cs @@ -0,0 +1,44 @@ +using Nop.Core.Caching; + +namespace Nop.Plugin.Api.Infrastructure +{ + public static class Constants + { + public static class Roles + { + public const string ApiRoleSystemName = "ApiUserRole"; + + public const string ApiRoleName = "Api Users"; + } + + public static class ViewNames + { + public const string AdminLayout = "_AdminLayout"; + } + + public static class Configurations + { + public const int DefaultAccessTokenExpirationInDays = 3650; // 10 years + + // time is in seconds (10 years = 315360000 seconds) and should not exceed 2038 year + // https://stackoverflow.com/questions/43593074/jwt-validation-fails/43605820 + //public const int DefaultAccessTokenExpiration = 315360000; + //public const int DefaultRefreshTokenExpiration = int.MaxValue; + public const int DefaultLimit = 50; + public const int DefaultPageValue = 1; + public const int DefaultSinceId = 0; + public const int DefaultCustomerId = 0; + public const string DefaultOrder = "Id"; + public const int MaxLimit = 250; + + public const int MinLimit = 1; + + //public const string PublishedStatus = "published"; + //public const string UnpublishedStatus = "unpublished"; + //public const string AnyStatus = "any"; + public static CacheKey JsonTypeMapsPattern => new CacheKey("json.maps"); + + public static CacheKey NEWSLETTER_SUBSCRIBERS_KEY = new CacheKey("Nop.api.newslettersubscribers"); + } + } +} diff --git a/Nop.Plugin.Api/Infrastructure/DependencyRegister.cs b/Nop.Plugin.Api/Infrastructure/DependencyRegister.cs index 63a5348..29b2ceb 100644 --- a/Nop.Plugin.Api/Infrastructure/DependencyRegister.cs +++ b/Nop.Plugin.Api/Infrastructure/DependencyRegister.cs @@ -1,29 +1,26 @@ -using Autofac; +using System.Collections.Generic; +using Autofac; +using JetBrains.Annotations; +using Microsoft.AspNetCore.Http; using Nop.Core.Configuration; +using Nop.Core.Domain.Catalog; +using Nop.Core.Domain.Common; +using Nop.Core.Domain.Customers; +using Nop.Core.Domain.Orders; using Nop.Core.Infrastructure; using Nop.Core.Infrastructure.DependencyManagement; +using Nop.Plugin.Api.Converters; +using Nop.Plugin.Api.Factories; +using Nop.Plugin.Api.Helpers; +using Nop.Plugin.Api.JSON.Serializers; +using Nop.Plugin.Api.Maps; +using Nop.Plugin.Api.ModelBinders; using Nop.Plugin.Api.Services; -using Nop.Web.Framework.Infrastructure.Extensions; +using Nop.Plugin.Api.Validators; namespace Nop.Plugin.Api.Infrastructure { - using Autofac.Core; - using Microsoft.AspNetCore.Http; - using Nop.Core.Domain.Catalog; - using Nop.Core.Domain.Common; - using Nop.Core.Domain.Customers; - using Nop.Core.Domain.Orders; - using Nop.Plugin.Api.Converters; - using Nop.Plugin.Api.Data; - using Nop.Plugin.Api.Factories; - using Nop.Plugin.Api.Helpers; - using Nop.Plugin.Api.JSON.Serializers; - using Nop.Plugin.Api.ModelBinders; - using Nop.Plugin.Api.Validators; - //using Nop.Plugin.Api.WebHooks; - using System; - using System.Collections.Generic; - + [UsedImplicitly] public class DependencyRegister : IDependencyRegistrar { public void Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config) @@ -33,6 +30,8 @@ public void Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig RegisterModelBinders(builder); } + public virtual int Order => short.MaxValue; + private void RegisterModelBinders(ContainerBuilder builder) { builder.RegisterGeneric(typeof(ParametersModelBinder<>)).InstancePerLifetimeScope(); @@ -41,7 +40,7 @@ private void RegisterModelBinders(ContainerBuilder builder) private void RegisterPluginServices(ContainerBuilder builder) { - builder.RegisterType().As().InstancePerLifetimeScope(); + //builder.RegisterType().As().InstancePerLifetimeScope(); builder.RegisterType().As().InstancePerLifetimeScope(); builder.RegisterType().As().InstancePerLifetimeScope(); builder.RegisterType().As().InstancePerLifetimeScope(); @@ -61,18 +60,11 @@ private void RegisterPluginServices(ContainerBuilder builder) builder.RegisterType().As().InstancePerLifetimeScope(); builder.RegisterType().As().InstancePerLifetimeScope(); builder.RegisterType().As().InstancePerLifetimeScope(); - builder.RegisterType().As().InstancePerLifetimeScope(); - - //TODO: Upgrade 4.1. Check this! - //builder.RegisterType().As().InstancePerLifetimeScope(); builder.RegisterType().As().InstancePerLifetimeScope(); builder.RegisterType().As().InstancePerLifetimeScope(); - //TODO: Upgrade 4.1. Check this! - //builder.RegisterType().As().SingleInstance(); - builder.RegisterType().As().InstancePerLifetimeScope(); builder.RegisterType().As().InstancePerLifetimeScope(); @@ -84,16 +76,11 @@ private void RegisterPluginServices(ContainerBuilder builder) builder.RegisterType().As>().InstancePerLifetimeScope(); builder.RegisterType().As>().InstancePerLifetimeScope(); - builder.RegisterType().As().InstancePerLifetimeScope(); + builder.RegisterType().As().InstancePerLifetimeScope(); builder.RegisterType().As().SingleInstance(); builder.RegisterType>().SingleInstance(); } - - public virtual int Order - { - get { return Int16.MaxValue; } - } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/JSON/ActionResults/ErrorActionResult.cs b/Nop.Plugin.Api/JSON/ActionResults/ErrorActionResult.cs index da8f3b9..2bce3aa 100644 --- a/Nop.Plugin.Api/JSON/ActionResults/ErrorActionResult.cs +++ b/Nop.Plugin.Api/JSON/ActionResults/ErrorActionResult.cs @@ -1,15 +1,14 @@ -using System.Net; +using System; +using System.IO; +using System.Net; +using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.WebUtilities; namespace Nop.Plugin.Api.JSON.ActionResults { - using System; - using System.IO; - using System.Text; - using Microsoft.AspNetCore.WebUtilities; - - public class ErrorActionResult : IActionResult + public class ErrorActionResult : ActionResult { private readonly string _jsonString; private readonly HttpStatusCode _statusCode; @@ -19,23 +18,22 @@ public ErrorActionResult(string jsonString, HttpStatusCode statusCode) _jsonString = jsonString; _statusCode = statusCode; } - - public Task ExecuteResultAsync(ActionContext context) - { + + public override void ExecuteResult(ActionContext context) + { if (context == null) + { throw new ArgumentNullException(nameof(context)); + } - var response = context.HttpContext.Response; - - response.StatusCode = (int)_statusCode; + var response = context.HttpContext.Response; + response.StatusCode = (int) _statusCode; response.ContentType = "application/json"; - using (TextWriter writer = new HttpResponseStreamWriter(response.Body, Encoding.UTF8)) { writer.Write(_jsonString); } - return Task.CompletedTask; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/JSON/ActionResults/RawJsonActionResult.cs b/Nop.Plugin.Api/JSON/ActionResults/RawJsonActionResult.cs index 0e8e1d6..d83ca79 100644 --- a/Nop.Plugin.Api/JSON/ActionResults/RawJsonActionResult.cs +++ b/Nop.Plugin.Api/JSON/ActionResults/RawJsonActionResult.cs @@ -1,18 +1,18 @@ -using System.Threading.Tasks; +using System; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.WebUtilities; namespace Nop.Plugin.Api.JSON.ActionResults { - using System; - using System.IO; - using System.Text; - using Microsoft.AspNetCore.WebUtilities; - // TODO: Move to BaseApiController as method. - public class RawJsonActionResult : IActionResult + public class RawJsonActionResult : ActionResult { private readonly string _jsonString; - + public RawJsonActionResult(object value) { if (value != null) @@ -21,22 +21,19 @@ public RawJsonActionResult(object value) } } - public Task ExecuteResultAsync(ActionContext context) + public override async Task ExecuteResultAsync(ActionContext context) { if (context == null) + { throw new ArgumentNullException(nameof(context)); + } var response = context.HttpContext.Response; - + response.StatusCode = 200; response.ContentType = "application/json"; - using (TextWriter writer = new HttpResponseStreamWriter(response.Body, Encoding.UTF8)) - { - writer.Write(_jsonString); - } - - return Task.CompletedTask; + await response.WriteAsync(_jsonString); } } } diff --git a/Nop.Plugin.Api/JSON/Serializers/IJsonFieldsSerializer.cs b/Nop.Plugin.Api/JSON/Serializers/IJsonFieldsSerializer.cs index cb0b6d7..5d0cfe5 100644 --- a/Nop.Plugin.Api/JSON/Serializers/IJsonFieldsSerializer.cs +++ b/Nop.Plugin.Api/JSON/Serializers/IJsonFieldsSerializer.cs @@ -1,7 +1,7 @@ -namespace Nop.Plugin.Api.JSON.Serializers -{ - using Nop.Plugin.Api.DTOs; +using Nop.Plugin.Api.DTO; +namespace Nop.Plugin.Api.JSON.Serializers +{ public interface IJsonFieldsSerializer { string Serialize(ISerializableObject objectToSerialize, string fields); diff --git a/Nop.Plugin.Api/JSON/Serializers/JsonFieldsSerializer.cs b/Nop.Plugin.Api/JSON/Serializers/JsonFieldsSerializer.cs index 45a7b6d..5ef8cf6 100644 --- a/Nop.Plugin.Api/JSON/Serializers/JsonFieldsSerializer.cs +++ b/Nop.Plugin.Api/JSON/Serializers/JsonFieldsSerializer.cs @@ -1,12 +1,12 @@ -namespace Nop.Plugin.Api.JSON.Serializers -{ - using System; - using System.Collections.Generic; - using System.Linq; - using Newtonsoft.Json.Linq; - using Nop.Plugin.Api.DTOs; - using Nop.Plugin.Api.Helpers; +using System; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json.Linq; +using Nop.Plugin.Api.DTO; +using Nop.Plugin.Api.Helpers; +namespace Nop.Plugin.Api.JSON.Serializers +{ public class JsonFieldsSerializer : IJsonFieldsSerializer { public string Serialize(ISerializableObject objectToSerialize, string jsonFields) @@ -50,12 +50,15 @@ private string Serialize(object objectToSerialize, IList jsonFields = nu private IList GetPropertiesIntoList(string fields) { IList properties = fields.ToLowerInvariant() - .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) - .Select(x => x.Trim()) - .Distinct() - .ToList(); + .Split(new[] + { + ',' + }, StringSplitOptions.RemoveEmptyEntries) + .Select(x => x.Trim()) + .Distinct() + .ToList(); return properties; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/KendoUI/DataSourceRequest.cs b/Nop.Plugin.Api/KendoUI/DataSourceRequest.cs deleted file mode 100644 index c6beab9..0000000 --- a/Nop.Plugin.Api/KendoUI/DataSourceRequest.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace Nop.Plugin.Api.Kendoui -{ - /// - /// DataSource request - /// - public class DataSourceRequest - { - /// - /// Ctor - /// - public DataSourceRequest() - { - Page = 1; - PageSize = 10; - } - - /// - /// Page number - /// - public int Page { get; set; } - - /// - /// Page size - /// - public int PageSize { get; set; } - } -} diff --git a/Nop.Plugin.Api/KendoUI/DataSourceResult.cs b/Nop.Plugin.Api/KendoUI/DataSourceResult.cs deleted file mode 100644 index 070d67a..0000000 --- a/Nop.Plugin.Api/KendoUI/DataSourceResult.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections; - -namespace Nop.Plugin.Api.Kendoui -{ - /// - /// DataSource result - /// - public class DataSourceResult - { - /// - /// Extra data - /// - public object ExtraData { get; set; } - - /// - /// Data - /// - public IEnumerable Data { get; set; } - - /// - /// Errors - /// - public object Errors { get; set; } - - /// - /// Total records - /// - public int Total { get; set; } - } -} diff --git a/Nop.Plugin.Api/MappingExtensions/AddressDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/AddressDtoMappings.cs index de5ba90..5bd91b5 100644 --- a/Nop.Plugin.Api/MappingExtensions/AddressDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/AddressDtoMappings.cs @@ -1,6 +1,6 @@ using Nop.Core.Domain.Common; using Nop.Plugin.Api.AutoMapper; -using Nop.Plugin.Api.DTOs; +using Nop.Plugin.Api.DTO; namespace Nop.Plugin.Api.MappingExtensions { @@ -16,4 +16,4 @@ public static Address ToEntity(this AddressDto addressDto) return addressDto.MapTo(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/BaseMapping.cs b/Nop.Plugin.Api/MappingExtensions/BaseMapping.cs index 32f7fc7..4029c7b 100644 --- a/Nop.Plugin.Api/MappingExtensions/BaseMapping.cs +++ b/Nop.Plugin.Api/MappingExtensions/BaseMapping.cs @@ -6,7 +6,8 @@ namespace Nop.Plugin.Api.MappingExtensions { public static class BaseMapping { - public static IMappingExpression IgnoreAllNonExisting(this IMappingExpression expression) + public static IMappingExpression IgnoreAllNonExisting( + this IMappingExpression expression) { var flags = BindingFlags.Public | BindingFlags.Instance; var sourceType = typeof(TSource); @@ -21,13 +22,16 @@ public static IMappingExpression IgnoreAllNonExisting(this TSource instance, - Func getter, - TResult defaultValue = default(TResult)) - where TSource : class + + public static TResult GetWithDefault( + this TSource instance, + Func getter, + TResult defaultValue = default(TResult)) + where TSource : class { - return instance != null ? getter(instance) : defaultValue; + return instance != null + ? getter(instance) + : defaultValue; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/CategoryDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/CategoryDtoMappings.cs index 26abcf6..42b331d 100644 --- a/Nop.Plugin.Api/MappingExtensions/CategoryDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/CategoryDtoMappings.cs @@ -1,6 +1,6 @@ using Nop.Core.Domain.Catalog; using Nop.Plugin.Api.AutoMapper; -using Nop.Plugin.Api.DTOs.Categories; +using Nop.Plugin.Api.DTO.Categories; namespace Nop.Plugin.Api.MappingExtensions { @@ -16,4 +16,4 @@ public static Category ToEntity(this CategoryDto categoryDto) return categoryDto.MapTo(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/ClientMappings.cs b/Nop.Plugin.Api/MappingExtensions/ClientMappings.cs deleted file mode 100644 index 21ffa3f..0000000 --- a/Nop.Plugin.Api/MappingExtensions/ClientMappings.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Nop.Plugin.Api.AutoMapper; - -namespace Nop.Plugin.Api.MappingExtensions -{ - using IdentityServer4.EntityFramework.Entities; - using Nop.Plugin.Api.Models; - - public static class ClientMappings - { - public static ClientApiModel ToApiModel(this Client client) - { - return client.MapTo(); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/MappingExtensions/ConfigurationMappings.cs b/Nop.Plugin.Api/MappingExtensions/ConfigurationMappings.cs index bbac81b..234f337 100644 --- a/Nop.Plugin.Api/MappingExtensions/ConfigurationMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/ConfigurationMappings.cs @@ -1,6 +1,6 @@ -using Nop.Plugin.Api.AutoMapper; +using Nop.Plugin.Api.Areas.Admin.Models; +using Nop.Plugin.Api.AutoMapper; using Nop.Plugin.Api.Domain; -using Nop.Plugin.Api.Models; namespace Nop.Plugin.Api.MappingExtensions { @@ -16,4 +16,4 @@ public static ApiSettings ToEntity(this ConfigurationModel apiSettingsModel) return apiSettingsModel.MapTo(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/CustomerDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/CustomerDtoMappings.cs index ef1b37e..8d76c72 100644 --- a/Nop.Plugin.Api/MappingExtensions/CustomerDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/CustomerDtoMappings.cs @@ -1,6 +1,6 @@ -using Nop.Plugin.Api.AutoMapper; -using Nop.Core.Domain.Customers; -using Nop.Plugin.Api.DTOs.Customers; +using Nop.Core.Domain.Customers; +using Nop.Plugin.Api.AutoMapper; +using Nop.Plugin.Api.DTO.Customers; namespace Nop.Plugin.Api.MappingExtensions { @@ -26,4 +26,4 @@ public static CustomerForShoppingCartItemDto ToCustomerForShoppingCartItemDto(th return customer.MapTo(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/CustomerRoleDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/CustomerRoleDtoMappings.cs index 34bffc5..ccae1fb 100644 --- a/Nop.Plugin.Api/MappingExtensions/CustomerRoleDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/CustomerRoleDtoMappings.cs @@ -1,6 +1,6 @@ -using Nop.Plugin.Api.AutoMapper; -using Nop.Core.Domain.Customers; -using Nop.Plugin.Api.DTOs.CustomerRoles; +using Nop.Core.Domain.Customers; +using Nop.Plugin.Api.AutoMapper; +using Nop.Plugin.Api.DTO.CustomerRoles; namespace Nop.Plugin.Api.MappingExtensions { diff --git a/Nop.Plugin.Api/MappingExtensions/LanguageDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/LanguageDtoMappings.cs index 6f0000c..551e898 100644 --- a/Nop.Plugin.Api/MappingExtensions/LanguageDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/LanguageDtoMappings.cs @@ -1,6 +1,6 @@ using Nop.Core.Domain.Localization; using Nop.Plugin.Api.AutoMapper; -using Nop.Plugin.Api.DTOs.Languages; +using Nop.Plugin.Api.DTO.Languages; namespace Nop.Plugin.Api.MappingExtensions { diff --git a/Nop.Plugin.Api/MappingExtensions/ManufacturerDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/ManufacturerDtoMappings.cs index 92eb2d7..b049644 100644 --- a/Nop.Plugin.Api/MappingExtensions/ManufacturerDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/ManufacturerDtoMappings.cs @@ -1,6 +1,6 @@ using Nop.Core.Domain.Catalog; using Nop.Plugin.Api.AutoMapper; -using Nop.Plugin.Api.DTOs.Manufacturers; +using Nop.Plugin.Api.DTO.Manufacturers; namespace Nop.Plugin.Api.MappingExtensions { @@ -11,4 +11,4 @@ public static ManufacturerDto ToDto(this Manufacturer manufacturer) return manufacturer.MapTo(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/NewsLetterSubscriptoonDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/NewsLetterSubscriptoonDtoMappings.cs index f9fe51f..918fe75 100644 --- a/Nop.Plugin.Api/MappingExtensions/NewsLetterSubscriptoonDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/NewsLetterSubscriptoonDtoMappings.cs @@ -1,6 +1,6 @@ using Nop.Core.Domain.Messages; using Nop.Plugin.Api.AutoMapper; -using Nop.Plugin.Api.DTOs.Categories; +using Nop.Plugin.Api.DTO.NewsLetterSubscriptions; namespace Nop.Plugin.Api.MappingExtensions { diff --git a/Nop.Plugin.Api/MappingExtensions/OrderDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/OrderDtoMappings.cs index 0d192b1..84a8883 100644 --- a/Nop.Plugin.Api/MappingExtensions/OrderDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/OrderDtoMappings.cs @@ -1,6 +1,6 @@ using Nop.Core.Domain.Orders; using Nop.Plugin.Api.AutoMapper; -using Nop.Plugin.Api.DTOs.Orders; +using Nop.Plugin.Api.DTO.Orders; namespace Nop.Plugin.Api.MappingExtensions { @@ -11,4 +11,4 @@ public static OrderDto ToDto(this Order order) return order.MapTo(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/OrderItemDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/OrderItemDtoMappings.cs index 3019d7c..c058f86 100644 --- a/Nop.Plugin.Api/MappingExtensions/OrderItemDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/OrderItemDtoMappings.cs @@ -1,6 +1,6 @@ using Nop.Core.Domain.Orders; using Nop.Plugin.Api.AutoMapper; -using Nop.Plugin.Api.DTOs.OrderItems; +using Nop.Plugin.Api.DTO.OrderItems; namespace Nop.Plugin.Api.MappingExtensions { @@ -11,4 +11,4 @@ public static OrderItemDto ToDto(this OrderItem orderItem) return orderItem.MapTo(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/ProductAttributeCombinationDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/ProductAttributeCombinationDtoMappings.cs index acc6e7d..21c3096 100644 --- a/Nop.Plugin.Api/MappingExtensions/ProductAttributeCombinationDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/ProductAttributeCombinationDtoMappings.cs @@ -1,6 +1,6 @@ using Nop.Core.Domain.Catalog; using Nop.Plugin.Api.AutoMapper; -using Nop.Plugin.Api.DTOs.Products; +using Nop.Plugin.Api.DTO.Products; namespace Nop.Plugin.Api.MappingExtensions { @@ -11,4 +11,4 @@ public static ProductAttributeCombinationDto ToDto(this ProductAttributeCombinat return productAttributeCombination.MapTo(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/ProductAttributeDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/ProductAttributeDtoMappings.cs index ba003c0..570a954 100644 --- a/Nop.Plugin.Api/MappingExtensions/ProductAttributeDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/ProductAttributeDtoMappings.cs @@ -1,6 +1,6 @@ using Nop.Core.Domain.Catalog; using Nop.Plugin.Api.AutoMapper; -using Nop.Plugin.Api.DTOs.ProductAttributes; +using Nop.Plugin.Api.DTO.ProductAttributes; namespace Nop.Plugin.Api.MappingExtensions { diff --git a/Nop.Plugin.Api/MappingExtensions/ProductCategoryMappingDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/ProductCategoryMappingDtoMappings.cs index c1caf5d..5e83e5f 100644 --- a/Nop.Plugin.Api/MappingExtensions/ProductCategoryMappingDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/ProductCategoryMappingDtoMappings.cs @@ -1,6 +1,6 @@ -using Nop.Plugin.Api.AutoMapper; -using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.DTOs.ProductCategoryMappings; +using Nop.Core.Domain.Catalog; +using Nop.Plugin.Api.AutoMapper; +using Nop.Plugin.Api.DTO.ProductCategoryMappings; namespace Nop.Plugin.Api.MappingExtensions { @@ -11,4 +11,4 @@ public static ProductCategoryMappingDto ToDto(this ProductCategory mapping) return mapping.MapTo(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/ProductDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/ProductDtoMappings.cs index ca43d3e..194603c 100644 --- a/Nop.Plugin.Api/MappingExtensions/ProductDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/ProductDtoMappings.cs @@ -1,6 +1,6 @@ -using Nop.Plugin.Api.AutoMapper; -using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.DTOs.Products; +using Nop.Core.Domain.Catalog; +using Nop.Plugin.Api.AutoMapper; +using Nop.Plugin.Api.DTO.Products; namespace Nop.Plugin.Api.MappingExtensions { @@ -16,4 +16,4 @@ public static ProductAttributeValueDto ToDto(this ProductAttributeValue productA return productAttributeValue.MapTo(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/ProductManufacturerMappingDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/ProductManufacturerMappingDtoMappings.cs index 583858e..62568b6 100644 --- a/Nop.Plugin.Api/MappingExtensions/ProductManufacturerMappingDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/ProductManufacturerMappingDtoMappings.cs @@ -1,6 +1,6 @@ using Nop.Core.Domain.Catalog; using Nop.Plugin.Api.AutoMapper; -using Nop.Plugin.Api.DTOs.ProductManufacturerMappings; +using Nop.Plugin.Api.DTO.ProductManufacturerMappings; namespace Nop.Plugin.Api.MappingExtensions { @@ -11,4 +11,4 @@ public static ProductManufacturerMappingsDto ToDto(this ProductManufacturer mapp return mapping.MapTo(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/ShoppingCartItemDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/ShoppingCartItemDtoMappings.cs index 7a31c07..24c8c10 100644 --- a/Nop.Plugin.Api/MappingExtensions/ShoppingCartItemDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/ShoppingCartItemDtoMappings.cs @@ -1,6 +1,6 @@ -using Nop.Plugin.Api.AutoMapper; -using Nop.Core.Domain.Orders; -using Nop.Plugin.Api.DTOs.ShoppingCarts; +using Nop.Core.Domain.Orders; +using Nop.Plugin.Api.AutoMapper; +using Nop.Plugin.Api.DTO.ShoppingCarts; namespace Nop.Plugin.Api.MappingExtensions { @@ -11,4 +11,4 @@ public static ShoppingCartItemDto ToDto(this ShoppingCartItem shoppingCartItem) return shoppingCartItem.MapTo(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/SpecificationAttributeDtoMapping.cs b/Nop.Plugin.Api/MappingExtensions/SpecificationAttributeDtoMapping.cs index 5af3501..3c8bf7e 100644 --- a/Nop.Plugin.Api/MappingExtensions/SpecificationAttributeDtoMapping.cs +++ b/Nop.Plugin.Api/MappingExtensions/SpecificationAttributeDtoMapping.cs @@ -1,6 +1,6 @@ using Nop.Core.Domain.Catalog; using Nop.Plugin.Api.AutoMapper; -using Nop.Plugin.Api.DTOs.SpecificationAttributes; +using Nop.Plugin.Api.DTO.SpecificationAttributes; namespace Nop.Plugin.Api.MappingExtensions { @@ -21,4 +21,4 @@ public static SpecificationAttributeOptionDto ToDto(this SpecificationAttributeO return specificationAttributeOption.MapTo(); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/MappingExtensions/StoreDtoMappings.cs b/Nop.Plugin.Api/MappingExtensions/StoreDtoMappings.cs index 230d738..ca1479f 100644 --- a/Nop.Plugin.Api/MappingExtensions/StoreDtoMappings.cs +++ b/Nop.Plugin.Api/MappingExtensions/StoreDtoMappings.cs @@ -1,6 +1,6 @@ using Nop.Core.Domain.Stores; using Nop.Plugin.Api.AutoMapper; -using Nop.Plugin.Api.DTOs.Stores; +using Nop.Plugin.Api.DTO.Stores; namespace Nop.Plugin.Api.MappingExtensions { diff --git a/Nop.Plugin.Api/Maps/IJsonPropertyMap.cs b/Nop.Plugin.Api/Maps/IJsonPropertyMap.cs index 9a648cf..e0d8441 100644 --- a/Nop.Plugin.Api/Maps/IJsonPropertyMap.cs +++ b/Nop.Plugin.Api/Maps/IJsonPropertyMap.cs @@ -7,4 +7,4 @@ public interface IJsonPropertyMapper { Dictionary> GetMap(Type type); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Maps/JsonPropertyMap.cs b/Nop.Plugin.Api/Maps/JsonPropertyMap.cs index 7faa1c8..a2f3a4a 100644 --- a/Nop.Plugin.Api/Maps/JsonPropertyMap.cs +++ b/Nop.Plugin.Api/Maps/JsonPropertyMap.cs @@ -5,35 +5,26 @@ using Nop.Core.Caching; using Nop.Core.Infrastructure; using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; +using Nop.Services.Caching; namespace Nop.Plugin.Api.Maps { public class JsonPropertyMapper : IJsonPropertyMapper { private IStaticCacheManager _cacheManager; - - private IStaticCacheManager StaticCacheManager - { - get - { - if (_cacheManager == null) - { - _cacheManager = EngineContext.Current.Resolve(); - } - - return _cacheManager; - } - } + private ICacheKeyService _cacheKeyService => EngineContext.Current.Resolve(); + private IStaticCacheManager StaticCacheManager => _cacheManager ?? (_cacheManager = EngineContext.Current.Resolve()); public Dictionary> GetMap(Type type) { - if (!StaticCacheManager.IsSet(Configurations.JsonTypeMapsPattern)) + if (!StaticCacheManager.IsSet(Constants.Configurations.JsonTypeMapsPattern)) { - StaticCacheManager.Set(Configurations.JsonTypeMapsPattern, new Dictionary>>(), int.MaxValue); + StaticCacheManager.Set(_cacheKeyService.PrepareKeyForDefaultCache(Constants.Configurations.JsonTypeMapsPattern), new Dictionary>>()); } - var typeMaps = StaticCacheManager.Get>>>(Configurations.JsonTypeMapsPattern, () => null); + var typeMaps = + StaticCacheManager.Get>>>(_cacheKeyService.PrepareKeyForDefaultCache(Constants.Configurations.JsonTypeMapsPattern), () => null); if (!typeMaps.ContainsKey(type.Name)) { @@ -46,12 +37,12 @@ public Dictionary> GetMap(Type type) private void Build(Type type) { var typeMaps = - StaticCacheManager.Get>>>(Configurations.JsonTypeMapsPattern, () => null); + StaticCacheManager.Get>>>(_cacheKeyService.PrepareKeyForDefaultCache(Constants.Configurations.JsonTypeMapsPattern), () => null); var mapForCurrentType = new Dictionary>(); var typeProps = type.GetProperties(); - + foreach (var property in typeProps) { var jsonAttribute = property.GetCustomAttribute(typeof(JsonPropertyAttribute)) as JsonPropertyAttribute; @@ -67,11 +58,11 @@ private void Build(Type type) } } } - + if (!typeMaps.ContainsKey(type.Name)) { typeMaps.Add(type.Name, mapForCurrentType); } } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20170319181717_Config.Designer.cs b/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20170319181717_Config.Designer.cs deleted file mode 100644 index d5c3ca5..0000000 --- a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20170319181717_Config.Designer.cs +++ /dev/null @@ -1,539 +0,0 @@ -namespace Nop.Plugin.Api.Migrations.IdentityServer.ConfigurationDb -{ - using System; - using IdentityServer4.EntityFramework.DbContexts; - using Microsoft.EntityFrameworkCore; - using Microsoft.EntityFrameworkCore.Infrastructure; - using Microsoft.EntityFrameworkCore.Metadata; - using Microsoft.EntityFrameworkCore.Migrations; - - [DbContext(typeof(ConfigurationDbContext))] - [Migration("20170319181717_Config")] - partial class Config - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { - modelBuilder - .HasAnnotation("ProductVersion", "1.1.1") - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Enabled"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ApiResourceId") - .IsRequired(); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ApiResourceId") - .IsRequired(); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Emphasize"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.Property("Required"); - - b.Property("ShowInDiscoveryDocument"); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ApiScopeId") - .IsRequired(); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ApiScopeId"); - - b.ToTable("ApiScopeClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ApiResourceId") - .IsRequired(); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("Expiration"); - - b.Property("Type") - .HasMaxLength(250); - - b.Property("Value") - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("AbsoluteRefreshTokenLifetime"); - - b.Property("AccessTokenLifetime"); - - b.Property("AccessTokenType"); - - b.Property("AllowAccessTokensViaBrowser"); - - b.Property("AllowOfflineAccess"); - - b.Property("AllowPlainTextPkce"); - - b.Property("AllowRememberConsent"); - - b.Property("AlwaysIncludeUserClaimsInIdToken"); - - b.Property("AlwaysSendClientClaims"); - - b.Property("AuthorizationCodeLifetime"); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200); - - b.Property("ClientName") - .HasMaxLength(200); - - b.Property("ClientUri") - .HasMaxLength(2000); - - b.Property("EnableLocalLogin"); - - b.Property("Enabled"); - - b.Property("IdentityTokenLifetime"); - - b.Property("IncludeJwtId"); - - b.Property("LogoUri"); - - b.Property("LogoutSessionRequired"); - - b.Property("LogoutUri"); - - b.Property("PrefixClientClaims"); - - b.Property("ProtocolType") - .IsRequired() - .HasMaxLength(200); - - b.Property("RefreshTokenExpiration"); - - b.Property("RefreshTokenUsage"); - - b.Property("RequireClientSecret"); - - b.Property("RequireConsent"); - - b.Property("RequirePkce"); - - b.Property("SlidingRefreshTokenLifetime"); - - b.Property("UpdateAccessTokenClaimsOnRefresh"); - - b.HasKey("Id"); - - b.HasIndex("ClientId") - .IsUnique(); - - b.ToTable("Clients"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(250); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Origin") - .IsRequired() - .HasMaxLength(150); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientCorsOrigins"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("GrantType") - .IsRequired() - .HasMaxLength(250); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientGrantTypes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Provider") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientIdPRestrictions"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("PostLogoutRedirectUri") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientPostLogoutRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("RedirectUri") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Scope") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Description") - .HasMaxLength(2000); - - b.Property("Expiration"); - - b.Property("Type") - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("IdentityResourceId") - .IsRequired(); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("IdentityResourceId"); - - b.ToTable("IdentityClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Emphasize"); - - b.Property("Enabled"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.Property("Required"); - - b.Property("ShowInDiscoveryDocument"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("IdentityResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("UserClaims") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Scopes") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "ApiScope") - .WithMany("UserClaims") - .HasForeignKey("ApiScopeId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Secrets") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("Claims") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedCorsOrigins") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedGrantTypes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("IdentityProviderRestrictions") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("PostLogoutRedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("RedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedScopes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("ClientSecrets") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") - .WithMany("UserClaims") - .HasForeignKey("IdentityResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20170319181717_Config.cs b/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20170319181717_Config.cs deleted file mode 100644 index b098a63..0000000 --- a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20170319181717_Config.cs +++ /dev/null @@ -1,500 +0,0 @@ -namespace Nop.Plugin.Api.Migrations.IdentityServer.ConfigurationDb -{ - using System; - using Microsoft.EntityFrameworkCore.Metadata; - using Microsoft.EntityFrameworkCore.Migrations; - - public partial class Config : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "ApiResources", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - Description = table.Column(maxLength: 1000, nullable: true), - DisplayName = table.Column(maxLength: 200, nullable: true), - Enabled = table.Column(nullable: false), - Name = table.Column(maxLength: 200, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiResources", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Clients", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - AbsoluteRefreshTokenLifetime = table.Column(nullable: false), - AccessTokenLifetime = table.Column(nullable: false), - AccessTokenType = table.Column(nullable: false), - AllowAccessTokensViaBrowser = table.Column(nullable: false), - AllowOfflineAccess = table.Column(nullable: false), - AllowPlainTextPkce = table.Column(nullable: false), - AllowRememberConsent = table.Column(nullable: false), - AlwaysIncludeUserClaimsInIdToken = table.Column(nullable: false), - AlwaysSendClientClaims = table.Column(nullable: false), - AuthorizationCodeLifetime = table.Column(nullable: false), - ClientId = table.Column(maxLength: 200, nullable: false), - ClientName = table.Column(maxLength: 200, nullable: true), - ClientUri = table.Column(maxLength: 2000, nullable: true), - EnableLocalLogin = table.Column(nullable: false), - Enabled = table.Column(nullable: false), - IdentityTokenLifetime = table.Column(nullable: false), - IncludeJwtId = table.Column(nullable: false), - LogoUri = table.Column(nullable: true), - LogoutSessionRequired = table.Column(nullable: false), - LogoutUri = table.Column(nullable: true), - PrefixClientClaims = table.Column(nullable: false), - ProtocolType = table.Column(maxLength: 200, nullable: false), - RefreshTokenExpiration = table.Column(nullable: false), - RefreshTokenUsage = table.Column(nullable: false), - RequireClientSecret = table.Column(nullable: false), - RequireConsent = table.Column(nullable: false), - RequirePkce = table.Column(nullable: false), - SlidingRefreshTokenLifetime = table.Column(nullable: false), - UpdateAccessTokenClaimsOnRefresh = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Clients", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "IdentityResources", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - Description = table.Column(maxLength: 1000, nullable: true), - DisplayName = table.Column(maxLength: 200, nullable: true), - Emphasize = table.Column(nullable: false), - Enabled = table.Column(nullable: false), - Name = table.Column(maxLength: 200, nullable: false), - Required = table.Column(nullable: false), - ShowInDiscoveryDocument = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_IdentityResources", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "ApiClaims", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ApiResourceId = table.Column(nullable: false), - Type = table.Column(maxLength: 200, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiClaims", x => x.Id); - table.ForeignKey( - name: "FK_ApiClaims_ApiResources_ApiResourceId", - column: x => x.ApiResourceId, - principalTable: "ApiResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ApiScopes", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ApiResourceId = table.Column(nullable: false), - Description = table.Column(maxLength: 1000, nullable: true), - DisplayName = table.Column(maxLength: 200, nullable: true), - Emphasize = table.Column(nullable: false), - Name = table.Column(maxLength: 200, nullable: false), - Required = table.Column(nullable: false), - ShowInDiscoveryDocument = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiScopes", x => x.Id); - table.ForeignKey( - name: "FK_ApiScopes_ApiResources_ApiResourceId", - column: x => x.ApiResourceId, - principalTable: "ApiResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ApiSecrets", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ApiResourceId = table.Column(nullable: false), - Description = table.Column(maxLength: 1000, nullable: true), - Expiration = table.Column(nullable: true), - Type = table.Column(maxLength: 250, nullable: true), - Value = table.Column(maxLength: 2000, nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiSecrets", x => x.Id); - table.ForeignKey( - name: "FK_ApiSecrets_ApiResources_ApiResourceId", - column: x => x.ApiResourceId, - principalTable: "ApiResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientClaims", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(nullable: false), - Type = table.Column(maxLength: 250, nullable: false), - Value = table.Column(maxLength: 250, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientClaims", x => x.Id); - table.ForeignKey( - name: "FK_ClientClaims_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientCorsOrigins", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(nullable: false), - Origin = table.Column(maxLength: 150, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientCorsOrigins", x => x.Id); - table.ForeignKey( - name: "FK_ClientCorsOrigins_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientGrantTypes", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(nullable: false), - GrantType = table.Column(maxLength: 250, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientGrantTypes", x => x.Id); - table.ForeignKey( - name: "FK_ClientGrantTypes_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientIdPRestrictions", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(nullable: false), - Provider = table.Column(maxLength: 200, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientIdPRestrictions", x => x.Id); - table.ForeignKey( - name: "FK_ClientIdPRestrictions_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientPostLogoutRedirectUris", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(nullable: false), - PostLogoutRedirectUri = table.Column(maxLength: 2000, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientPostLogoutRedirectUris", x => x.Id); - table.ForeignKey( - name: "FK_ClientPostLogoutRedirectUris_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientRedirectUris", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(nullable: false), - RedirectUri = table.Column(maxLength: 2000, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientRedirectUris", x => x.Id); - table.ForeignKey( - name: "FK_ClientRedirectUris_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientScopes", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(nullable: false), - Scope = table.Column(maxLength: 200, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientScopes", x => x.Id); - table.ForeignKey( - name: "FK_ClientScopes_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ClientSecrets", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(nullable: false), - Description = table.Column(maxLength: 2000, nullable: true), - Expiration = table.Column(nullable: true), - Type = table.Column(maxLength: 250, nullable: true), - Value = table.Column(maxLength: 2000, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientSecrets", x => x.Id); - table.ForeignKey( - name: "FK_ClientSecrets_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "IdentityClaims", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - IdentityResourceId = table.Column(nullable: false), - Type = table.Column(maxLength: 200, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_IdentityClaims", x => x.Id); - table.ForeignKey( - name: "FK_IdentityClaims_IdentityResources_IdentityResourceId", - column: x => x.IdentityResourceId, - principalTable: "IdentityResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "ApiScopeClaims", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ApiScopeId = table.Column(nullable: false), - Type = table.Column(maxLength: 200, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiScopeClaims", x => x.Id); - table.ForeignKey( - name: "FK_ApiScopeClaims_ApiScopes_ApiScopeId", - column: x => x.ApiScopeId, - principalTable: "ApiScopes", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateIndex( - name: "IX_ApiResources_Name", - table: "ApiResources", - column: "Name", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_ApiClaims_ApiResourceId", - table: "ApiClaims", - column: "ApiResourceId"); - - migrationBuilder.CreateIndex( - name: "IX_ApiScopes_ApiResourceId", - table: "ApiScopes", - column: "ApiResourceId"); - - migrationBuilder.CreateIndex( - name: "IX_ApiScopes_Name", - table: "ApiScopes", - column: "Name", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_ApiScopeClaims_ApiScopeId", - table: "ApiScopeClaims", - column: "ApiScopeId"); - - migrationBuilder.CreateIndex( - name: "IX_ApiSecrets_ApiResourceId", - table: "ApiSecrets", - column: "ApiResourceId"); - - migrationBuilder.CreateIndex( - name: "IX_Clients_ClientId", - table: "Clients", - column: "ClientId", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_ClientClaims_ClientId", - table: "ClientClaims", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientCorsOrigins_ClientId", - table: "ClientCorsOrigins", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientGrantTypes_ClientId", - table: "ClientGrantTypes", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientIdPRestrictions_ClientId", - table: "ClientIdPRestrictions", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientPostLogoutRedirectUris_ClientId", - table: "ClientPostLogoutRedirectUris", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientRedirectUris_ClientId", - table: "ClientRedirectUris", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientScopes_ClientId", - table: "ClientScopes", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_ClientSecrets_ClientId", - table: "ClientSecrets", - column: "ClientId"); - - migrationBuilder.CreateIndex( - name: "IX_IdentityClaims_IdentityResourceId", - table: "IdentityClaims", - column: "IdentityResourceId"); - - migrationBuilder.CreateIndex( - name: "IX_IdentityResources_Name", - table: "IdentityResources", - column: "Name", - unique: true); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "ApiClaims"); - - migrationBuilder.DropTable( - name: "ApiScopeClaims"); - - migrationBuilder.DropTable( - name: "ApiSecrets"); - - migrationBuilder.DropTable( - name: "ClientClaims"); - - migrationBuilder.DropTable( - name: "ClientCorsOrigins"); - - migrationBuilder.DropTable( - name: "ClientGrantTypes"); - - migrationBuilder.DropTable( - name: "ClientIdPRestrictions"); - - migrationBuilder.DropTable( - name: "ClientPostLogoutRedirectUris"); - - migrationBuilder.DropTable( - name: "ClientRedirectUris"); - - migrationBuilder.DropTable( - name: "ClientScopes"); - - migrationBuilder.DropTable( - name: "ClientSecrets"); - - migrationBuilder.DropTable( - name: "IdentityClaims"); - - migrationBuilder.DropTable( - name: "ApiScopes"); - - migrationBuilder.DropTable( - name: "Clients"); - - migrationBuilder.DropTable( - name: "IdentityResources"); - - migrationBuilder.DropTable( - name: "ApiResources"); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20171107104928_DotNetCore2IdentityServerConfigurationDbMigration.Designer.cs b/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20171107104928_DotNetCore2IdentityServerConfigurationDbMigration.Designer.cs deleted file mode 100644 index b0b160e..0000000 --- a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20171107104928_DotNetCore2IdentityServerConfigurationDbMigration.Designer.cs +++ /dev/null @@ -1,590 +0,0 @@ -// - -namespace Nop.Plugin.Api.Migrations.IdentityServer.ConfigurationDb -{ - using System; - using IdentityServer4.EntityFramework.DbContexts; - using Microsoft.EntityFrameworkCore; - using Microsoft.EntityFrameworkCore.Infrastructure; - using Microsoft.EntityFrameworkCore.Metadata; - using Microsoft.EntityFrameworkCore.Migrations; - - [DbContext(typeof(ConfigurationDbContext))] - [Migration("20171107104928_DotNetCore2IdentityServerConfigurationDbMigration")] - partial class DotNetCore2IdentityServerConfigurationDbMigration - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "2.0.0-rtm-26452") - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Enabled"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ApiResourceId") - .IsRequired(); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ApiResourceId") - .IsRequired(); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Emphasize"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.Property("Required"); - - b.Property("ShowInDiscoveryDocument"); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ApiScopeId") - .IsRequired(); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ApiScopeId"); - - b.ToTable("ApiScopeClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ApiResourceId") - .IsRequired(); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("Expiration"); - - b.Property("Type") - .HasMaxLength(250); - - b.Property("Value") - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("AbsoluteRefreshTokenLifetime"); - - b.Property("AccessTokenLifetime"); - - b.Property("AccessTokenType"); - - b.Property("AllowAccessTokensViaBrowser"); - - b.Property("AllowOfflineAccess"); - - b.Property("AllowPlainTextPkce"); - - b.Property("AllowRememberConsent"); - - b.Property("AlwaysIncludeUserClaimsInIdToken"); - - b.Property("AlwaysSendClientClaims"); - - b.Property("AuthorizationCodeLifetime"); - - b.Property("BackChannelLogoutSessionRequired"); - - b.Property("BackChannelLogoutUri") - .HasMaxLength(2000); - - b.Property("ClientClaimsPrefix") - .HasMaxLength(200); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200); - - b.Property("ClientName") - .HasMaxLength(200); - - b.Property("ClientUri") - .HasMaxLength(2000); - - b.Property("ConsentLifetime"); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("EnableLocalLogin"); - - b.Property("Enabled"); - - b.Property("FrontChannelLogoutSessionRequired"); - - b.Property("FrontChannelLogoutUri") - .HasMaxLength(2000); - - b.Property("IdentityTokenLifetime"); - - b.Property("IncludeJwtId"); - - b.Property("LogoUri") - .HasMaxLength(2000); - - b.Property("PairWiseSubjectSalt") - .HasMaxLength(200); - - b.Property("ProtocolType") - .IsRequired() - .HasMaxLength(200); - - b.Property("RefreshTokenExpiration"); - - b.Property("RefreshTokenUsage"); - - b.Property("RequireClientSecret"); - - b.Property("RequireConsent"); - - b.Property("RequirePkce"); - - b.Property("SlidingRefreshTokenLifetime"); - - b.Property("UpdateAccessTokenClaimsOnRefresh"); - - b.HasKey("Id"); - - b.HasIndex("ClientId") - .IsUnique(); - - b.ToTable("Clients"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(250); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Origin") - .IsRequired() - .HasMaxLength(150); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientCorsOrigins"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("GrantType") - .IsRequired() - .HasMaxLength(250); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientGrantTypes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Provider") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientIdPRestrictions"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("PostLogoutRedirectUri") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientPostLogoutRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("RedirectUri") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Scope") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClientId") - .IsRequired(); - - b.Property("Description") - .HasMaxLength(2000); - - b.Property("Expiration"); - - b.Property("Type") - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("IdentityResourceId") - .IsRequired(); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("IdentityResourceId"); - - b.ToTable("IdentityClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Emphasize"); - - b.Property("Enabled"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.Property("Required"); - - b.Property("ShowInDiscoveryDocument"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("IdentityResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("UserClaims") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Scopes") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "ApiScope") - .WithMany("UserClaims") - .HasForeignKey("ApiScopeId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Secrets") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("Claims") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedCorsOrigins") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedGrantTypes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("IdentityProviderRestrictions") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("PostLogoutRedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("Properties") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("RedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedScopes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("ClientSecrets") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") - .WithMany("UserClaims") - .HasForeignKey("IdentityResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20171107104928_DotNetCore2IdentityServerConfigurationDbMigration.cs b/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20171107104928_DotNetCore2IdentityServerConfigurationDbMigration.cs deleted file mode 100644 index 3db8418..0000000 --- a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20171107104928_DotNetCore2IdentityServerConfigurationDbMigration.cs +++ /dev/null @@ -1,177 +0,0 @@ -namespace Nop.Plugin.Api.Migrations.IdentityServer.ConfigurationDb -{ - using Microsoft.EntityFrameworkCore.Metadata; - using Microsoft.EntityFrameworkCore.Migrations; - - public partial class DotNetCore2IdentityServerConfigurationDbMigration : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropColumn( - name: "LogoutSessionRequired", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "LogoutUri", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "PrefixClientClaims", - table: "Clients"); - - migrationBuilder.AlterColumn( - name: "LogoUri", - table: "Clients", - type: "nvarchar(2000)", - maxLength: 2000, - nullable: true, - oldClrType: typeof(string), - oldNullable: true); - - migrationBuilder.AddColumn( - name: "BackChannelLogoutSessionRequired", - table: "Clients", - type: "bit", - nullable: false, - defaultValue: false); - - migrationBuilder.AddColumn( - name: "BackChannelLogoutUri", - table: "Clients", - type: "nvarchar(2000)", - maxLength: 2000, - nullable: true); - - migrationBuilder.AddColumn( - name: "ClientClaimsPrefix", - table: "Clients", - type: "nvarchar(200)", - maxLength: 200, - nullable: true); - - migrationBuilder.AddColumn( - name: "ConsentLifetime", - table: "Clients", - type: "int", - nullable: true); - - migrationBuilder.AddColumn( - name: "Description", - table: "Clients", - type: "nvarchar(1000)", - maxLength: 1000, - nullable: true); - - migrationBuilder.AddColumn( - name: "FrontChannelLogoutSessionRequired", - table: "Clients", - type: "bit", - nullable: false, - defaultValue: false); - - migrationBuilder.AddColumn( - name: "FrontChannelLogoutUri", - table: "Clients", - type: "nvarchar(2000)", - maxLength: 2000, - nullable: true); - - migrationBuilder.AddColumn( - name: "PairWiseSubjectSalt", - table: "Clients", - type: "nvarchar(200)", - maxLength: 200, - nullable: true); - - migrationBuilder.CreateTable( - name: "ClientProperties", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - ClientId = table.Column(type: "int", nullable: false), - Key = table.Column(type: "nvarchar(250)", maxLength: 250, nullable: false), - Value = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ClientProperties", x => x.Id); - table.ForeignKey( - name: "FK_ClientProperties_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateIndex( - name: "IX_ClientProperties_ClientId", - table: "ClientProperties", - column: "ClientId"); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "ClientProperties"); - - migrationBuilder.DropColumn( - name: "BackChannelLogoutSessionRequired", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "BackChannelLogoutUri", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "ClientClaimsPrefix", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "ConsentLifetime", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "Description", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "FrontChannelLogoutSessionRequired", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "FrontChannelLogoutUri", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "PairWiseSubjectSalt", - table: "Clients"); - - migrationBuilder.AlterColumn( - name: "LogoUri", - table: "Clients", - nullable: true, - oldClrType: typeof(string), - oldType: "nvarchar(2000)", - oldMaxLength: 2000, - oldNullable: true); - - migrationBuilder.AddColumn( - name: "LogoutSessionRequired", - table: "Clients", - nullable: false, - defaultValue: false); - - migrationBuilder.AddColumn( - name: "LogoutUri", - table: "Clients", - nullable: true); - - migrationBuilder.AddColumn( - name: "PrefixClientClaims", - table: "Clients", - nullable: false, - defaultValue: false); - } - } -} diff --git a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20191009140628_identityserver25update.Designer.cs b/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20191009140628_identityserver25update.Designer.cs deleted file mode 100644 index f82a222..0000000 --- a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20191009140628_identityserver25update.Designer.cs +++ /dev/null @@ -1,692 +0,0 @@ -// -using System; -using IdentityServer4.EntityFramework.DbContexts; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -namespace Nop.Plugin.Api.Migrations.IdentityServer.ConfigurationDb -{ - [DbContext(typeof(ConfigurationDbContext))] - [Migration("20191009140628_identityserver25update")] - partial class identityserver25update - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "2.1.11-servicing-32099") - .HasAnnotation("Relational:MaxIdentifierLength", 128) - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("Created"); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Enabled"); - - b.Property("LastAccessed"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.Property("NonEditable"); - - b.Property("Updated"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ApiResourceId"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ApiResourceId"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ApiResourceId"); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Emphasize"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.Property("Required"); - - b.Property("ShowInDiscoveryDocument"); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ApiScopeId"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ApiScopeId"); - - b.ToTable("ApiScopeClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ApiResourceId"); - - b.Property("Created"); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("Expiration"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(4000); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("AbsoluteRefreshTokenLifetime"); - - b.Property("AccessTokenLifetime"); - - b.Property("AccessTokenType"); - - b.Property("AllowAccessTokensViaBrowser"); - - b.Property("AllowOfflineAccess"); - - b.Property("AllowPlainTextPkce"); - - b.Property("AllowRememberConsent"); - - b.Property("AlwaysIncludeUserClaimsInIdToken"); - - b.Property("AlwaysSendClientClaims"); - - b.Property("AuthorizationCodeLifetime"); - - b.Property("BackChannelLogoutSessionRequired"); - - b.Property("BackChannelLogoutUri") - .HasMaxLength(2000); - - b.Property("ClientClaimsPrefix") - .HasMaxLength(200); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200); - - b.Property("ClientName") - .HasMaxLength(200); - - b.Property("ClientUri") - .HasMaxLength(2000); - - b.Property("ConsentLifetime"); - - b.Property("Created"); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DeviceCodeLifetime"); - - b.Property("EnableLocalLogin"); - - b.Property("Enabled"); - - b.Property("FrontChannelLogoutSessionRequired"); - - b.Property("FrontChannelLogoutUri") - .HasMaxLength(2000); - - b.Property("IdentityTokenLifetime"); - - b.Property("IncludeJwtId"); - - b.Property("LastAccessed"); - - b.Property("LogoUri") - .HasMaxLength(2000); - - b.Property("NonEditable"); - - b.Property("PairWiseSubjectSalt") - .HasMaxLength(200); - - b.Property("ProtocolType") - .IsRequired() - .HasMaxLength(200); - - b.Property("RefreshTokenExpiration"); - - b.Property("RefreshTokenUsage"); - - b.Property("RequireClientSecret"); - - b.Property("RequireConsent"); - - b.Property("RequirePkce"); - - b.Property("SlidingRefreshTokenLifetime"); - - b.Property("UpdateAccessTokenClaimsOnRefresh"); - - b.Property("Updated"); - - b.Property("UserCodeType") - .HasMaxLength(100); - - b.Property("UserSsoLifetime"); - - b.HasKey("Id"); - - b.HasIndex("ClientId") - .IsUnique(); - - b.ToTable("Clients"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(250); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("Origin") - .IsRequired() - .HasMaxLength(150); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientCorsOrigins"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("GrantType") - .IsRequired() - .HasMaxLength(250); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientGrantTypes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("Provider") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientIdPRestrictions"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("PostLogoutRedirectUri") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientPostLogoutRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("RedirectUri") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("Scope") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("Created"); - - b.Property("Description") - .HasMaxLength(2000); - - b.Property("Expiration"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(4000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("IdentityResourceId"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("IdentityResourceId"); - - b.ToTable("IdentityClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("Created"); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Emphasize"); - - b.Property("Enabled"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.Property("NonEditable"); - - b.Property("Required"); - - b.Property("ShowInDiscoveryDocument"); - - b.Property("Updated"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("IdentityResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("IdentityResourceId"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("IdentityResourceId"); - - b.ToTable("IdentityProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("UserClaims") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Properties") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Scopes") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "ApiScope") - .WithMany("UserClaims") - .HasForeignKey("ApiScopeId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Secrets") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("Claims") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedCorsOrigins") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedGrantTypes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("IdentityProviderRestrictions") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("PostLogoutRedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("Properties") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("RedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedScopes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("ClientSecrets") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") - .WithMany("UserClaims") - .HasForeignKey("IdentityResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") - .WithMany("Properties") - .HasForeignKey("IdentityResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20191009140628_identityserver25update.cs b/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20191009140628_identityserver25update.cs deleted file mode 100644 index f783841..0000000 --- a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/20191009140628_identityserver25update.cs +++ /dev/null @@ -1,294 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace Nop.Plugin.Api.Migrations.IdentityServer.ConfigurationDb -{ - public partial class identityserver25update : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.AddColumn( - name: "Created", - table: "IdentityResources", - nullable: false, - defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); - - migrationBuilder.AddColumn( - name: "NonEditable", - table: "IdentityResources", - nullable: false, - defaultValue: false); - - migrationBuilder.AddColumn( - name: "Updated", - table: "IdentityResources", - nullable: true); - - migrationBuilder.AlterColumn( - name: "Value", - table: "ClientSecrets", - maxLength: 4000, - nullable: false, - oldClrType: typeof(string), - oldMaxLength: 2000); - - migrationBuilder.AlterColumn( - name: "Type", - table: "ClientSecrets", - maxLength: 250, - nullable: false, - oldClrType: typeof(string), - oldMaxLength: 250, - oldNullable: true); - - migrationBuilder.AddColumn( - name: "Created", - table: "ClientSecrets", - nullable: false, - defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); - - migrationBuilder.AddColumn( - name: "Created", - table: "Clients", - nullable: false, - defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); - - migrationBuilder.AddColumn( - name: "DeviceCodeLifetime", - table: "Clients", - nullable: false, - defaultValue: 0); - - migrationBuilder.AddColumn( - name: "LastAccessed", - table: "Clients", - nullable: true); - - migrationBuilder.AddColumn( - name: "NonEditable", - table: "Clients", - nullable: false, - defaultValue: false); - - migrationBuilder.AddColumn( - name: "Updated", - table: "Clients", - nullable: true); - - migrationBuilder.AddColumn( - name: "UserCodeType", - table: "Clients", - maxLength: 100, - nullable: true); - - migrationBuilder.AddColumn( - name: "UserSsoLifetime", - table: "Clients", - nullable: true); - - migrationBuilder.AlterColumn( - name: "Value", - table: "ApiSecrets", - maxLength: 4000, - nullable: false, - oldClrType: typeof(string), - oldMaxLength: 2000, - oldNullable: true); - - migrationBuilder.AlterColumn( - name: "Type", - table: "ApiSecrets", - maxLength: 250, - nullable: false, - oldClrType: typeof(string), - oldMaxLength: 250, - oldNullable: true); - - migrationBuilder.AddColumn( - name: "Created", - table: "ApiSecrets", - nullable: false, - defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); - - migrationBuilder.AddColumn( - name: "Created", - table: "ApiResources", - nullable: false, - defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); - - migrationBuilder.AddColumn( - name: "LastAccessed", - table: "ApiResources", - nullable: true); - - migrationBuilder.AddColumn( - name: "NonEditable", - table: "ApiResources", - nullable: false, - defaultValue: false); - - migrationBuilder.AddColumn( - name: "Updated", - table: "ApiResources", - nullable: true); - - migrationBuilder.CreateTable( - name: "ApiProperties", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - Key = table.Column(maxLength: 250, nullable: false), - Value = table.Column(maxLength: 2000, nullable: false), - ApiResourceId = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ApiProperties", x => x.Id); - table.ForeignKey( - name: "FK_ApiProperties_ApiResources_ApiResourceId", - column: x => x.ApiResourceId, - principalTable: "ApiResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "IdentityProperties", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), - Key = table.Column(maxLength: 250, nullable: false), - Value = table.Column(maxLength: 2000, nullable: false), - IdentityResourceId = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_IdentityProperties", x => x.Id); - table.ForeignKey( - name: "FK_IdentityProperties_IdentityResources_IdentityResourceId", - column: x => x.IdentityResourceId, - principalTable: "IdentityResources", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateIndex( - name: "IX_ApiProperties_ApiResourceId", - table: "ApiProperties", - column: "ApiResourceId"); - - migrationBuilder.CreateIndex( - name: "IX_IdentityProperties_IdentityResourceId", - table: "IdentityProperties", - column: "IdentityResourceId"); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "ApiProperties"); - - migrationBuilder.DropTable( - name: "IdentityProperties"); - - migrationBuilder.DropColumn( - name: "Created", - table: "IdentityResources"); - - migrationBuilder.DropColumn( - name: "NonEditable", - table: "IdentityResources"); - - migrationBuilder.DropColumn( - name: "Updated", - table: "IdentityResources"); - - migrationBuilder.DropColumn( - name: "Created", - table: "ClientSecrets"); - - migrationBuilder.DropColumn( - name: "Created", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "DeviceCodeLifetime", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "LastAccessed", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "NonEditable", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "Updated", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "UserCodeType", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "UserSsoLifetime", - table: "Clients"); - - migrationBuilder.DropColumn( - name: "Created", - table: "ApiSecrets"); - - migrationBuilder.DropColumn( - name: "Created", - table: "ApiResources"); - - migrationBuilder.DropColumn( - name: "LastAccessed", - table: "ApiResources"); - - migrationBuilder.DropColumn( - name: "NonEditable", - table: "ApiResources"); - - migrationBuilder.DropColumn( - name: "Updated", - table: "ApiResources"); - - migrationBuilder.AlterColumn( - name: "Value", - table: "ClientSecrets", - maxLength: 2000, - nullable: false, - oldClrType: typeof(string), - oldMaxLength: 4000); - - migrationBuilder.AlterColumn( - name: "Type", - table: "ClientSecrets", - maxLength: 250, - nullable: true, - oldClrType: typeof(string), - oldMaxLength: 250); - - migrationBuilder.AlterColumn( - name: "Value", - table: "ApiSecrets", - maxLength: 2000, - nullable: true, - oldClrType: typeof(string), - oldMaxLength: 4000); - - migrationBuilder.AlterColumn( - name: "Type", - table: "ApiSecrets", - maxLength: 250, - nullable: true, - oldClrType: typeof(string), - oldMaxLength: 250); - } - } -} diff --git a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/ConfigurationDbContextModelSnapshot.cs b/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/ConfigurationDbContextModelSnapshot.cs deleted file mode 100644 index deda783..0000000 --- a/Nop.Plugin.Api/Migrations/IdentityServer/ConfigurationDb/ConfigurationDbContextModelSnapshot.cs +++ /dev/null @@ -1,690 +0,0 @@ -// -using System; -using IdentityServer4.EntityFramework.DbContexts; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -namespace Nop.Plugin.Api.Migrations.IdentityServer.ConfigurationDb -{ - [DbContext(typeof(ConfigurationDbContext))] - partial class ConfigurationDbContextModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "2.1.11-servicing-32099") - .HasAnnotation("Relational:MaxIdentifierLength", 128) - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("Created"); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Enabled"); - - b.Property("LastAccessed"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.Property("NonEditable"); - - b.Property("Updated"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ApiResourceId"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ApiResourceId"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ApiResourceId"); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Emphasize"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.Property("Required"); - - b.Property("ShowInDiscoveryDocument"); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("ApiScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ApiScopeId"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ApiScopeId"); - - b.ToTable("ApiScopeClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ApiResourceId"); - - b.Property("Created"); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("Expiration"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(4000); - - b.HasKey("Id"); - - b.HasIndex("ApiResourceId"); - - b.ToTable("ApiSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("AbsoluteRefreshTokenLifetime"); - - b.Property("AccessTokenLifetime"); - - b.Property("AccessTokenType"); - - b.Property("AllowAccessTokensViaBrowser"); - - b.Property("AllowOfflineAccess"); - - b.Property("AllowPlainTextPkce"); - - b.Property("AllowRememberConsent"); - - b.Property("AlwaysIncludeUserClaimsInIdToken"); - - b.Property("AlwaysSendClientClaims"); - - b.Property("AuthorizationCodeLifetime"); - - b.Property("BackChannelLogoutSessionRequired"); - - b.Property("BackChannelLogoutUri") - .HasMaxLength(2000); - - b.Property("ClientClaimsPrefix") - .HasMaxLength(200); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200); - - b.Property("ClientName") - .HasMaxLength(200); - - b.Property("ClientUri") - .HasMaxLength(2000); - - b.Property("ConsentLifetime"); - - b.Property("Created"); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DeviceCodeLifetime"); - - b.Property("EnableLocalLogin"); - - b.Property("Enabled"); - - b.Property("FrontChannelLogoutSessionRequired"); - - b.Property("FrontChannelLogoutUri") - .HasMaxLength(2000); - - b.Property("IdentityTokenLifetime"); - - b.Property("IncludeJwtId"); - - b.Property("LastAccessed"); - - b.Property("LogoUri") - .HasMaxLength(2000); - - b.Property("NonEditable"); - - b.Property("PairWiseSubjectSalt") - .HasMaxLength(200); - - b.Property("ProtocolType") - .IsRequired() - .HasMaxLength(200); - - b.Property("RefreshTokenExpiration"); - - b.Property("RefreshTokenUsage"); - - b.Property("RequireClientSecret"); - - b.Property("RequireConsent"); - - b.Property("RequirePkce"); - - b.Property("SlidingRefreshTokenLifetime"); - - b.Property("UpdateAccessTokenClaimsOnRefresh"); - - b.Property("Updated"); - - b.Property("UserCodeType") - .HasMaxLength(100); - - b.Property("UserSsoLifetime"); - - b.HasKey("Id"); - - b.HasIndex("ClientId") - .IsUnique(); - - b.ToTable("Clients"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(250); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("Origin") - .IsRequired() - .HasMaxLength(150); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientCorsOrigins"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("GrantType") - .IsRequired() - .HasMaxLength(250); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientGrantTypes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("Provider") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientIdPRestrictions"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("PostLogoutRedirectUri") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientPostLogoutRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("RedirectUri") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientRedirectUris"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("Scope") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientScopes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("ClientId"); - - b.Property("Created"); - - b.Property("Description") - .HasMaxLength(2000); - - b.Property("Expiration"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(4000); - - b.HasKey("Id"); - - b.HasIndex("ClientId"); - - b.ToTable("ClientSecrets"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("IdentityResourceId"); - - b.Property("Type") - .IsRequired() - .HasMaxLength(200); - - b.HasKey("Id"); - - b.HasIndex("IdentityResourceId"); - - b.ToTable("IdentityClaims"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("Created"); - - b.Property("Description") - .HasMaxLength(1000); - - b.Property("DisplayName") - .HasMaxLength(200); - - b.Property("Emphasize"); - - b.Property("Enabled"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200); - - b.Property("NonEditable"); - - b.Property("Required"); - - b.Property("ShowInDiscoveryDocument"); - - b.Property("Updated"); - - b.HasKey("Id"); - - b.HasIndex("Name") - .IsUnique(); - - b.ToTable("IdentityResources"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - b.Property("IdentityResourceId"); - - b.Property("Key") - .IsRequired() - .HasMaxLength(250); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2000); - - b.HasKey("Id"); - - b.HasIndex("IdentityResourceId"); - - b.ToTable("IdentityProperties"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("UserClaims") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Properties") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Scopes") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "ApiScope") - .WithMany("UserClaims") - .HasForeignKey("ApiScopeId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") - .WithMany("Secrets") - .HasForeignKey("ApiResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("Claims") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedCorsOrigins") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedGrantTypes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("IdentityProviderRestrictions") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("PostLogoutRedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("Properties") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("RedirectUris") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("AllowedScopes") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") - .WithMany("ClientSecrets") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") - .WithMany("UserClaims") - .HasForeignKey("IdentityResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => - { - b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") - .WithMany("Properties") - .HasForeignKey("IdentityResourceId") - .OnDelete(DeleteBehavior.Cascade); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/20170319181710_Grants.Designer.cs b/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/20170319181710_Grants.Designer.cs deleted file mode 100644 index 097a742..0000000 --- a/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/20170319181710_Grants.Designer.cs +++ /dev/null @@ -1,52 +0,0 @@ -namespace Nop.Plugin.Api.Migrations.IdentityServer.PersitedGrantDb -{ - using System; - using IdentityServer4.EntityFramework.DbContexts; - using Microsoft.EntityFrameworkCore; - using Microsoft.EntityFrameworkCore.Infrastructure; - using Microsoft.EntityFrameworkCore.Metadata; - using Microsoft.EntityFrameworkCore.Migrations; - - [DbContext(typeof(PersistedGrantDbContext))] - [Migration("20170319181710_Grants")] - partial class Grants - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { - modelBuilder - .HasAnnotation("ProductVersion", "1.1.1") - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => - { - b.Property("Key") - .HasMaxLength(200); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200); - - b.Property("CreationTime"); - - b.Property("Data") - .IsRequired() - .HasMaxLength(50000); - - b.Property("Expiration"); - - b.Property("SubjectId") - .HasMaxLength(200); - - b.Property("Type") - .IsRequired() - .HasMaxLength(50); - - b.HasKey("Key"); - - b.HasIndex("SubjectId", "ClientId", "Type"); - - b.ToTable("PersistedGrants"); - }); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/20170319181710_Grants.cs b/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/20170319181710_Grants.cs deleted file mode 100644 index 0a053d7..0000000 --- a/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/20170319181710_Grants.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace Nop.Plugin.Api.Migrations.IdentityServer.PersitedGrantDb -{ - using System; - using Microsoft.EntityFrameworkCore.Migrations; - - public partial class Grants : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "PersistedGrants", - columns: table => new - { - Key = table.Column(maxLength: 200, nullable: false), - ClientId = table.Column(maxLength: 200, nullable: false), - CreationTime = table.Column(nullable: false), - Data = table.Column(maxLength: 50000, nullable: false), - Expiration = table.Column(nullable: true), - SubjectId = table.Column(maxLength: 200, nullable: true), - Type = table.Column(maxLength: 50, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_PersistedGrants", x => x.Key); - }); - - migrationBuilder.CreateIndex( - name: "IX_PersistedGrants_SubjectId_ClientId_Type", - table: "PersistedGrants", - columns: new[] { "SubjectId", "ClientId", "Type" }); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "PersistedGrants"); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/20191009140613_identityserver25update.Designer.cs b/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/20191009140613_identityserver25update.Designer.cs deleted file mode 100644 index 220f083..0000000 --- a/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/20191009140613_identityserver25update.Designer.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -using System; -using IdentityServer4.EntityFramework.DbContexts; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -namespace Nop.Plugin.Api.Migrations.IdentityServer.PersitedGrantDb -{ - [DbContext(typeof(PersistedGrantDbContext))] - [Migration("20191009140613_identityserver25update")] - partial class identityserver25update - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "2.1.11-servicing-32099") - .HasAnnotation("Relational:MaxIdentifierLength", 128) - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b => - { - b.Property("UserCode") - .ValueGeneratedOnAdd() - .HasMaxLength(200); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200); - - b.Property("CreationTime"); - - b.Property("Data") - .IsRequired() - .HasMaxLength(50000); - - b.Property("DeviceCode") - .IsRequired() - .HasMaxLength(200); - - b.Property("Expiration") - .IsRequired(); - - b.Property("SubjectId") - .HasMaxLength(200); - - b.HasKey("UserCode"); - - b.HasIndex("DeviceCode") - .IsUnique(); - - b.HasIndex("Expiration"); - - b.ToTable("DeviceCodes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => - { - b.Property("Key") - .HasMaxLength(200); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200); - - b.Property("CreationTime"); - - b.Property("Data") - .IsRequired() - .HasMaxLength(50000); - - b.Property("Expiration"); - - b.Property("SubjectId") - .HasMaxLength(200); - - b.Property("Type") - .IsRequired() - .HasMaxLength(50); - - b.HasKey("Key"); - - b.HasIndex("SubjectId", "ClientId", "Type", "Expiration"); - - b.ToTable("PersistedGrants"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/20191009140613_identityserver25update.cs b/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/20191009140613_identityserver25update.cs deleted file mode 100644 index a5ab286..0000000 --- a/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/20191009140613_identityserver25update.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -namespace Nop.Plugin.Api.Migrations.IdentityServer.PersitedGrantDb -{ - public partial class identityserver25update : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropIndex( - name: "IX_PersistedGrants_SubjectId_ClientId_Type", - table: "PersistedGrants"); - - migrationBuilder.CreateTable( - name: "DeviceCodes", - columns: table => new - { - DeviceCode = table.Column(maxLength: 200, nullable: false), - UserCode = table.Column(maxLength: 200, nullable: false), - SubjectId = table.Column(maxLength: 200, nullable: true), - ClientId = table.Column(maxLength: 200, nullable: false), - CreationTime = table.Column(nullable: false), - Expiration = table.Column(nullable: false), - Data = table.Column(maxLength: 50000, nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_DeviceCodes", x => x.UserCode); - }); - - migrationBuilder.CreateIndex( - name: "IX_PersistedGrants_SubjectId_ClientId_Type_Expiration", - table: "PersistedGrants", - columns: new[] { "SubjectId", "ClientId", "Type", "Expiration" }); - - migrationBuilder.CreateIndex( - name: "IX_DeviceCodes_DeviceCode", - table: "DeviceCodes", - column: "DeviceCode", - unique: true); - - migrationBuilder.CreateIndex( - name: "IX_DeviceCodes_Expiration", - table: "DeviceCodes", - column: "Expiration"); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "DeviceCodes"); - - migrationBuilder.DropIndex( - name: "IX_PersistedGrants_SubjectId_ClientId_Type_Expiration", - table: "PersistedGrants"); - - migrationBuilder.CreateIndex( - name: "IX_PersistedGrants_SubjectId_ClientId_Type", - table: "PersistedGrants", - columns: new[] { "SubjectId", "ClientId", "Type" }); - } - } -} diff --git a/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/PersistedGrantDbContextModelSnapshot.cs b/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/PersistedGrantDbContextModelSnapshot.cs deleted file mode 100644 index faae5d5..0000000 --- a/Nop.Plugin.Api/Migrations/IdentityServer/PersistedGrantDb/PersistedGrantDbContextModelSnapshot.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -using System; -using IdentityServer4.EntityFramework.DbContexts; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -namespace Nop.Plugin.Api.Migrations.IdentityServer.PersitedGrantDb -{ - [DbContext(typeof(PersistedGrantDbContext))] - partial class PersistedGrantDbContextModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "2.1.11-servicing-32099") - .HasAnnotation("Relational:MaxIdentifierLength", 128) - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b => - { - b.Property("UserCode") - .ValueGeneratedOnAdd() - .HasMaxLength(200); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200); - - b.Property("CreationTime"); - - b.Property("Data") - .IsRequired() - .HasMaxLength(50000); - - b.Property("DeviceCode") - .IsRequired() - .HasMaxLength(200); - - b.Property("Expiration") - .IsRequired(); - - b.Property("SubjectId") - .HasMaxLength(200); - - b.HasKey("UserCode"); - - b.HasIndex("DeviceCode") - .IsUnique(); - - b.HasIndex("Expiration"); - - b.ToTable("DeviceCodes"); - }); - - modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => - { - b.Property("Key") - .HasMaxLength(200); - - b.Property("ClientId") - .IsRequired() - .HasMaxLength(200); - - b.Property("CreationTime"); - - b.Property("Data") - .IsRequired() - .HasMaxLength(50000); - - b.Property("Expiration"); - - b.Property("SubjectId") - .HasMaxLength(200); - - b.Property("Type") - .IsRequired() - .HasMaxLength(50); - - b.HasKey("Key"); - - b.HasIndex("SubjectId", "ClientId", "Type", "Expiration"); - - b.ToTable("PersistedGrants"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/Nop.Plugin.Api/ModelBinders/JsonModelBinder.cs b/Nop.Plugin.Api/ModelBinders/JsonModelBinder.cs index 7b60a8e..253ce64 100644 --- a/Nop.Plugin.Api/ModelBinders/JsonModelBinder.cs +++ b/Nop.Plugin.Api/ModelBinders/JsonModelBinder.cs @@ -1,25 +1,24 @@ -using Nop.Plugin.Api.Attributes; -using Nop.Plugin.Api.Delta; -using Nop.Plugin.Api.Helpers; -using Nop.Plugin.Api.Validators; -using Nop.Services.Localization; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Nop.Plugin.Api.Attributes; +using Nop.Plugin.Api.Delta; +using Nop.Plugin.Api.Helpers; +using Nop.Plugin.Api.Validators; +using Nop.Services.Localization; namespace Nop.Plugin.Api.ModelBinders { - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.ModelBinding; - using System; - public class JsonModelBinder : IModelBinder where T : class, new() { private readonly IJsonHelper _jsonHelper; - private readonly ILocalizationService _localizationService; private readonly int _languageId; + private readonly ILocalizationService _localizationService; public JsonModelBinder(IJsonHelper jsonHelper, ILocalizationService localizationService, ILanguageService languageService) { @@ -56,12 +55,12 @@ public Task BindModelAsync(ModelBindingContext bindingContext) if (routeDataId != null) { - // Here we insert the route data id in the value paires. + // Here we insert the route data id in the value pairs. // If id is contained in the category json body the one from the route data is used instead. - InsertIdInTheValuePaires(propertyValuePairs, routeDataId); + InsertIdInTheValuePairs(propertyValuePairs, routeDataId); } - // We need to call this method here so it will be certain that the routeDataId will be in the propertyValuePaires + // We need to call this method here so it will be certain that the routeDataId will be in the propertyValuePairs // when the request is PUT. ValidateValueTypes(bindingContext, propertyValuePairs); @@ -103,7 +102,7 @@ private Dictionary GetPropertyValuePairs(ModelBindingContext bin result = _jsonHelper.GetRequestJsonDictionaryFromStream(bindingContext.HttpContext.Request.Body, true); var rootPropertyName = _jsonHelper.GetRootPropertyName(); - result = (Dictionary)result[rootPropertyName]; + result = (Dictionary) result[rootPropertyName]; } catch (Exception ex) { @@ -126,14 +125,14 @@ private object GetRouteDataId(ActionContext actionContext) return routeDataId; } - private void ValidateValueTypes(ModelBindingContext bindingContext, Dictionary propertyValuePaires) + private void ValidateValueTypes(ModelBindingContext bindingContext, Dictionary propertyValuePairs) { var errors = new Dictionary(); // Validate if the property value pairs passed maches the type. var typeValidator = new TypeValidator(); - if (!typeValidator.IsValid(propertyValuePaires)) + if (!typeValidator.IsValid(propertyValuePairs)) { foreach (var invalidProperty in typeValidator.InvalidProperties) { @@ -145,7 +144,7 @@ private void ValidateValueTypes(ModelBindingContext bindingContext, Dictionary 0) { foreach (var error in errors) @@ -155,7 +154,7 @@ private void ValidateValueTypes(ModelBindingContext bindingContext, Dictionary propertyValuePaires, T dto) + private void ValidateModel(ModelBindingContext bindingContext, Dictionary propertyValuePairs, T dto) { // this method validates each property by checking if it has an attribute that inherits from BaseValidationAttribute // these attribtues are different than FluentValidation attributes, so they need to be validated manually @@ -188,16 +187,16 @@ private void ValidateModel(ModelBindingContext bindingContext, Dictionary propertyValuePaires, object requestId) + private void InsertIdInTheValuePairs(IDictionary propertyValuePairs, object requestId) { - if (propertyValuePaires.ContainsKey("id")) + if (propertyValuePairs.ContainsKey("id")) { - propertyValuePaires["id"] = requestId; + propertyValuePairs["id"] = requestId; } else { - propertyValuePaires.Add("id", requestId); + propertyValuePairs.Add("id", requestId); } } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/ModelBinders/ParametersModelBinder.cs b/Nop.Plugin.Api/ModelBinders/ParametersModelBinder.cs index 1787e44..a0ef9ae 100644 --- a/Nop.Plugin.Api/ModelBinders/ParametersModelBinder.cs +++ b/Nop.Plugin.Api/ModelBinders/ParametersModelBinder.cs @@ -1,12 +1,11 @@ -using Nop.Plugin.Api.Converters; +using System; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Nop.Plugin.Api.Converters; namespace Nop.Plugin.Api.ModelBinders { - using System; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc.ModelBinding; - public class ParametersModelBinder : IModelBinder where T : class, new() { private readonly IObjectConverter _objectConverter; @@ -15,14 +14,14 @@ public ParametersModelBinder(IObjectConverter objectConverter) { _objectConverter = objectConverter; } - + public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } - + if (bindingContext.HttpContext.Request.QueryString.HasValue) { var queryParameters = bindingContext.HttpContext.Request.Query.ToDictionary(pair => pair.Key, pair => pair.Value.ToString()); @@ -40,4 +39,4 @@ public Task BindModelAsync(ModelBindingContext bindingContext) return Task.CompletedTask; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/Authentication/TokenRequest.cs b/Nop.Plugin.Api/Models/Authentication/TokenRequest.cs new file mode 100644 index 0000000..d31ac17 --- /dev/null +++ b/Nop.Plugin.Api/Models/Authentication/TokenRequest.cs @@ -0,0 +1,9 @@ +namespace Nop.Plugin.Api.Models.Authentication +{ + public class TokenRequest + { + public string Username { get; set; } + + public string Password { get; set; } + } +} diff --git a/Nop.Plugin.Api/Models/Authentication/TokenResponse.cs b/Nop.Plugin.Api/Models/Authentication/TokenResponse.cs new file mode 100644 index 0000000..25915fb --- /dev/null +++ b/Nop.Plugin.Api/Models/Authentication/TokenResponse.cs @@ -0,0 +1,31 @@ +using Newtonsoft.Json; + +namespace Nop.Plugin.Api.Models.Authentication +{ + public class TokenResponse + { + public TokenResponse(string errorDescription) + { + ErrorDescription = errorDescription; + } + + public TokenResponse(string accessToken, long expiresInSeconds, string tokenType = "Bearer") + { + AccessToken = accessToken; + ExpiresInSeconds = expiresInSeconds; + TokenType = tokenType; + } + + [JsonProperty("access_token")] + public string AccessToken { get; set; } + + [JsonProperty("token_type")] + public string TokenType { get; set; } = "Bearer"; + + [JsonProperty("expires_in")] + public long ExpiresInSeconds { get; set; } + + [JsonProperty("error_description")] + public string ErrorDescription { get; set; } + } +} diff --git a/Nop.Plugin.Api/Models/CategoriesParameters/BaseCategoriesParametersModel.cs b/Nop.Plugin.Api/Models/CategoriesParameters/BaseCategoriesParametersModel.cs index 2a041da..472aed2 100644 --- a/Nop.Plugin.Api/Models/CategoriesParameters/BaseCategoriesParametersModel.cs +++ b/Nop.Plugin.Api/Models/CategoriesParameters/BaseCategoriesParametersModel.cs @@ -17,43 +17,43 @@ public BaseCategoriesParametersModel() } /// - /// Show categories created after date (format: 2008-12-31 03:00) + /// Show categories created after date (format: 2008-12-31 03:00) /// [JsonProperty("created_at_min")] public DateTime? CreatedAtMin { get; set; } /// - /// Show categories created before date (format: 2008-12-31 03:00) + /// Show categories created before date (format: 2008-12-31 03:00) /// [JsonProperty("created_at_max")] public DateTime? CreatedAtMax { get; set; } /// - /// Show categories last updated after date (format: 2008-12-31 03:00) + /// Show categories last updated after date (format: 2008-12-31 03:00) /// [JsonProperty("updated_at_min")] public DateTime? UpdatedAtMin { get; set; } /// - /// Show categories last updated before date (format: 2008-12-31 03:00) + /// Show categories last updated before date (format: 2008-12-31 03:00) /// [JsonProperty("updated_at_max")] public DateTime? UpdatedAtMax { get; set; } /// - ///
    - ///
  • published - Show only published categories
  • - ///
  • unpublished - Show only unpublished categories
  • - ///
  • any - Show all categories(default)
  • - ///
+ ///
    + ///
  • published - Show only published categories
  • + ///
  • unpublished - Show only unpublished categories
  • + ///
  • any - Show all categories(default)
  • + ///
///
[JsonProperty("published_status")] public bool? PublishedStatus { get; set; } /// - /// Show only the categories to which the product is mapped to + /// Show only the categories to which the product is mapped to /// [JsonProperty("product_id")] public int? ProductId { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/CategoriesParameters/CategoriesCountParametersModel.cs b/Nop.Plugin.Api/Models/CategoriesParameters/CategoriesCountParametersModel.cs index 991acc9..83aa730 100644 --- a/Nop.Plugin.Api/Models/CategoriesParameters/CategoriesCountParametersModel.cs +++ b/Nop.Plugin.Api/Models/CategoriesParameters/CategoriesCountParametersModel.cs @@ -1,11 +1,11 @@ -using Nop.Plugin.Api.ModelBinders; +using Microsoft.AspNetCore.Mvc; +using Nop.Plugin.Api.ModelBinders; + namespace Nop.Plugin.Api.Models.CategoriesParameters { - using Microsoft.AspNetCore.Mvc; - [ModelBinder(typeof(ParametersModelBinder))] public class CategoriesCountParametersModel : BaseCategoriesParametersModel { // Nothing special here, created just for clarity. } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/CategoriesParameters/CategoriesParametersModel.cs b/Nop.Plugin.Api/Models/CategoriesParameters/CategoriesParametersModel.cs index 53b60cb..2dcefe7 100644 --- a/Nop.Plugin.Api/Models/CategoriesParameters/CategoriesParametersModel.cs +++ b/Nop.Plugin.Api/Models/CategoriesParameters/CategoriesParametersModel.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.ModelBinders; -using Microsoft.AspNetCore.Mvc; namespace Nop.Plugin.Api.Models.CategoriesParameters { @@ -13,40 +13,40 @@ public class CategoriesParametersModel : BaseCategoriesParametersModel public CategoriesParametersModel() { Ids = null; - Limit = Configurations.DefaultLimit; - Page = Configurations.DefaultPageValue; - SinceId = Configurations.DefaultSinceId; + Limit = Constants.Configurations.DefaultLimit; + Page = Constants.Configurations.DefaultPageValue; + SinceId = Constants.Configurations.DefaultSinceId; Fields = string.Empty; } /// - /// A comma-separated list of category ids + /// A comma-separated list of category ids /// [JsonProperty("ids")] public List Ids { get; set; } /// - /// Amount of results (default: 50) (maximum: 250) + /// Amount of results (default: 50) (maximum: 250) /// [JsonProperty("limit")] public int Limit { get; set; } /// - /// Page to show (default: 1) + /// Page to show (default: 1) /// [JsonProperty("page")] public int Page { get; set; } /// - /// Restrict results to after the specified ID + /// Restrict results to after the specified ID /// [JsonProperty("since_id")] public int SinceId { get; set; } /// - /// comma-separated list of fields to include in the response + /// comma-separated list of fields to include in the response /// [JsonProperty("fields")] public string Fields { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ClientApiModel.cs b/Nop.Plugin.Api/Models/ClientApiModel.cs deleted file mode 100644 index 243c0c8..0000000 --- a/Nop.Plugin.Api/Models/ClientApiModel.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace Nop.Plugin.Api.Models -{ - public class ClientApiModel - { - - public int Id { get; set; } - public string ClientName { get; set; } - - public string ClientId - { - get; - set; - } - - public string ClientSecret - { - get; - set; - } - - public string RedirectUrl { get; set; } - - public int AccessTokenLifetime - { - get;set; - } - - public int RefreshTokenLifetime - { - get;set; - } - - public bool Enabled { get; set; } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Models/CustomersParameters/CustomersParametersModel.cs b/Nop.Plugin.Api/Models/CustomersParameters/CustomersParametersModel.cs index b131ce5..f2c0b87 100644 --- a/Nop.Plugin.Api/Models/CustomersParameters/CustomersParametersModel.cs +++ b/Nop.Plugin.Api/Models/CustomersParameters/CustomersParametersModel.cs @@ -1,20 +1,19 @@ using System; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.ModelBinders; namespace Nop.Plugin.Api.Models.CustomersParameters { - using Microsoft.AspNetCore.Mvc; - // JsonProperty is used only for swagger [ModelBinder(typeof(ParametersModelBinder))] public class CustomersParametersModel { public CustomersParametersModel() { - Limit = Configurations.DefaultLimit; - Page = Configurations.DefaultPageValue; + Limit = Constants.Configurations.DefaultLimit; + Page = Constants.Configurations.DefaultPageValue; SinceId = 0; Fields = string.Empty; CreatedAtMax = null; @@ -22,39 +21,39 @@ public CustomersParametersModel() } /// - /// Amount of results (default: 50) (maximum: 250) + /// Amount of results (default: 50) (maximum: 250) /// [JsonProperty("limit")] public int Limit { get; set; } /// - /// Page to show (default: 1) + /// Page to show (default: 1) /// [JsonProperty("page")] public int Page { get; set; } /// - /// Restrict results to after the specified ID + /// Restrict results to after the specified ID /// [JsonProperty("since_id")] public int SinceId { get; set; } /// - /// Comma-separated list of fields to include in the response + /// Comma-separated list of fields to include in the response /// [JsonProperty("fields")] public string Fields { get; set; } /// - /// Show customers created after date (format: 2008-12-31 03:00) + /// Show customers created after date (format: 2008-12-31 03:00) /// [JsonProperty("created_at_min")] public DateTime? CreatedAtMin { get; set; } /// - /// Show customers created before date (format: 2008-12-31 03:00) + /// Show customers created before date (format: 2008-12-31 03:00) /// [JsonProperty("created_at_max")] public DateTime? CreatedAtMax { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/CustomersParameters/CustomersSearchParametersModel.cs b/Nop.Plugin.Api/Models/CustomersParameters/CustomersSearchParametersModel.cs index 77fcc3d..c4c58c8 100644 --- a/Nop.Plugin.Api/Models/CustomersParameters/CustomersSearchParametersModel.cs +++ b/Nop.Plugin.Api/Models/CustomersParameters/CustomersSearchParametersModel.cs @@ -1,11 +1,10 @@ -using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.ModelBinders; namespace Nop.Plugin.Api.Models.CustomersParameters { - using Microsoft.AspNetCore.Mvc; - // JsonProperty is used only for swagger [ModelBinder(typeof(ParametersModelBinder))] public class CustomersSearchParametersModel @@ -14,39 +13,39 @@ public CustomersSearchParametersModel() { Order = "Id"; Query = string.Empty; - Page = Configurations.DefaultPageValue; - Limit = Configurations.DefaultLimit; + Page = Constants.Configurations.DefaultPageValue; + Limit = Constants.Configurations.DefaultLimit; Fields = string.Empty; } /// - /// Field and direction to order results by (default: id DESC) + /// Field and direction to order results by (default: id DESC) /// [JsonProperty("order")] public string Order { get; set; } /// - /// Text to search customers + /// Text to search customers /// [JsonProperty("query")] public string Query { get; set; } /// - /// Page to show (default: 1) + /// Page to show (default: 1) /// [JsonProperty("page")] public int Page { get; set; } /// - /// Amount of results (default: 50) (maximum: 250) + /// Amount of results (default: 50) (maximum: 250) /// [JsonProperty("limit")] public int Limit { get; set; } /// - /// Comma-separated list of fields to include in the response + /// Comma-separated list of fields to include in the response /// [JsonProperty("fields")] public string Fields { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/DefaultWeApiErrorsModel.cs b/Nop.Plugin.Api/Models/DefaultWeApiErrorsModel.cs deleted file mode 100644 index c7b9a2a..0000000 --- a/Nop.Plugin.Api/Models/DefaultWeApiErrorsModel.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Nop.Plugin.Api.Models -{ - public class DefaultWeApiErrorsModel - { - public string Message { get; set; } - public string MessageDetail { get; set; } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Models/DefaultWebApiErrorsModel.cs b/Nop.Plugin.Api/Models/DefaultWebApiErrorsModel.cs new file mode 100644 index 0000000..1e55037 --- /dev/null +++ b/Nop.Plugin.Api/Models/DefaultWebApiErrorsModel.cs @@ -0,0 +1,9 @@ +namespace Nop.Plugin.Api.Models +{ + public class DefaultWebApiErrorsModel + { + public string Message { get; set; } + + public string MessageDetail { get; set; } + } +} diff --git a/Nop.Plugin.Api/Models/ManufacturersParameters/BaseManufacturersParametersModel.cs b/Nop.Plugin.Api/Models/ManufacturersParameters/BaseManufacturersParametersModel.cs index d173a99..a578519 100644 --- a/Nop.Plugin.Api/Models/ManufacturersParameters/BaseManufacturersParametersModel.cs +++ b/Nop.Plugin.Api/Models/ManufacturersParameters/BaseManufacturersParametersModel.cs @@ -17,43 +17,43 @@ public BaseManufacturersParametersModel() } /// - /// Show categories created after date (format: 2008-12-31 03:00) + /// Show categories created after date (format: 2008-12-31 03:00) /// [JsonProperty("created_at_min")] public DateTime? CreatedAtMin { get; set; } /// - /// Show categories created before date (format: 2008-12-31 03:00) + /// Show categories created before date (format: 2008-12-31 03:00) /// [JsonProperty("created_at_max")] public DateTime? CreatedAtMax { get; set; } /// - /// Show categories last updated after date (format: 2008-12-31 03:00) + /// Show categories last updated after date (format: 2008-12-31 03:00) /// [JsonProperty("updated_at_min")] public DateTime? UpdatedAtMin { get; set; } /// - /// Show categories last updated before date (format: 2008-12-31 03:00) + /// Show categories last updated before date (format: 2008-12-31 03:00) /// [JsonProperty("updated_at_max")] public DateTime? UpdatedAtMax { get; set; } /// - ///
    - ///
  • published - Show only published categories
  • - ///
  • unpublished - Show only unpublished categories
  • - ///
  • any - Show all categories(default)
  • - ///
+ ///
    + ///
  • published - Show only published categories
  • + ///
  • unpublished - Show only unpublished categories
  • + ///
  • any - Show all categories(default)
  • + ///
///
[JsonProperty("published_status")] public bool? PublishedStatus { get; set; } /// - /// Show only the categories to which the product is mapped to + /// Show only the categories to which the product is mapped to /// [JsonProperty("product_id")] public int? ProductId { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ManufacturersParameters/ManufacturersCountParametersModel.cs b/Nop.Plugin.Api/Models/ManufacturersParameters/ManufacturersCountParametersModel.cs index 87bf48c..eb805d9 100644 --- a/Nop.Plugin.Api/Models/ManufacturersParameters/ManufacturersCountParametersModel.cs +++ b/Nop.Plugin.Api/Models/ManufacturersParameters/ManufacturersCountParametersModel.cs @@ -1,11 +1,11 @@ -using Nop.Plugin.Api.ModelBinders; +using Microsoft.AspNetCore.Mvc; +using Nop.Plugin.Api.ModelBinders; + namespace Nop.Plugin.Api.Models.ManufacturersParameters { - using Microsoft.AspNetCore.Mvc; - [ModelBinder(typeof(ParametersModelBinder))] public class ManufacturersCountParametersModel : BaseManufacturersParametersModel { // Nothing special here, created just for clarity. } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ManufacturersParameters/ManufacturersParametersModel.cs b/Nop.Plugin.Api/Models/ManufacturersParameters/ManufacturersParametersModel.cs index c4ffa56..776e93f 100644 --- a/Nop.Plugin.Api/Models/ManufacturersParameters/ManufacturersParametersModel.cs +++ b/Nop.Plugin.Api/Models/ManufacturersParameters/ManufacturersParametersModel.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.ModelBinders; -using Microsoft.AspNetCore.Mvc; namespace Nop.Plugin.Api.Models.ManufacturersParameters { @@ -13,46 +13,46 @@ public class ManufacturersParametersModel : BaseManufacturersParametersModel public ManufacturersParametersModel() { Ids = null; - Limit = Configurations.DefaultLimit; - Page = Configurations.DefaultPageValue; - SinceId = Configurations.DefaultSinceId; + Limit = Constants.Configurations.DefaultLimit; + Page = Constants.Configurations.DefaultPageValue; + SinceId = Constants.Configurations.DefaultSinceId; Fields = string.Empty; } /// - /// A comma-separated list of manufacturer ids + /// A comma-separated list of manufacturer ids /// [JsonProperty("ids")] public List Ids { get; set; } /// - /// Amount of results (default: 50) (maximum: 250) + /// Amount of results (default: 50) (maximum: 250) /// [JsonProperty("limit")] public int Limit { get; set; } /// - /// Page to show (default: 1) + /// Page to show (default: 1) /// [JsonProperty("page")] public int Page { get; set; } /// - /// Restrict results to after the specified ID + /// Restrict results to after the specified ID /// [JsonProperty("since_id")] public int SinceId { get; set; } /// - /// comma-separated list of fields to include in the response + /// comma-separated list of fields to include in the response /// [JsonProperty("fields")] public string Fields { get; set; } /// - /// comma-separated list of fields to include in the response + /// comma-separated list of fields to include in the response /// [JsonProperty("languageid")] public int? LanguageId { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/NewsLetterSubscriptionsParameters/NewsLetterSubscriptionsParametersModel.cs b/Nop.Plugin.Api/Models/NewsLetterSubscriptionsParameters/NewsLetterSubscriptionsParametersModel.cs index a62b9e7..4bd7da8 100644 --- a/Nop.Plugin.Api/Models/NewsLetterSubscriptionsParameters/NewsLetterSubscriptionsParametersModel.cs +++ b/Nop.Plugin.Api/Models/NewsLetterSubscriptionsParameters/NewsLetterSubscriptionsParametersModel.cs @@ -1,20 +1,19 @@ using System; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.ModelBinders; -namespace Nop.Plugin.Api.Models.CustomersParameters +namespace Nop.Plugin.Api.Models.NewsLetterSubscriptionsParameters { - using Microsoft.AspNetCore.Mvc; - // JsonProperty is used only for swagger [ModelBinder(typeof(ParametersModelBinder))] public class NewsLetterSubscriptionsParametersModel { public NewsLetterSubscriptionsParametersModel() { - Limit = Configurations.DefaultLimit; - Page = Configurations.DefaultPageValue; + Limit = Constants.Configurations.DefaultLimit; + Page = Constants.Configurations.DefaultPageValue; SinceId = 0; Fields = string.Empty; CreatedAtMax = null; @@ -23,45 +22,45 @@ public NewsLetterSubscriptionsParametersModel() } /// - /// Amount of results (default: 50) (maximum: 250) + /// Amount of results (default: 50) (maximum: 250) /// [JsonProperty("limit")] public int Limit { get; set; } /// - /// Page to show (default: 1) + /// Page to show (default: 1) /// [JsonProperty("page")] public int Page { get; set; } /// - /// Restrict results to after the specified ID + /// Restrict results to after the specified ID /// [JsonProperty("since_id")] public int SinceId { get; set; } /// - /// Comma-separated list of fields to include in the response + /// Comma-separated list of fields to include in the response /// [JsonProperty("fields")] public string Fields { get; set; } /// - /// Show news letter subscriptions created after date (format: 2008-12-31 03:00) + /// Show news letter subscriptions created after date (format: 2008-12-31 03:00) /// [JsonProperty("created_at_min")] public DateTime? CreatedAtMin { get; set; } /// - /// Show news letter subscriptions created before date (format: 2008-12-31 03:00) + /// Show news letter subscriptions created before date (format: 2008-12-31 03:00) /// [JsonProperty("created_at_max")] public DateTime? CreatedAtMax { get; set; } /// - /// Whether should return only active news letter subscriptions + /// Whether should return only active news letter subscriptions /// [JsonProperty("only_active")] public bool? OnlyActive { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/OrderItemsParameters/OrderItemsParametersModel.cs b/Nop.Plugin.Api/Models/OrderItemsParameters/OrderItemsParametersModel.cs index 6d79a81..f022aa8 100644 --- a/Nop.Plugin.Api/Models/OrderItemsParameters/OrderItemsParametersModel.cs +++ b/Nop.Plugin.Api/Models/OrderItemsParameters/OrderItemsParametersModel.cs @@ -1,22 +1,21 @@ -using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.ModelBinders; namespace Nop.Plugin.Api.Models.OrderItemsParameters { - using Microsoft.AspNetCore.Mvc; - [ModelBinder(typeof(ParametersModelBinder))] public class OrderItemsParametersModel { public OrderItemsParametersModel() { - Limit = Configurations.DefaultLimit; - Page = Configurations.DefaultPageValue; + Limit = Constants.Configurations.DefaultLimit; + Page = Constants.Configurations.DefaultPageValue; SinceId = 0; Fields = string.Empty; } - + [JsonProperty("limit")] public int Limit { get; set; } @@ -29,4 +28,4 @@ public OrderItemsParametersModel() [JsonProperty("fields")] public string Fields { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/OrdersParameters/BaseOrdersParametersModel.cs b/Nop.Plugin.Api/Models/OrdersParameters/BaseOrdersParametersModel.cs index a6709d7..1fadf16 100644 --- a/Nop.Plugin.Api/Models/OrdersParameters/BaseOrdersParametersModel.cs +++ b/Nop.Plugin.Api/Models/OrdersParameters/BaseOrdersParametersModel.cs @@ -20,57 +20,57 @@ public BaseOrdersParametersModel() } /// - /// Show orders created after date (format: 2008-12-31 03:00) + /// Show orders created after date (format: 2008-12-31 03:00) /// [JsonProperty("created_at_min")] public DateTime? CreatedAtMin { get; set; } /// - /// Show orders created before date(format: 2008-12-31 03:00) + /// Show orders created before date(format: 2008-12-31 03:00) /// [JsonProperty("created_at_max")] public DateTime? CreatedAtMax { get; set; } /// - ///
    - ///
  • pending - All open orders (default)
  • - ///
  • processing - Show only payed or shipped orders
  • - ///
  • complete - Show only the complete orders
  • - ///
  • cancelled - Show only cancelled orders
  • - ///
+ ///
    + ///
  • pending - All open orders (default)
  • + ///
  • processing - Show only payed or shipped orders
  • + ///
  • complete - Show only the complete orders
  • + ///
  • cancelled - Show only cancelled orders
  • + ///
///
[JsonProperty("status")] public OrderStatus? Status { get; set; } /// - ///
    - ///
  • pending - Show all orders that are not payed
  • - ///
  • authorized - Show all orders that are authorized by the payment provider
  • - ///
  • paid - Show the paid orders
  • - ///
  • partiallyRefunded - Show only the partially refunded orders
  • - ///
  • refunded - Show only the refunded orders
  • - ///
  • voided - Show only the voided orders
  • - ///
+ ///
    + ///
  • pending - Show all orders that are not payed
  • + ///
  • authorized - Show all orders that are authorized by the payment provider
  • + ///
  • paid - Show the paid orders
  • + ///
  • partiallyRefunded - Show only the partially refunded orders
  • + ///
  • refunded - Show only the refunded orders
  • + ///
  • voided - Show only the voided orders
  • + ///
///
[JsonProperty("payment_status")] public PaymentStatus? PaymentStatus { get; set; } /// - ///
    - ///
  • shippingNotRequired - Show only the orders that do not require shipping
  • - ///
  • notYetShipped - Show only the orders that are not shipped
  • - ///
  • partiallyShipped - Show only the orders that are partially shippied
  • - ///
  • shipped - Show only the shipped orders
  • - ///
  • delivered - Show only the delivered orders
  • - ///
+ ///
    + ///
  • shippingNotRequired - Show only the orders that do not require shipping
  • + ///
  • notYetShipped - Show only the orders that are not shipped
  • + ///
  • partiallyShipped - Show only the orders that are partially shippied
  • + ///
  • shipped - Show only the shipped orders
  • + ///
  • delivered - Show only the delivered orders
  • + ///
///
[JsonProperty("shipping_status")] public ShippingStatus? ShippingStatus { get; set; } /// - /// Show all the orders for this customer + /// Show all the orders for this customer /// [JsonProperty("customer_id")] public int? CustomerId { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/OrdersParameters/OrdersCountParametersModel.cs b/Nop.Plugin.Api/Models/OrdersParameters/OrdersCountParametersModel.cs index ca7985f..1ce5f7e 100644 --- a/Nop.Plugin.Api/Models/OrdersParameters/OrdersCountParametersModel.cs +++ b/Nop.Plugin.Api/Models/OrdersParameters/OrdersCountParametersModel.cs @@ -1,12 +1,11 @@ -using Nop.Plugin.Api.ModelBinders; +using Microsoft.AspNetCore.Mvc; +using Nop.Plugin.Api.ModelBinders; namespace Nop.Plugin.Api.Models.OrdersParameters { - using Microsoft.AspNetCore.Mvc; - [ModelBinder(typeof(ParametersModelBinder))] public class OrdersCountParametersModel : BaseOrdersParametersModel { // Nothing special here, created just for clarity. } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/OrdersParameters/OrdersParametersModel.cs b/Nop.Plugin.Api/Models/OrdersParameters/OrdersParametersModel.cs index b02c1e0..e19a3c9 100644 --- a/Nop.Plugin.Api/Models/OrdersParameters/OrdersParametersModel.cs +++ b/Nop.Plugin.Api/Models/OrdersParameters/OrdersParametersModel.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.ModelBinders; namespace Nop.Plugin.Api.Models.OrdersParameters { - using Microsoft.AspNetCore.Mvc; - // JsonProperty is used only for swagger [ModelBinder(typeof(ParametersModelBinder))] public class OrdersParametersModel : BaseOrdersParametersModel @@ -14,40 +13,40 @@ public class OrdersParametersModel : BaseOrdersParametersModel public OrdersParametersModel() { Ids = null; - Limit = Configurations.DefaultLimit; - Page = Configurations.DefaultPageValue; - SinceId = Configurations.DefaultSinceId; + Limit = Constants.Configurations.DefaultLimit; + Page = Constants.Configurations.DefaultPageValue; + SinceId = Constants.Configurations.DefaultSinceId; Fields = string.Empty; } /// - /// A comma-separated list of order ids + /// A comma-separated list of order ids /// [JsonProperty("ids")] public List Ids { get; set; } /// - /// Amount of results (default: 50) (maximum: 250) + /// Amount of results (default: 50) (maximum: 250) /// [JsonProperty("limit")] public int Limit { get; set; } /// - /// Page to show (default: 1) + /// Page to show (default: 1) /// [JsonProperty("page")] public int Page { get; set; } /// - /// Restrict results to after the specified ID + /// Restrict results to after the specified ID /// [JsonProperty("since_id")] public int SinceId { get; set; } /// - /// comma-separated list of fields to include in the response + /// comma-separated list of fields to include in the response /// [JsonProperty("fields")] public string Fields { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ProductAttributesParameters/ProductAttributesParametersModel.cs b/Nop.Plugin.Api/Models/ProductAttributesParameters/ProductAttributesParametersModel.cs index 690dcbc..050894f 100644 --- a/Nop.Plugin.Api/Models/ProductAttributesParameters/ProductAttributesParametersModel.cs +++ b/Nop.Plugin.Api/Models/ProductAttributesParameters/ProductAttributesParametersModel.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.ModelBinders; -namespace Nop.Plugin.Api.Models.ProductAttributes +namespace Nop.Plugin.Api.Models.ProductAttributesParameters { // JsonProperty is used only for swagger [ModelBinder(typeof(ParametersModelBinder))] @@ -13,40 +13,40 @@ public class ProductAttributesParametersModel public ProductAttributesParametersModel() { Ids = null; - Limit = Configurations.DefaultLimit; - Page = Configurations.DefaultPageValue; - SinceId = Configurations.DefaultSinceId; + Limit = Constants.Configurations.DefaultLimit; + Page = Constants.Configurations.DefaultPageValue; + SinceId = Constants.Configurations.DefaultSinceId; Fields = string.Empty; } /// - /// A comma-separated list of category ids + /// A comma-separated list of category ids /// [JsonProperty("ids")] public List Ids { get; set; } /// - /// Amount of results (default: 50) (maximum: 250) + /// Amount of results (default: 50) (maximum: 250) /// [JsonProperty("limit")] public int Limit { get; set; } /// - /// Page to show (default: 1) + /// Page to show (default: 1) /// [JsonProperty("page")] public int Page { get; set; } /// - /// Restrict results to after the specified ID + /// Restrict results to after the specified ID /// [JsonProperty("since_id")] public int SinceId { get; set; } /// - /// comma-separated list of fields to include in the response + /// comma-separated list of fields to include in the response /// [JsonProperty("fields")] public string Fields { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ProductCategoryMappingsParameters/BaseCategoryMappingsParametersModel.cs b/Nop.Plugin.Api/Models/ProductCategoryMappingsParameters/BaseCategoryMappingsParametersModel.cs index 5330a03..23e9432 100644 --- a/Nop.Plugin.Api/Models/ProductCategoryMappingsParameters/BaseCategoryMappingsParametersModel.cs +++ b/Nop.Plugin.Api/Models/ProductCategoryMappingsParameters/BaseCategoryMappingsParametersModel.cs @@ -6,15 +6,15 @@ namespace Nop.Plugin.Api.Models.ProductCategoryMappingsParameters public class BaseCategoryMappingsParametersModel { /// - /// Show all the product-category mappings for this product + /// Show all the product-category mappings for this product /// [JsonProperty("product_id")] public int? ProductId { get; set; } /// - /// Show all the product-category mappings for this category + /// Show all the product-category mappings for this category /// [JsonProperty("category_id")] - public int? CategoryId { get; set; } + public int? CategoryId { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ProductCategoryMappingsParameters/ProductCategoryMappingsCountParametersModel.cs b/Nop.Plugin.Api/Models/ProductCategoryMappingsParameters/ProductCategoryMappingsCountParametersModel.cs index 576322d..eb1d253 100644 --- a/Nop.Plugin.Api/Models/ProductCategoryMappingsParameters/ProductCategoryMappingsCountParametersModel.cs +++ b/Nop.Plugin.Api/Models/ProductCategoryMappingsParameters/ProductCategoryMappingsCountParametersModel.cs @@ -1,12 +1,11 @@ -using Nop.Plugin.Api.ModelBinders; +using Microsoft.AspNetCore.Mvc; +using Nop.Plugin.Api.ModelBinders; namespace Nop.Plugin.Api.Models.ProductCategoryMappingsParameters { - using Microsoft.AspNetCore.Mvc; - [ModelBinder(typeof(ParametersModelBinder))] public class ProductCategoryMappingsCountParametersModel : BaseCategoryMappingsParametersModel { // Nothing special here, created just for clarity. } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ProductCategoryMappingsParameters/ProductCategoryMappingsParametersModel.cs b/Nop.Plugin.Api/Models/ProductCategoryMappingsParameters/ProductCategoryMappingsParametersModel.cs index b5e84bb..901d7be 100644 --- a/Nop.Plugin.Api/Models/ProductCategoryMappingsParameters/ProductCategoryMappingsParametersModel.cs +++ b/Nop.Plugin.Api/Models/ProductCategoryMappingsParameters/ProductCategoryMappingsParametersModel.cs @@ -1,45 +1,44 @@ -using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.ModelBinders; namespace Nop.Plugin.Api.Models.ProductCategoryMappingsParameters { - using Microsoft.AspNetCore.Mvc; - // JsonProperty is used only for swagger [ModelBinder(typeof(ParametersModelBinder))] public class ProductCategoryMappingsParametersModel : BaseCategoryMappingsParametersModel { public ProductCategoryMappingsParametersModel() { - SinceId = Configurations.DefaultSinceId; - Page = Configurations.DefaultPageValue; - Limit = Configurations.DefaultLimit; + SinceId = Constants.Configurations.DefaultSinceId; + Page = Constants.Configurations.DefaultPageValue; + Limit = Constants.Configurations.DefaultLimit; Fields = string.Empty; } /// - /// Restrict results to after the specified ID + /// Restrict results to after the specified ID /// [JsonProperty("since_id")] public int SinceId { get; set; } /// - /// Page to show (default: 1) + /// Page to show (default: 1) /// [JsonProperty("page")] public int Page { get; set; } /// - /// Amount of results (default: 50) (maximum: 250) + /// Amount of results (default: 50) (maximum: 250) /// [JsonProperty("limit")] public int Limit { get; set; } /// - /// comma-separated list of fields to include in the response + /// comma-separated list of fields to include in the response /// [JsonProperty("fields")] public string Fields { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ProductManufacturerMappingsParameters/BaseManufacturerMappingsParametersModel.cs b/Nop.Plugin.Api/Models/ProductManufacturerMappingsParameters/BaseManufacturerMappingsParametersModel.cs index 6a87463..fa25a6f 100644 --- a/Nop.Plugin.Api/Models/ProductManufacturerMappingsParameters/BaseManufacturerMappingsParametersModel.cs +++ b/Nop.Plugin.Api/Models/ProductManufacturerMappingsParameters/BaseManufacturerMappingsParametersModel.cs @@ -6,15 +6,15 @@ namespace Nop.Plugin.Api.Models.ProductManufacturerMappingsParameters public class BaseManufacturerMappingsParametersModel { /// - /// Show all the product-manufacturer mappings for this product + /// Show all the product-manufacturer mappings for this product /// [JsonProperty("product_id")] public int? ProductId { get; set; } /// - /// Show all the product-manufacturer mappings for this manufacturer + /// Show all the product-manufacturer mappings for this manufacturer /// [JsonProperty("manufacturer_id")] - public int? ManufacturerId { get; set; } + public int? ManufacturerId { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ProductManufacturerMappingsParameters/ProductManufacturerMappingsCountParametersModel.cs b/Nop.Plugin.Api/Models/ProductManufacturerMappingsParameters/ProductManufacturerMappingsCountParametersModel.cs index 4f383b8..5dfdf05 100644 --- a/Nop.Plugin.Api/Models/ProductManufacturerMappingsParameters/ProductManufacturerMappingsCountParametersModel.cs +++ b/Nop.Plugin.Api/Models/ProductManufacturerMappingsParameters/ProductManufacturerMappingsCountParametersModel.cs @@ -1,12 +1,11 @@ -using Nop.Plugin.Api.ModelBinders; +using Microsoft.AspNetCore.Mvc; +using Nop.Plugin.Api.ModelBinders; namespace Nop.Plugin.Api.Models.ProductManufacturerMappingsParameters { - using Microsoft.AspNetCore.Mvc; - [ModelBinder(typeof(ParametersModelBinder))] public class ProductManufacturerMappingsCountParametersModel : BaseManufacturerMappingsParametersModel { // Nothing special here, created just for clarity. } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ProductManufacturerMappingsParameters/ProductManufacturerMappingsParametersModel.cs b/Nop.Plugin.Api/Models/ProductManufacturerMappingsParameters/ProductManufacturerMappingsParametersModel.cs index afc08e6..3995e5a 100644 --- a/Nop.Plugin.Api/Models/ProductManufacturerMappingsParameters/ProductManufacturerMappingsParametersModel.cs +++ b/Nop.Plugin.Api/Models/ProductManufacturerMappingsParameters/ProductManufacturerMappingsParametersModel.cs @@ -1,45 +1,44 @@ -using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.ModelBinders; namespace Nop.Plugin.Api.Models.ProductManufacturerMappingsParameters { - using Microsoft.AspNetCore.Mvc; - // JsonProperty is used only for swagger [ModelBinder(typeof(ParametersModelBinder))] public class ProductManufacturerMappingsParametersModel : BaseManufacturerMappingsParametersModel { public ProductManufacturerMappingsParametersModel() { - SinceId = Configurations.DefaultSinceId; - Page = Configurations.DefaultPageValue; - Limit = Configurations.DefaultLimit; + SinceId = Constants.Configurations.DefaultSinceId; + Page = Constants.Configurations.DefaultPageValue; + Limit = Constants.Configurations.DefaultLimit; Fields = string.Empty; } /// - /// Restrict results to after the specified ID + /// Restrict results to after the specified ID /// [JsonProperty("since_id")] public int SinceId { get; set; } /// - /// Page to show (default: 1) + /// Page to show (default: 1) /// [JsonProperty("page")] public int Page { get; set; } /// - /// Amount of results (default: 50) (maximum: 250) + /// Amount of results (default: 50) (maximum: 250) /// [JsonProperty("limit")] public int Limit { get; set; } /// - /// comma-separated list of fields to include in the response + /// comma-separated list of fields to include in the response /// [JsonProperty("fields")] public string Fields { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ProductSpecificationAttributesParameters/ProductSpecificationAttributesCountParametersModel.cs b/Nop.Plugin.Api/Models/ProductSpecificationAttributesParameters/ProductSpecificationAttributesCountParametersModel.cs index a48dc5e..f4b3445 100644 --- a/Nop.Plugin.Api/Models/ProductSpecificationAttributesParameters/ProductSpecificationAttributesCountParametersModel.cs +++ b/Nop.Plugin.Api/Models/ProductSpecificationAttributesParameters/ProductSpecificationAttributesCountParametersModel.cs @@ -2,27 +2,22 @@ using Newtonsoft.Json; using Nop.Plugin.Api.ModelBinders; -namespace Nop.Plugin.Api.Models.ProductSpecificationAttributes +namespace Nop.Plugin.Api.Models.ProductSpecificationAttributesParameters { // JsonProperty is used only for swagger - [ModelBinder(typeof(ParametersModelBinder))] - public class ProductSpecifcationAttributesCountParametersModel + [ModelBinder(typeof(ParametersModelBinder))] + public class ProductSpecificationAttributesCountParametersModel { - public ProductSpecifcationAttributesCountParametersModel() - { - - } - /// - /// Product Id + /// Product Id /// [JsonProperty("product_id")] public int ProductId { get; set; } /// - /// Specification Attribute Option Id + /// Specification Attribute Option Id /// [JsonProperty("specification_attribute_option_id")] public int SpecificationAttributeOptionId { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ProductSpecificationAttributesParameters/ProductSpecificationAttributesParametersModel.cs b/Nop.Plugin.Api/Models/ProductSpecificationAttributesParameters/ProductSpecificationAttributesParametersModel.cs index 7e86751..ce8ad6d 100644 --- a/Nop.Plugin.Api/Models/ProductSpecificationAttributesParameters/ProductSpecificationAttributesParametersModel.cs +++ b/Nop.Plugin.Api/Models/ProductSpecificationAttributesParameters/ProductSpecificationAttributesParametersModel.cs @@ -1,67 +1,67 @@ using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.ModelBinders; -namespace Nop.Plugin.Api.Models.ProductSpecificationAttributes +namespace Nop.Plugin.Api.Models.ProductSpecificationAttributesParameters { - [ModelBinder(typeof(ParametersModelBinder))] - public class ProductSpecifcationAttributesParametersModel + [ModelBinder(typeof(ParametersModelBinder))] + public class ProductSpecificationAttributesParametersModel { - public ProductSpecifcationAttributesParametersModel() + public ProductSpecificationAttributesParametersModel() { - Limit = Configurations.DefaultLimit; - Page = Configurations.DefaultPageValue; - SinceId = Configurations.DefaultSinceId; + Limit = Constants.Configurations.DefaultLimit; + Page = Constants.Configurations.DefaultPageValue; + SinceId = Constants.Configurations.DefaultSinceId; Fields = string.Empty; } /// - /// Product Id + /// Product Id /// [JsonProperty("product_id")] public int ProductId { get; set; } /// - /// Specification Attribute Option Id + /// Specification Attribute Option Id /// [JsonProperty("specification_attribute_option_id")] public int SpecificationAttributeOptionId { get; set; } /// - /// Allow Filtering + /// Allow Filtering /// [JsonProperty("allow_filtering")] public bool? AllowFiltering { get; set; } /// - /// Show on Product Page + /// Show on Product Page /// [JsonProperty("show_on_product_page")] public bool? ShowOnProductPage { get; set; } /// - /// Amount of results (default: 50) (maximum: 250) + /// Amount of results (default: 50) (maximum: 250) /// [JsonProperty("limit")] public int Limit { get; set; } /// - /// Page to show (default: 1) + /// Page to show (default: 1) /// [JsonProperty("page")] public int Page { get; set; } /// - /// Restrict results to after the specified ID + /// Restrict results to after the specified ID /// [JsonProperty("since_id")] public int SinceId { get; set; } /// - /// comma-separated list of fields to include in the response + /// comma-separated list of fields to include in the response /// [JsonProperty("fields")] public string Fields { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ProductsParameters/BaseProductsParametersModel.cs b/Nop.Plugin.Api/Models/ProductsParameters/BaseProductsParametersModel.cs index 93c187c..bcfb5f1 100644 --- a/Nop.Plugin.Api/Models/ProductsParameters/BaseProductsParametersModel.cs +++ b/Nop.Plugin.Api/Models/ProductsParameters/BaseProductsParametersModel.cs @@ -18,49 +18,49 @@ public BaseProductsParametersModel() } /// - /// Show products created after date (format: 2008-12-31 03:00) + /// Show products created after date (format: 2008-12-31 03:00) /// [JsonProperty("created_at_min")] public DateTime? CreatedAtMin { get; set; } /// - /// Show products created before date (format: 2008-12-31 03:00) + /// Show products created before date (format: 2008-12-31 03:00) /// [JsonProperty("created_at_max")] public DateTime? CreatedAtMax { get; set; } /// - /// Show products last updated after date (format: 2008-12-31 03:00) + /// Show products last updated after date (format: 2008-12-31 03:00) /// [JsonProperty("updated_at_min")] public DateTime? UpdatedAtMin { get; set; } /// - /// Show products last updated before date (format: 2008-12-31 03:00) + /// Show products last updated before date (format: 2008-12-31 03:00) /// [JsonProperty("updated_at_max")] public DateTime? UpdatedAtMax { get; set; } /// - ///
    - ///
  • published - Show only published products
  • - ///
  • unpublished - Show only unpublished products
  • - ///
  • any - Show all products (default)
  • - ///
+ ///
    + ///
  • published - Show only published products
  • + ///
  • unpublished - Show only unpublished products
  • + ///
  • any - Show all products (default)
  • + ///
///
[JsonProperty("published_status")] public bool? PublishedStatus { get; set; } /// - /// Filter by product vendor + /// Filter by product vendor /// [JsonProperty("vendor_name")] public string VendorName { get; set; } /// - /// Show only the products mapped to the specified category + /// Show only the products mapped to the specified category /// [JsonProperty("category_id")] public int? CategoryId { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ProductsParameters/ProductsCountParametersModel.cs b/Nop.Plugin.Api/Models/ProductsParameters/ProductsCountParametersModel.cs index c92d4fd..d3da3bd 100644 --- a/Nop.Plugin.Api/Models/ProductsParameters/ProductsCountParametersModel.cs +++ b/Nop.Plugin.Api/Models/ProductsParameters/ProductsCountParametersModel.cs @@ -1,12 +1,11 @@ -using Nop.Plugin.Api.ModelBinders; +using Microsoft.AspNetCore.Mvc; +using Nop.Plugin.Api.ModelBinders; namespace Nop.Plugin.Api.Models.ProductsParameters { - using Microsoft.AspNetCore.Mvc; - [ModelBinder(typeof(ParametersModelBinder))] public class ProductsCountParametersModel : BaseProductsParametersModel { // Nothing special here, created just for clarity. } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ProductsParameters/ProductsParametersModel.cs b/Nop.Plugin.Api/Models/ProductsParameters/ProductsParametersModel.cs index 081580f..f1dfac2 100644 --- a/Nop.Plugin.Api/Models/ProductsParameters/ProductsParametersModel.cs +++ b/Nop.Plugin.Api/Models/ProductsParameters/ProductsParametersModel.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.ModelBinders; namespace Nop.Plugin.Api.Models.ProductsParameters { - using Microsoft.AspNetCore.Mvc; - // JsonProperty is used only for swagger [ModelBinder(typeof(ParametersModelBinder))] public class ProductsParametersModel : BaseProductsParametersModel @@ -14,40 +13,40 @@ public class ProductsParametersModel : BaseProductsParametersModel public ProductsParametersModel() { Ids = null; - Limit = Configurations.DefaultLimit; - Page = Configurations.DefaultPageValue; - SinceId = Configurations.DefaultSinceId; + Limit = Constants.Configurations.DefaultLimit; + Page = Constants.Configurations.DefaultPageValue; + SinceId = Constants.Configurations.DefaultSinceId; Fields = string.Empty; } /// - /// A comma-separated list of order ids + /// A comma-separated list of order ids /// [JsonProperty("ids")] public List Ids { get; set; } /// - /// Amount of results (default: 50) (maximum: 250) + /// Amount of results (default: 50) (maximum: 250) /// [JsonProperty("limit")] public int Limit { get; set; } /// - /// Page to show (default: 1) + /// Page to show (default: 1) /// [JsonProperty("page")] public int Page { get; set; } /// - /// Restrict results to after the specified ID + /// Restrict results to after the specified ID /// [JsonProperty("since_id")] public int SinceId { get; set; } /// - /// comma-separated list of fields to include in the response + /// comma-separated list of fields to include in the response /// [JsonProperty("fields")] public string Fields { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ShoppingCartsParameters/BaseShoppingCartItemsParametersModel.cs b/Nop.Plugin.Api/Models/ShoppingCartsParameters/BaseShoppingCartItemsParametersModel.cs index 97ab0b9..4610fe7 100644 --- a/Nop.Plugin.Api/Models/ShoppingCartsParameters/BaseShoppingCartItemsParametersModel.cs +++ b/Nop.Plugin.Api/Models/ShoppingCartsParameters/BaseShoppingCartItemsParametersModel.cs @@ -1,6 +1,6 @@ using System; using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Models.ShoppingCartsParameters { @@ -13,51 +13,51 @@ public BaseShoppingCartItemsParametersModel() CreatedAtMax = null; UpdatedAtMin = null; UpdatedAtMax = null; - Limit = Configurations.DefaultLimit; - Page = Configurations.DefaultPageValue; + Limit = Constants.Configurations.DefaultLimit; + Page = Constants.Configurations.DefaultPageValue; Fields = string.Empty; } /// - /// Show shopping cart items created after date (format: 2008-12-31 03:00) + /// Show shopping cart items created after date (format: 2008-12-31 03:00) /// [JsonProperty("created_at_min")] public DateTime? CreatedAtMin { get; set; } /// - /// Show shopping cart items created before date (format: 2008-12-31 03:00) + /// Show shopping cart items created before date (format: 2008-12-31 03:00) /// [JsonProperty("created_at_max")] public DateTime? CreatedAtMax { get; set; } /// - /// Show shopping cart items updated after date (format: 2008-12-31 03:00) + /// Show shopping cart items updated after date (format: 2008-12-31 03:00) /// [JsonProperty("updated_at_min")] public DateTime? UpdatedAtMin { get; set; } /// - /// Show shopping cart items updated before date (format: 2008-12-31 03:00) + /// Show shopping cart items updated before date (format: 2008-12-31 03:00) /// [JsonProperty("updated_at_max")] public DateTime? UpdatedAtMax { get; set; } /// - /// Amount of results (default: 50) (maximum: 250) + /// Amount of results (default: 50) (maximum: 250) /// [JsonProperty("limit")] public int Limit { get; set; } /// - /// Page to show (default: 1) + /// Page to show (default: 1) /// [JsonProperty("page")] public int Page { get; set; } /// - /// comma-separated list of fields to include in the response + /// comma-separated list of fields to include in the response /// [JsonProperty("fields")] public string Fields { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ShoppingCartsParameters/ShoppingCartItemsForCustomerParametersModel.cs b/Nop.Plugin.Api/Models/ShoppingCartsParameters/ShoppingCartItemsForCustomerParametersModel.cs index 658374c..0babeb4 100644 --- a/Nop.Plugin.Api/Models/ShoppingCartsParameters/ShoppingCartItemsForCustomerParametersModel.cs +++ b/Nop.Plugin.Api/Models/ShoppingCartsParameters/ShoppingCartItemsForCustomerParametersModel.cs @@ -1,12 +1,11 @@ -using Nop.Plugin.Api.ModelBinders; +using Microsoft.AspNetCore.Mvc; +using Nop.Plugin.Api.ModelBinders; namespace Nop.Plugin.Api.Models.ShoppingCartsParameters { - using Microsoft.AspNetCore.Mvc; - [ModelBinder(typeof(ParametersModelBinder))] public class ShoppingCartItemsForCustomerParametersModel : BaseShoppingCartItemsParametersModel { // Nothing special here, created just for clarity. } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/ShoppingCartsParameters/ShoppingCartItemsParametersModel.cs b/Nop.Plugin.Api/Models/ShoppingCartsParameters/ShoppingCartItemsParametersModel.cs index 51c4074..99f9586 100644 --- a/Nop.Plugin.Api/Models/ShoppingCartsParameters/ShoppingCartItemsParametersModel.cs +++ b/Nop.Plugin.Api/Models/ShoppingCartsParameters/ShoppingCartItemsParametersModel.cs @@ -1,12 +1,11 @@ -using Nop.Plugin.Api.ModelBinders; +using Microsoft.AspNetCore.Mvc; +using Nop.Plugin.Api.ModelBinders; namespace Nop.Plugin.Api.Models.ShoppingCartsParameters { - using Microsoft.AspNetCore.Mvc; - [ModelBinder(typeof(ParametersModelBinder))] public class ShoppingCartItemsParametersModel : BaseShoppingCartItemsParametersModel { // Nothing special here, created just for clarity. } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/SpecificationAttributesParameters/SpecificationAttributesCountParametersModel.cs b/Nop.Plugin.Api/Models/SpecificationAttributesParameters/SpecificationAttributesCountParametersModel.cs index 3501aaa..1bfe6fc 100644 --- a/Nop.Plugin.Api/Models/SpecificationAttributesParameters/SpecificationAttributesCountParametersModel.cs +++ b/Nop.Plugin.Api/Models/SpecificationAttributesParameters/SpecificationAttributesCountParametersModel.cs @@ -1,16 +1,11 @@ using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; using Nop.Plugin.Api.ModelBinders; -namespace Nop.Plugin.Api.Models.SpecificationAttributes +namespace Nop.Plugin.Api.Models.SpecificationAttributesParameters { // JsonProperty is used only for swagger - [ModelBinder(typeof(ParametersModelBinder))] - public class SpecifcationAttributesCountParametersModel + [ModelBinder(typeof(ParametersModelBinder))] + public class SpecificationAttributesCountParametersModel { - public SpecifcationAttributesCountParametersModel() - { - - } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Models/SpecificationAttributesParameters/SpecificationAttributesParametersModel.cs b/Nop.Plugin.Api/Models/SpecificationAttributesParameters/SpecificationAttributesParametersModel.cs index 419dbff..7000317 100644 --- a/Nop.Plugin.Api/Models/SpecificationAttributesParameters/SpecificationAttributesParametersModel.cs +++ b/Nop.Plugin.Api/Models/SpecificationAttributesParameters/SpecificationAttributesParametersModel.cs @@ -1,42 +1,42 @@ using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.ModelBinders; -namespace Nop.Plugin.Api.Models.SpecificationAttributes +namespace Nop.Plugin.Api.Models.SpecificationAttributesParameters { - [ModelBinder(typeof(ParametersModelBinder))] - public class SpecifcationAttributesParametersModel + [ModelBinder(typeof(ParametersModelBinder))] + public class SpecificationAttributesParametersModel { - public SpecifcationAttributesParametersModel() + public SpecificationAttributesParametersModel() { - Limit = Configurations.DefaultLimit; - Page = Configurations.DefaultPageValue; - SinceId = Configurations.DefaultSinceId; + Limit = Constants.Configurations.DefaultLimit; + Page = Constants.Configurations.DefaultPageValue; + SinceId = Constants.Configurations.DefaultSinceId; } /// - /// Amount of results (default: 50) (maximum: 250) + /// Amount of results (default: 50) (maximum: 250) /// [JsonProperty("limit")] public int Limit { get; set; } /// - /// Page to show (default: 1) + /// Page to show (default: 1) /// [JsonProperty("page")] public int Page { get; set; } /// - /// comma-separated list of fields to include in the response + /// comma-separated list of fields to include in the response /// [JsonProperty("fields")] public string Fields { get; set; } /// - /// Restrict results to after the specified ID + /// Restrict results to after the specified ID /// [JsonProperty("since_id")] public int SinceId { get; set; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Nop.Plugin.Api.csproj b/Nop.Plugin.Api/Nop.Plugin.Api.csproj index fd54ba2..79002e1 100644 --- a/Nop.Plugin.Api/Nop.Plugin.Api.csproj +++ b/Nop.Plugin.Api/Nop.Plugin.Api.csproj @@ -1,83 +1,73 @@  - netcoreapp2.2 + netcoreapp3.1 + 0.0.1-local + $(BUILD_BUILDNUMBER) This plugin allows you to access/create Nop resources outside of the system + + + + Nop.Plugin.Api + Nop.Plugin.Api + Nop.Plugin.Api + true ..\..\Presentation\Nop.Web\Plugins\Nop.Plugin.Api $(OutputPath) - true ..\..\Presentation\Nop.Web\Plugins\Nop.Plugin.Api $(OutputPath) - true - - - - - - - - - - - - - - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - + - - - - - - + + + + + - + + + + + + + + Always + + + Always + + + Always + + + Always + - + - + + + + + + + \ No newline at end of file diff --git a/Nop.Plugin.Api/RouteProvider.cs b/Nop.Plugin.Api/RouteProvider.cs deleted file mode 100644 index d91ed59..0000000 --- a/Nop.Plugin.Api/RouteProvider.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Microsoft.AspNetCore.Routing; -using Nop.Web.Framework.Mvc.Routing; - -namespace Nop.Plugin.Api -{ - public class RouteProvider : IRouteProvider - { - public void RegisterRoutes(IRouteBuilder routeBuilder) - { - - } - - public int Priority => -1; - } -} diff --git a/Nop.Plugin.Api/Services/CategoryApiService.cs b/Nop.Plugin.Api/Services/CategoryApiService.cs index db2ec85..45dcbf8 100644 --- a/Nop.Plugin.Api/Services/CategoryApiService.cs +++ b/Nop.Plugin.Api/Services/CategoryApiService.cs @@ -1,21 +1,22 @@ using System; using System.Collections.Generic; using System.Linq; -using Nop.Core.Data; +using Nop.Data; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.DataStructures; +using Nop.Plugin.Api.Infrastructure; using Nop.Services.Stores; namespace Nop.Plugin.Api.Services { public class CategoryApiService : ICategoryApiService { - private readonly IStoreMappingService _storeMappingService; private readonly IRepository _categoryRepository; private readonly IRepository _productCategoryMappingRepository; + private readonly IStoreMappingService _storeMappingService; - public CategoryApiService(IRepository categoryRepository, + public CategoryApiService( + IRepository categoryRepository, IRepository productCategoryMappingRepository, IStoreMappingService storeMappingService) { @@ -24,9 +25,11 @@ public CategoryApiService(IRepository categoryRepository, _storeMappingService = storeMappingService; } - public IList GetCategories(IList ids = null, + public IList GetCategories( + IList ids = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, - int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId, + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId, int? productId = null, bool? publishedStatus = null) { @@ -44,14 +47,17 @@ public IList GetCategories(IList ids = null, public Category GetCategoryById(int id) { if (id <= 0) + { return null; + } var category = _categoryRepository.Table.FirstOrDefault(cat => cat.Id == id && !cat.Deleted); return category; } - public int GetCategoriesCount(DateTime? createdAtMin = null, DateTime? createdAtMax = null, + public int GetCategoriesCount( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, bool? publishedStatus = null, int? productId = null) { @@ -86,7 +92,6 @@ private IQueryable GetCategoriesQuery( if (createdAtMax != null) { - query = query.Where(c => c.CreatedOnUtc < createdAtMax.Value); } @@ -116,4 +121,4 @@ join productCategoryMapping in categoryMappingsForProduct on category.Id equals return query; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/ClientService.cs b/Nop.Plugin.Api/Services/ClientService.cs deleted file mode 100644 index 5ef4644..0000000 --- a/Nop.Plugin.Api/Services/ClientService.cs +++ /dev/null @@ -1,229 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Nop.Plugin.Api.Services -{ - using IdentityModel; - using IdentityServer4; - using IdentityServer4.EntityFramework.Entities; - using IdentityServer4.EntityFramework.Interfaces; - using IdentityServer4.Models; - using Microsoft.EntityFrameworkCore; - using MappingExtensions; - using Models; - using Client = IdentityServer4.EntityFramework.Entities.Client; - - public class ClientService : IClientService - { - private readonly IConfigurationDbContext _configurationDbContext; - - public ClientService(IConfigurationDbContext configurationDbContext) - { - _configurationDbContext = configurationDbContext; - } - - public IList GetAllClients() - { - IQueryable clientsQuery = _configurationDbContext.Clients - .Include(x => x.ClientSecrets) - .Include(x => x.RedirectUris); - - IList clients = clientsQuery.ToList(); - - IList clientApiModels = clients.Select(client => client.ToApiModel()).ToList(); - - return clientApiModels; - } - - public int InsertClient(ClientApiModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - var client = new Client - { - ClientId = model.ClientId, - Enabled = model.Enabled, - ClientName = model.ClientName, - // Needed to be able to obtain refresh token. - AllowOfflineAccess = true, - AccessTokenLifetime = model.AccessTokenLifetime, - AbsoluteRefreshTokenLifetime = model.RefreshTokenLifetime - }; - - AddOrUpdateClientSecret(client, model.ClientSecret); - AddOrUpdateClientRedirectUrl(client, model.RedirectUrl); - - client.AllowedGrantTypes = new List - { - new ClientGrantType - { - Client = client, - GrantType = OidcConstants.GrantTypes.AuthorizationCode - }, - new ClientGrantType - { - Client = client, - GrantType = OidcConstants.GrantTypes.RefreshToken - }, - new ClientGrantType - { - Client = client, - GrantType = OidcConstants.GrantTypes.JwtBearer - } - }; - - client.AllowedScopes = new List - { - new ClientScope - { - Client = client, - Scope = "nop_api" - } - }; - - client.Claims = new List - { - new ClientClaim - { - Client = client, - Type = JwtClaimTypes.Subject, - Value = client.ClientId - }, - new ClientClaim - { - Client = client, - Type = JwtClaimTypes.Name, - Value = client.ClientName - } - - }; - - _configurationDbContext.Clients.Add(client); - _configurationDbContext.SaveChanges(); - - return client.Id; - } - - public void UpdateClient(ClientApiModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - var currentClient = _configurationDbContext.Clients - .Include(client => client.ClientSecrets) - .Include(client => client.RedirectUris) - .FirstOrDefault(client => client.ClientId == model.ClientId); - - if (currentClient == null) - { - throw new ArgumentNullException(nameof(currentClient)); - } - - AddOrUpdateClientSecret(currentClient, model.ClientSecret); - AddOrUpdateClientRedirectUrl(currentClient, model.RedirectUrl); - - currentClient.ClientId = model.ClientId; - currentClient.ClientName = model.ClientName; - currentClient.Enabled = model.Enabled; - currentClient.AccessTokenLifetime = model.AccessTokenLifetime; - currentClient.AbsoluteRefreshTokenLifetime = model.RefreshTokenLifetime; - - _configurationDbContext.Clients.Update(currentClient); - _configurationDbContext.SaveChanges(); - } - - public ClientApiModel FindClientByIdAsync(int id) - { - var currentClient = _configurationDbContext.Clients - .Include(client => client.ClientSecrets) - .Include(client => client.RedirectUris) - .FirstOrDefault(client => client.Id == id); - - return currentClient?.ToApiModel(); - } - - public ClientApiModel FindClientByClientId(string clientId) - { - var currentClient = _configurationDbContext.Clients - .Include(client => client.ClientSecrets) - .Include(client => client.RedirectUris) - .FirstOrDefault(client => client.ClientId == clientId); - - return currentClient?.ToApiModel(); - } - - public void DeleteClient(int id) - { - var client = _configurationDbContext.Clients - .Include(entity => entity.ClientSecrets) - .Include(entity => entity.RedirectUris) - .FirstOrDefault(x => x.Id == id); - - if (client != null) - { - _configurationDbContext.Clients.Remove(client); - _configurationDbContext.SaveChanges(); - } - } - - private void AddOrUpdateClientRedirectUrl(Client currentClient, string modelRedirectUrl) - { - // Ensure the client redirect url collection is not null - if (currentClient.RedirectUris == null) - { - currentClient.RedirectUris = new List(); - } - - // Currently, the api works with only one client redirect uri. - var currentClientRedirectUri = currentClient.RedirectUris.FirstOrDefault(); - - // Add new redirectUri - if ((currentClientRedirectUri != null && currentClientRedirectUri.RedirectUri != modelRedirectUrl) || - currentClientRedirectUri == null) - { - // Remove all redirect uris as we may have only one. - currentClient.RedirectUris.Clear(); - - currentClient.RedirectUris.Add(new ClientRedirectUri - { - Client = currentClient, - RedirectUri = modelRedirectUrl - }); - } - } - - private void AddOrUpdateClientSecret(Client currentClient, string modelClientSecretDescription) - { - // Ensure the client secrets collection is not null - if (currentClient.ClientSecrets == null) - { - currentClient.ClientSecrets = new List(); - } - - // Currently, the api works with only one client secret. - var currentClientSecret = currentClient.ClientSecrets.FirstOrDefault(); - - // Add new secret - if ((currentClientSecret != null && currentClientSecret.Description != modelClientSecretDescription) || - currentClientSecret == null) - { - // Remove all secrets as we may have only one valid. - currentClient.ClientSecrets.Clear(); - - currentClient.ClientSecrets.Add(new ClientSecret - { - Client = currentClient, - Value = modelClientSecretDescription.Sha256(), - Type = IdentityServerConstants.ParsedSecretTypes.SharedSecret, - Description = modelClientSecretDescription - }); - } - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Services/CustomerApiService.cs b/Nop.Plugin.Api/Services/CustomerApiService.cs index d5fe55d..cb22e75 100644 --- a/Nop.Plugin.Api/Services/CustomerApiService.cs +++ b/Nop.Plugin.Api/Services/CustomerApiService.cs @@ -1,43 +1,45 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using Nop.Core.Data; -using Nop.Core.Domain.Customers; -using Nop.Plugin.Api.DTOs.Customers; using System.Linq; using System.Linq.Dynamic.Core; using System.Text.RegularExpressions; using Nop.Core; +using Nop.Core.Caching; +using Nop.Data; using Nop.Core.Domain.Common; -using Nop.Plugin.Api.Constants; +using Nop.Core.Domain.Customers; +using Nop.Core.Domain.Messages; using Nop.Plugin.Api.DataStructures; +using Nop.Plugin.Api.DTO.Customers; using Nop.Plugin.Api.Helpers; +using Nop.Plugin.Api.Infrastructure; using Nop.Plugin.Api.MappingExtensions; using Nop.Services.Localization; using Nop.Services.Stores; -using Nop.Core.Domain.Messages; -using Nop.Core.Caching; +using Nop.Services.Caching; namespace Nop.Plugin.Api.Services { public class CustomerApiService : ICustomerApiService { - private const string FirstName = "firstname"; - private const string LastName = "lastname"; - private const string LanguageId = "languageid"; - private const string DateOfBirth = "dateofbirth"; - private const string Gender = "gender"; - private const string KeyGroup = "customer"; + private const string FIRST_NAME = "firstname"; + private const string LAST_NAME = "lastname"; + private const string LANGUAGE_ID = "languageid"; + private const string DATE_OF_BIRTH = "dateofbirth"; + private const string GENDER = "gender"; + private const string KEY_GROUP = "customer"; + private readonly IStaticCacheManager _cacheManager; + private readonly IRepository _customerRepository; + private readonly IRepository _genericAttributeRepository; + private readonly ILanguageService _languageService; private readonly IStoreContext _storeContext; - private readonly ILanguageService _languageService; private readonly IStoreMappingService _storeMappingService; - private readonly IRepository _customerRepository; - private readonly IRepository _genericAttributeRepository; private readonly IRepository _subscriptionRepository; - private readonly IStaticCacheManager _cacheManager; - public CustomerApiService(IRepository customerRepository, + public CustomerApiService( + IRepository customerRepository, IRepository genericAttributeRepository, IRepository subscriptionRepository, IStoreContext storeContext, @@ -54,8 +56,9 @@ public CustomerApiService(IRepository customerRepository, _cacheManager = staticCacheManager; } - public IList GetCustomersDtos(DateTime? createdAtMin = null, DateTime? createdAtMax = null, int limit = Configurations.DefaultLimit, - int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId) + public IList GetCustomersDtos( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, int limit = Constants.Configurations.DefaultLimit, + int page = Constants.Configurations.DefaultPageValue, int sinceId = Constants.Configurations.DefaultSinceId) { var query = GetCustomersQuery(createdAtMin, createdAtMax, sinceId); @@ -69,12 +72,14 @@ public IList GetCustomersDtos(DateTime? createdAtMin = null, DateTi public int GetCustomersCount() { return _customerRepository.Table.Count(customer => !customer.Deleted - && (customer.RegisteredInStoreId == 0 || customer.RegisteredInStoreId == _storeContext.CurrentStore.Id)); + && (customer.RegisteredInStoreId == 0 || + customer.RegisteredInStoreId == _storeContext.CurrentStore.Id)); } // Need to work with dto object so we can map the first and last name from generic attributes table. - public IList Search(string queryParams = "", string order = Configurations.DefaultOrder, - int page = Configurations.DefaultPageValue, int limit = Configurations.DefaultLimit) + public IList Search( + string queryParams = "", string order = Constants.Configurations.DefaultOrder, + int page = Constants.Configurations.DefaultPageValue, int limit = Constants.Configurations.DefaultLimit) { IList result = new List(); @@ -89,7 +94,6 @@ public IList Search(string queryParams = "", string order = Configu // Skip non existing properties. if (ReflectionHelper.HasProperty(searchParam.Key, typeof(Customer))) { - // @0 is a placeholder used by dynamic linq and it is used to prevent possible sql injections. query = query.Where(string.Format("{0} = @0 || {0}.Contains(@0)", searchParam.Key), searchParam.Value); } @@ -109,9 +113,10 @@ public IList Search(string queryParams = "", string order = Configu public Dictionary GetFirstAndLastNameByCustomerId(int customerId) { return _genericAttributeRepository.Table.Where( - x => - x.KeyGroup == KeyGroup && x.EntityId == customerId && - (x.Key == FirstName || x.Key == LastName)).ToDictionary(x => x.Key.ToLowerInvariant(), y => y.Value); + x => + x.KeyGroup == KEY_GROUP && x.EntityId == customerId && + (x.Key == FIRST_NAME || x.Key == LAST_NAME)) + .ToDictionary(x => x.Key.ToLowerInvariant(), y => y.Value); } public Customer GetCustomerEntityById(int id) @@ -124,12 +129,14 @@ public Customer GetCustomerEntityById(int id) public CustomerDto GetCustomerById(int id, bool showDeleted = false) { if (id == 0) + { return null; + } // Here we expect to get two records, one for the first name and one for the last name. var customerAttributeMappings = (from customer in _customerRepository.Table //NoTracking - join attribute in _genericAttributeRepository.Table//NoTracking - on customer.Id equals attribute.EntityId + join attribute in _genericAttributeRepository.Table //NoTracking + on customer.Id equals attribute.EntityId where customer.Id == id && attribute.KeyGroup == "Customer" select new CustomerAttributeMappingDto @@ -150,11 +157,12 @@ on customer.Id equals attribute.EntityId var defaultStoreLanguageId = GetDefaultStoreLangaugeId(); // If there is no Language Id generic attribute create one with the default language id. - if (!customerAttributeMappings.Any(cam => cam?.Attribute != null && cam.Attribute.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase))) + if (!customerAttributeMappings.Any(cam => cam?.Attribute != null && + cam.Attribute.Key.Equals(LANGUAGE_ID, StringComparison.InvariantCultureIgnoreCase))) { var languageId = new GenericAttribute { - Key = LanguageId, + Key = LANGUAGE_ID, Value = defaultStoreLanguageId.ToString() }; @@ -176,23 +184,25 @@ on customer.Id equals attribute.EntityId if (mapping.Attribute != null) { - if (mapping.Attribute.Key.Equals(FirstName, StringComparison.InvariantCultureIgnoreCase)) + if (mapping.Attribute.Key.Equals(FIRST_NAME, StringComparison.InvariantCultureIgnoreCase)) { customerDto.FirstName = mapping.Attribute.Value; } - else if (mapping.Attribute.Key.Equals(LastName, StringComparison.InvariantCultureIgnoreCase)) + else if (mapping.Attribute.Key.Equals(LAST_NAME, StringComparison.InvariantCultureIgnoreCase)) { customerDto.LastName = mapping.Attribute.Value; } - else if (mapping.Attribute.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase)) + else if (mapping.Attribute.Key.Equals(LANGUAGE_ID, StringComparison.InvariantCultureIgnoreCase)) { customerDto.LanguageId = mapping.Attribute.Value; } - else if (mapping.Attribute.Key.Equals(DateOfBirth, StringComparison.InvariantCultureIgnoreCase)) + else if (mapping.Attribute.Key.Equals(DATE_OF_BIRTH, StringComparison.InvariantCultureIgnoreCase)) { - customerDto.DateOfBirth = string.IsNullOrEmpty(mapping.Attribute.Value) ? (DateTime?)null : DateTime.Parse(mapping.Attribute.Value); + customerDto.DateOfBirth = string.IsNullOrEmpty(mapping.Attribute.Value) + ? (DateTime?)null + : DateTime.Parse(mapping.Attribute.Value); } - else if (mapping.Attribute.Key.Equals(Gender, StringComparison.InvariantCultureIgnoreCase)) + else if (mapping.Attribute.Key.Equals(GENDER, StringComparison.InvariantCultureIgnoreCase)) { customerDto.Gender = mapping.Attribute.Value; } @@ -234,14 +244,16 @@ private Dictionary ParseSearchQuery(string query) var splitPattern = @"(\w+):"; - var fieldValueList = Regex.Split(query, splitPattern).Where(s => s != String.Empty).ToList(); + var fieldValueList = Regex.Split(query, splitPattern).Where(s => s != string.Empty).ToList(); if (fieldValueList.Count < 2) { return parsedQuery; } - for (var i = 0; i < fieldValueList.Count; i += 2) + for (var i = 0; + i < fieldValueList.Count; + i += 2) { var field = fieldValueList[i]; var value = fieldValueList[i + 1]; @@ -257,17 +269,25 @@ private Dictionary ParseSearchQuery(string query) } /// - /// The idea of this method is to get the first and last name from the GenericAttribute table and to set them in the CustomerDto object. + /// The idea of this method is to get the first and last name from the GenericAttribute table and to set them in the + /// CustomerDto object. /// - /// Search parameters is used to shrinc the range of results from the GenericAttibutes table - /// to be only those with specific search parameter (i.e. currently we focus only on first and last name). - /// Query parameter represents the current customer records which we will join with GenericAttributes table. + /// + /// Search parameters is used to shrinc the range of results from the GenericAttibutes table + /// to be only those with specific search parameter (i.e. currently we focus only on first and last name). + /// + /// + /// Query parameter represents the current customer records which we will join with GenericAttributes + /// table. + /// /// /// /// /// - private IList HandleCustomerGenericAttributes(IReadOnlyDictionary searchParams, IQueryable query, - int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, string order = Configurations.DefaultOrder) + private IList HandleCustomerGenericAttributes( + IReadOnlyDictionary searchParams, IQueryable query, + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + string order = Constants.Configurations.DefaultOrder) { // Here we join the GenericAttribute records with the customers and making sure that we are working only with the attributes // that are in the customers keyGroup and their keys are either first or last name. @@ -284,8 +304,8 @@ private IList HandleCustomerGenericAttributes(IReadOnlyDictionary attr.EntityId == customer.Id && - attr.KeyGroup == "Customer").DefaultIfEmpty() + .Where(attr => attr.EntityId == customer.Id && + attr.KeyGroup == "Customer").DefaultIfEmpty() select new CustomerAttributeMappingDto { Attribute = attribute, @@ -294,29 +314,29 @@ from attribute in _genericAttributeRepository.Table if (searchParams != null && searchParams.Count > 0) { - if (searchParams.ContainsKey(FirstName)) + if (searchParams.ContainsKey(FIRST_NAME)) { - allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, FirstName, searchParams[FirstName]); + allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, FIRST_NAME, searchParams[FIRST_NAME]); } - if (searchParams.ContainsKey(LastName)) + if (searchParams.ContainsKey(LAST_NAME)) { - allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, LastName, searchParams[LastName]); + allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, LAST_NAME, searchParams[LAST_NAME]); } - if (searchParams.ContainsKey(LanguageId)) + if (searchParams.ContainsKey(LANGUAGE_ID)) { - allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, LanguageId, searchParams[LanguageId]); + allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, LANGUAGE_ID, searchParams[LANGUAGE_ID]); } - if (searchParams.ContainsKey(DateOfBirth)) + if (searchParams.ContainsKey(DATE_OF_BIRTH)) { - allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, DateOfBirth, searchParams[DateOfBirth]); + allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, DATE_OF_BIRTH, searchParams[DATE_OF_BIRTH]); } - if (searchParams.ContainsKey(Gender)) + if (searchParams.ContainsKey(GENDER)) { - allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, Gender, searchParams[Gender]); + allRecordsGroupedByCustomerId = GetCustomerAttributesMappingsByKey(allRecordsGroupedByCustomerId, GENDER, searchParams[GENDER]); } } @@ -326,16 +346,20 @@ from attribute in _genericAttributeRepository.Table } /// - /// This method is responsible for getting customer dto records with first and last names set from the attribute mappings. + /// This method is responsible for getting customer dto records with first and last names set from the attribute + /// mappings. /// - private IList GetFullCustomerDtos(IQueryable> customerAttributesMappings, - int page = Configurations.DefaultPageValue, int limit = Configurations.DefaultLimit, string order = Configurations.DefaultOrder) + private IList GetFullCustomerDtos( + IQueryable> customerAttributesMappings, + int page = Constants.Configurations.DefaultPageValue, int limit = Constants.Configurations.DefaultLimit, + string order = Constants.Configurations.DefaultOrder) { var customerDtos = new List(); customerAttributesMappings = customerAttributesMappings.OrderBy(x => x.Key); - IList> customerAttributeGroupsList = new ApiList>(customerAttributesMappings, page - 1, limit); + IList> customerAttributeGroupsList = + new ApiList>(customerAttributesMappings, page - 1, limit); // Get the default language id for the current store. var defaultLanguageId = GetDefaultStoreLangaugeId(); @@ -361,11 +385,11 @@ private static CustomerDto Merge(IList mappingsForM var attributes = mappingsForMerge.Select(x => x.Attribute).ToList(); // If there is no Language Id generic attribute create one with the default language id. - if (!attributes.Any(atr => atr != null && atr.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase))) + if (!attributes.Any(atr => atr != null && atr.Key.Equals(LANGUAGE_ID, StringComparison.InvariantCultureIgnoreCase))) { var languageId = new GenericAttribute { - Key = LanguageId, + Key = LANGUAGE_ID, Value = defaultLanguageId.ToString() }; @@ -376,23 +400,25 @@ private static CustomerDto Merge(IList mappingsForM { if (attribute != null) { - if (attribute.Key.Equals(FirstName, StringComparison.InvariantCultureIgnoreCase)) + if (attribute.Key.Equals(FIRST_NAME, StringComparison.InvariantCultureIgnoreCase)) { customerDto.FirstName = attribute.Value; } - else if (attribute.Key.Equals(LastName, StringComparison.InvariantCultureIgnoreCase)) + else if (attribute.Key.Equals(LAST_NAME, StringComparison.InvariantCultureIgnoreCase)) { customerDto.LastName = attribute.Value; } - else if (attribute.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase)) + else if (attribute.Key.Equals(LANGUAGE_ID, StringComparison.InvariantCultureIgnoreCase)) { customerDto.LanguageId = attribute.Value; } - else if (attribute.Key.Equals(DateOfBirth, StringComparison.InvariantCultureIgnoreCase)) + else if (attribute.Key.Equals(DATE_OF_BIRTH, StringComparison.InvariantCultureIgnoreCase)) { - customerDto.DateOfBirth = string.IsNullOrEmpty(attribute.Value) ? (DateTime?)null : DateTime.Parse(attribute.Value); + customerDto.DateOfBirth = string.IsNullOrEmpty(attribute.Value) + ? (DateTime?)null + : DateTime.Parse(attribute.Value); } - else if (attribute.Key.Equals(Gender, StringComparison.InvariantCultureIgnoreCase)) + else if (attribute.Key.Equals(GENDER, StringComparison.InvariantCultureIgnoreCase)) { customerDto.Gender = attribute.Value; } @@ -409,7 +435,7 @@ private IQueryable> GetCustomerAttri var customerAttributesMappingByKey = from @group in customerAttributesGroups where @group.Select(x => x.Attribute) .Any(x => x.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase) && - x.Value.Equals(value, StringComparison.InvariantCultureIgnoreCase)) + x.Value.Equals(value, StringComparison.InvariantCultureIgnoreCase)) select @group; return customerAttributesMappingByKey; @@ -418,10 +444,15 @@ where @group.Select(x => x.Attribute) private IQueryable GetCustomersQuery(DateTime? createdAtMin = null, DateTime? createdAtMax = null, int sinceId = 0) { var query = _customerRepository.Table //NoTracking - .Where(customer => !customer.Deleted && !customer.IsSystemAccount && customer.Active); + .Where(customer => !customer.Deleted && !customer.IsSystemAccount && customer.Active); + + //query = query.Where(customer => + // !customer.CustomerCustomerRoleMappings.Any(ccrm => ccrm.CustomerRole.Active && + // ccrm.CustomerRole.SystemName == NopCustomerDefaults.GuestsRoleName) + // && (customer.RegisteredInStoreId == 0 || customer.RegisteredInStoreId == _storeContext.CurrentStore.Id)); - query = query.Where(customer => !customer.CustomerCustomerRoleMappings.Any(ccrm => ccrm.CustomerRole.Active && ccrm.CustomerRole.SystemName == NopCustomerDefaults.GuestsRoleName) - && (customer.RegisteredInStoreId == 0 || customer.RegisteredInStoreId == _storeContext.CurrentStore.Id)); + query = query.Where(customer => + (customer.RegisteredInStoreId == 0 || customer.RegisteredInStoreId == _storeContext.CurrentStore.Id)); if (createdAtMin != null) { @@ -453,7 +484,7 @@ private int GetDefaultStoreLangaugeId() var allLanguages = _languageService.GetAllLanguages(); var storeLanguages = allLanguages.Where(l => - _storeMappingService.Authorize(l, _storeContext.CurrentStore.Id)).ToList(); + _storeMappingService.Authorize(l, _storeContext.CurrentStore.Id)).ToList(); // If there is no language mapped to the current store, get all of the languages, // and use the one with the first display order. This is a default nopCommerce workflow. @@ -486,9 +517,9 @@ private void SetNewsletterSubscribtionStatus(IList customerDtos) } } - private void SetNewsletterSubscribtionStatus(BaseCustomerDto customerDto, IEnumerable allNewsletterCustomerEmail = null) + private void SetNewsletterSubscribtionStatus(BaseCustomerDto customerDto, IEnumerable allNewsletterCustomerEmail = null) { - if (customerDto == null || String.IsNullOrEmpty(customerDto.Email)) + if (customerDto == null || string.IsNullOrEmpty(customerDto.Email)) { return; } @@ -504,20 +535,20 @@ private void SetNewsletterSubscribtionStatus(BaseCustomerDto customerDto, IEnume } } - private IEnumerable GetAllNewsletterCustomersEmails() + private IEnumerable GetAllNewsletterCustomersEmails() { - return _cacheManager.Get(Configurations.NEWSLETTER_SUBSCRIBERS_KEY, () => + return _cacheManager.Get(Constants.Configurations.NEWSLETTER_SUBSCRIBERS_KEY, () => { - IEnumerable subscriberEmails = (from nls in _subscriptionRepository.Table + IEnumerable subscriberEmails = (from nls in _subscriptionRepository.Table where nls.StoreId == _storeContext.CurrentStore.Id && nls.Active select nls.Email).ToList(); - subscriberEmails = subscriberEmails.Where(e => !String.IsNullOrEmpty(e)).Select(e => e.ToLowerInvariant()); + subscriberEmails = subscriberEmails.Where(e => !string.IsNullOrEmpty(e)).Select(e => e.ToLowerInvariant()); - return subscriberEmails.Where(e => !String.IsNullOrEmpty(e)).Select(e => e.ToLowerInvariant()); + return subscriberEmails.Where(e => !string.IsNullOrEmpty(e)).Select(e => e.ToLowerInvariant()); }); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/ICategoryApiService.cs b/Nop.Plugin.Api/Services/ICategoryApiService.cs index f47366d..e8e378e 100644 --- a/Nop.Plugin.Api/Services/ICategoryApiService.cs +++ b/Nop.Plugin.Api/Services/ICategoryApiService.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { @@ -9,12 +9,15 @@ public interface ICategoryApiService { Category GetCategoryById(int categoryId); - IList GetCategories(IList ids = null, + IList GetCategories( + IList ids = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, - int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId, + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId, int? productId = null, bool? publishedStatus = null); - int GetCategoriesCount(DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, + int GetCategoriesCount( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, bool? publishedStatus = null, int? productId = null); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/IClientService.cs b/Nop.Plugin.Api/Services/IClientService.cs deleted file mode 100644 index 8e448da..0000000 --- a/Nop.Plugin.Api/Services/IClientService.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Collections.Generic; - -namespace Nop.Plugin.Api.Services -{ - using Models; - - public interface IClientService - { - IList GetAllClients(); - void DeleteClient(int id); - int InsertClient(ClientApiModel model); - void UpdateClient(ClientApiModel model); - ClientApiModel FindClientByIdAsync(int id); - ClientApiModel FindClientByClientId(string clientId); - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Services/ICustomerApiService.cs b/Nop.Plugin.Api/Services/ICustomerApiService.cs index 4e4683c..0a4f745 100644 --- a/Nop.Plugin.Api/Services/ICustomerApiService.cs +++ b/Nop.Plugin.Api/Services/ICustomerApiService.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using Nop.Core.Domain.Customers; -using Nop.Plugin.Api.Constants; -using Nop.Plugin.Api.DTOs.Customers; +using Nop.Plugin.Api.DTO.Customers; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { @@ -14,12 +14,15 @@ public interface ICustomerApiService Customer GetCustomerEntityById(int id); - IList GetCustomersDtos(DateTime? createdAtMin = null, DateTime? createdAtMax = null, - int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId); - - IList Search(string query = "", string order = Configurations.DefaultOrder, - int page = Configurations.DefaultPageValue, int limit = Configurations.DefaultLimit); + IList GetCustomersDtos( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId); + + IList Search( + string query = "", string order = Constants.Configurations.DefaultOrder, + int page = Constants.Configurations.DefaultPageValue, int limit = Constants.Configurations.DefaultLimit); Dictionary GetFirstAndLastNameByCustomerId(int customerId); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/IManufacturerApiService.cs b/Nop.Plugin.Api/Services/IManufacturerApiService.cs index 6875587..f74b2c9 100644 --- a/Nop.Plugin.Api/Services/IManufacturerApiService.cs +++ b/Nop.Plugin.Api/Services/IManufacturerApiService.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { @@ -9,12 +9,15 @@ public interface IManufacturerApiService { Manufacturer GetManufacturerById(int manufacturerId); - IList GetManufacturers(IList ids = null, + IList GetManufacturers( + IList ids = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, - int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId, + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId, int? productId = null, bool? publishedStatus = null, int? languageId = null); - int GetManufacturersCount(DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, + int GetManufacturersCount( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, bool? publishedStatus = null, int? productId = null); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/INewsLetterSubscriptionApiService.cs b/Nop.Plugin.Api/Services/INewsLetterSubscriptionApiService.cs index 20d55a0..af0e6a9 100644 --- a/Nop.Plugin.Api/Services/INewsLetterSubscriptionApiService.cs +++ b/Nop.Plugin.Api/Services/INewsLetterSubscriptionApiService.cs @@ -1,14 +1,16 @@ -using Nop.Core.Domain.Messages; -using Nop.Plugin.Api.Constants; -using System; +using System; using System.Collections.Generic; +using Nop.Core.Domain.Messages; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { public interface INewsLetterSubscriptionApiService { - List GetNewsLetterSubscriptions(DateTime? createdAtMin = null, DateTime? createdAtMax = null, - int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId, + List GetNewsLetterSubscriptions( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId, bool? onlyActive = true); } } diff --git a/Nop.Plugin.Api/Services/IOrderApiService.cs b/Nop.Plugin.Api/Services/IOrderApiService.cs index 8d4684e..d8642f6 100644 --- a/Nop.Plugin.Api/Services/IOrderApiService.cs +++ b/Nop.Plugin.Api/Services/IOrderApiService.cs @@ -3,7 +3,7 @@ using Nop.Core.Domain.Orders; using Nop.Core.Domain.Payments; using Nop.Core.Domain.Shipping; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { @@ -11,15 +11,17 @@ public interface IOrderApiService { IList GetOrdersByCustomerId(int customerId); - IList GetOrders(IList ids = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, - int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, - int sinceId = Configurations.DefaultSinceId, OrderStatus? status = null, PaymentStatus? paymentStatus = null, - ShippingStatus? shippingStatus = null, int? customerId = null, int? storeId = null); + IList GetOrders( + IList ids = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId, OrderStatus? status = null, PaymentStatus? paymentStatus = null, + ShippingStatus? shippingStatus = null, int? customerId = null, int? storeId = null); Order GetOrderById(int orderId); - int GetOrdersCount(DateTime? createdAtMin = null, DateTime? createdAtMax = null, OrderStatus? status = null, - PaymentStatus? paymentStatus = null, ShippingStatus? shippingStatus = null, - int? customerId = null, int? storeId = null); + int GetOrdersCount( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, OrderStatus? status = null, + PaymentStatus? paymentStatus = null, ShippingStatus? shippingStatus = null, + int? customerId = null, int? storeId = null); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/IOrderItemApiService.cs b/Nop.Plugin.Api/Services/IOrderItemApiService.cs index b448407..679204b 100644 --- a/Nop.Plugin.Api/Services/IOrderItemApiService.cs +++ b/Nop.Plugin.Api/Services/IOrderItemApiService.cs @@ -8,4 +8,4 @@ public interface IOrderItemApiService IList GetOrderItemsForOrder(Order order, int limit, int page, int sinceId); int GetOrderItemsCount(Order order); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/IProductApiService.cs b/Nop.Plugin.Api/Services/IProductApiService.cs index 6d0f005..9f756e6 100644 --- a/Nop.Plugin.Api/Services/IProductApiService.cs +++ b/Nop.Plugin.Api/Services/IProductApiService.cs @@ -1,23 +1,26 @@ using System; using System.Collections.Generic; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { public interface IProductApiService { - IList GetProducts(IList ids = null, + IList GetProducts( + IList ids = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, - int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId, - int? categoryId = null, string vendorName = null, bool? publishedStatus = null); + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId, + int? categoryId = null, string vendorName = null, bool? publishedStatus = null); - int GetProductsCount(DateTime? createdAtMin = null, DateTime? createdAtMax = null, - DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, bool? publishedStatus = null, + int GetProductsCount( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, + DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, bool? publishedStatus = null, string vendorName = null, int? categoryId = null); Product GetProductById(int productId); Product GetProductByIdNoTracking(int productId); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/IProductAttributeConverter.cs b/Nop.Plugin.Api/Services/IProductAttributeConverter.cs index 5b8b933..bcf93a3 100644 --- a/Nop.Plugin.Api/Services/IProductAttributeConverter.cs +++ b/Nop.Plugin.Api/Services/IProductAttributeConverter.cs @@ -1,5 +1,5 @@ -using Nop.Plugin.Api.DTOs; -using System.Collections.Generic; +using System.Collections.Generic; +using Nop.Plugin.Api.DTO; namespace Nop.Plugin.Api.Services { diff --git a/Nop.Plugin.Api/Services/IProductAttributesApiService.cs b/Nop.Plugin.Api/Services/IProductAttributesApiService.cs index b7ade53..7e03530 100644 --- a/Nop.Plugin.Api/Services/IProductAttributesApiService.cs +++ b/Nop.Plugin.Api/Services/IProductAttributesApiService.cs @@ -1,16 +1,17 @@ using System.Collections.Generic; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { public interface IProductAttributesApiService { - IList GetProductAttributes(int limit = Configurations.DefaultLimit, - int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId); + IList GetProductAttributes( + int limit = Constants.Configurations.DefaultLimit, + int page = Constants.Configurations.DefaultPageValue, int sinceId = Constants.Configurations.DefaultSinceId); int GetProductAttributesCount(); ProductAttribute GetById(int id); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/IProductCategoryMappingsApiService.cs b/Nop.Plugin.Api/Services/IProductCategoryMappingsApiService.cs index f81f995..d2cab06 100644 --- a/Nop.Plugin.Api/Services/IProductCategoryMappingsApiService.cs +++ b/Nop.Plugin.Api/Services/IProductCategoryMappingsApiService.cs @@ -1,16 +1,17 @@ using System.Collections.Generic; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { public interface IProductCategoryMappingsApiService { - IList GetMappings(int? productId = null, int? categoryId = null, int limit = Configurations.DefaultLimit, - int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId); + IList GetMappings( + int? productId = null, int? categoryId = null, int limit = Constants.Configurations.DefaultLimit, + int page = Constants.Configurations.DefaultPageValue, int sinceId = Constants.Configurations.DefaultSinceId); int GetMappingsCount(int? productId = null, int? categoryId = null); ProductCategory GetById(int id); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/IProductManufacturerMappingsApiService.cs b/Nop.Plugin.Api/Services/IProductManufacturerMappingsApiService.cs index eca7627..2d42da4 100644 --- a/Nop.Plugin.Api/Services/IProductManufacturerMappingsApiService.cs +++ b/Nop.Plugin.Api/Services/IProductManufacturerMappingsApiService.cs @@ -1,16 +1,17 @@ using System.Collections.Generic; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { public interface IProductManufacturerMappingsApiService { - IList GetMappings(int? productId = null, int? manufacturerId = null, int limit = Configurations.DefaultLimit, - int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId); + IList GetMappings( + int? productId = null, int? manufacturerId = null, int limit = Constants.Configurations.DefaultLimit, + int page = Constants.Configurations.DefaultPageValue, int sinceId = Constants.Configurations.DefaultSinceId); int GetMappingsCount(int? productId = null, int? manufacturerId = null); ProductManufacturer GetById(int id); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/IShoppingCartItemApiService.cs b/Nop.Plugin.Api/Services/IShoppingCartItemApiService.cs index f675fc2..9db7db9 100644 --- a/Nop.Plugin.Api/Services/IShoppingCartItemApiService.cs +++ b/Nop.Plugin.Api/Services/IShoppingCartItemApiService.cs @@ -1,16 +1,17 @@ using System; using System.Collections.Generic; using Nop.Core.Domain.Orders; -using Nop.Plugin.Api.Constants; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { public interface IShoppingCartItemApiService { - List GetShoppingCartItems(int? customerId = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, - DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, int limit = Configurations.DefaultLimit, - int page = Configurations.DefaultPageValue); + List GetShoppingCartItems( + int? customerId = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, + DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, int limit = Constants.Configurations.DefaultLimit, + int page = Constants.Configurations.DefaultPageValue); ShoppingCartItem GetShoppingCartItem(int id); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/ISpecificationAttributeApiService.cs b/Nop.Plugin.Api/Services/ISpecificationAttributeApiService.cs index 052a015..c846553 100644 --- a/Nop.Plugin.Api/Services/ISpecificationAttributeApiService.cs +++ b/Nop.Plugin.Api/Services/ISpecificationAttributeApiService.cs @@ -1,12 +1,18 @@ -using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.Constants; -using System.Collections.Generic; +using System.Collections.Generic; +using Nop.Core.Domain.Catalog; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { public interface ISpecificationAttributeApiService { - IList GetProductSpecificationAttributes(int? productId = null, int? specificationAttributeOptionId = null, bool? allowFiltering = null, bool? showOnProductPage = null, int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId); - IList GetSpecificationAttributes(int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId); + IList GetProductSpecificationAttributes( + int? productId = null, int? specificationAttributeOptionId = null, bool? allowFiltering = null, bool? showOnProductPage = null, + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId); + + IList GetSpecificationAttributes( + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/IWebHookService.cs b/Nop.Plugin.Api/Services/IWebHookService.cs deleted file mode 100644 index e4e7463..0000000 --- a/Nop.Plugin.Api/Services/IWebHookService.cs +++ /dev/null @@ -1,12 +0,0 @@ -//namespace Nop.Plugin.Api.Services -//{ -// using Microsoft.AspNet.WebHooks; - -// public interface IWebHookService -// { -// IWebHookManager GetWebHookManager(); -// IWebHookSender GetWebHookSender(); -// IWebHookStore GetWebHookStore(); -// IWebHookFilterManager GetWebHookFilterManager(); -// } -//} diff --git a/Nop.Plugin.Api/Services/ManufacturerApiService.cs b/Nop.Plugin.Api/Services/ManufacturerApiService.cs index edbe708..b8bae61 100644 --- a/Nop.Plugin.Api/Services/ManufacturerApiService.cs +++ b/Nop.Plugin.Api/Services/ManufacturerApiService.cs @@ -1,22 +1,22 @@ using System; using System.Collections.Generic; using System.Linq; -using Nop.Core.Data; +using Nop.Data; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Localization; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.DataStructures; -using Nop.Services.Stores; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { public class ManufacturerApiService : IManufacturerApiService { + private readonly IRepository _localizedPropertyRepository; private readonly IRepository _manufacturerRepository; private readonly IRepository _productManufacturerMappingRepository; - private readonly IRepository _localizedPropertyRepository; - public ManufacturerApiService(IRepository manufacturerRepository, + public ManufacturerApiService( + IRepository manufacturerRepository, IRepository productManufacturerMappingRepository, IRepository localizedPropertyRepository) { @@ -25,13 +25,15 @@ public ManufacturerApiService(IRepository manufacturerRepository, _localizedPropertyRepository = localizedPropertyRepository; } - public IList GetManufacturers(IList ids = null, + public IList GetManufacturers( + IList ids = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, - int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId, + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId, int? productId = null, bool? publishedStatus = null, int? languageId = null) { var query = GetManufacturersQuery(createdAtMin, createdAtMax, updatedAtMin, updatedAtMax, publishedStatus, productId, ids); - + if (sinceId > 0) { query = query.Where(c => c.Id > sinceId); @@ -40,13 +42,15 @@ public IList GetManufacturers(IList ids = null, if (languageId.HasValue) { - var localizedNames = _localizedPropertyRepository.TableNoTracking.Where(x => x.LocaleKeyGroup == "Manufacturer" && languageId == languageId.Value); - foreach (var cat in list) - { - var localizedName = localizedNames.FirstOrDefault(x => x.EntityId == cat.Id); - if (localizedName != null) - cat.Name = localizedName.LocaleValue; - } + //var localizedNames = _localizedPropertyRepository.TableNoTracking.Where(x => x.LocaleKeyGroup == "Manufacturer" && languageId == languageId.Value); + //foreach (var cat in list) + //{ + // var localizedName = localizedNames.FirstOrDefault(x => x.EntityId == cat.Id); + // if (localizedName != null) + // { + // cat.Name = localizedName.LocaleValue; + // } + //} } return list; @@ -56,19 +60,22 @@ public IList GetManufacturers(IList ids = null, public Manufacturer GetManufacturerById(int id) { if (id <= 0) + { return null; + } var manufacturer = _manufacturerRepository.Table.FirstOrDefault(man => man.Id == id && !man.Deleted); return manufacturer; } - public int GetManufacturersCount(DateTime? createdAtMin = null, DateTime? createdAtMax = null, + public int GetManufacturersCount( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, bool? publishedStatus = null, int? productId = null) { var query = GetManufacturersQuery(createdAtMin, createdAtMax, updatedAtMin, updatedAtMax, - publishedStatus, productId); + publishedStatus, productId); return query.Count(); } @@ -98,7 +105,6 @@ private IQueryable GetManufacturersQuery( if (createdAtMax != null) { - query = query.Where(c => c.CreatedOnUtc < createdAtMax.Value); } @@ -115,8 +121,8 @@ private IQueryable GetManufacturersQuery( if (productId != null) { var manufacturerMappingsForProduct = from productManufacturerMapping in _productManufacturerMappingRepository.Table - where productManufacturerMapping.ProductId == productId - select productManufacturerMapping; + where productManufacturerMapping.ProductId == productId + select productManufacturerMapping; query = from manufacturer in query join productManufacturerMapping in manufacturerMappingsForProduct on manufacturer.Id equals productManufacturerMapping.ManufacturerId @@ -128,4 +134,4 @@ join productManufacturerMapping in manufacturerMappingsForProduct on manufacture return query; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/NewsLetterSubscriptionApiService.cs b/Nop.Plugin.Api/Services/NewsLetterSubscriptionApiService.cs index dcd5c20..1d41274 100644 --- a/Nop.Plugin.Api/Services/NewsLetterSubscriptionApiService.cs +++ b/Nop.Plugin.Api/Services/NewsLetterSubscriptionApiService.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.Linq; using Nop.Core; -using Nop.Core.Data; +using Nop.Data; using Nop.Core.Domain.Messages; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.DataStructures; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { @@ -20,8 +20,10 @@ public NewsLetterSubscriptionApiService(IRepository news _storeContext = storeContext; } - public List GetNewsLetterSubscriptions(DateTime? createdAtMin = null, DateTime? createdAtMax = null, - int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId, + public List GetNewsLetterSubscriptions( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId, bool? onlyActive = true) { var query = GetNewsLetterSubscriptionsQuery(createdAtMin, createdAtMax, onlyActive); @@ -34,7 +36,8 @@ public List GetNewsLetterSubscriptions(DateTime? created return new ApiList(query, page - 1, limit); } - private IQueryable GetNewsLetterSubscriptionsQuery(DateTime? createdAtMin = null, DateTime? createdAtMax = null, bool? onlyActive = true) + private IQueryable GetNewsLetterSubscriptionsQuery( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, bool? onlyActive = true) { var query = _newsLetterSubscriptionRepository.Table.Where(nls => nls.StoreId == _storeContext.CurrentStore.Id); @@ -42,7 +45,7 @@ private IQueryable GetNewsLetterSubscriptionsQuery(DateT { query = query.Where(nls => nls.Active == onlyActive); } - + if (createdAtMin != null) { query = query.Where(c => c.CreatedOnUtc > createdAtMin.Value); @@ -50,7 +53,6 @@ private IQueryable GetNewsLetterSubscriptionsQuery(DateT if (createdAtMax != null) { - query = query.Where(c => c.CreatedOnUtc < createdAtMax.Value); } diff --git a/Nop.Plugin.Api/Services/OrderApiService.cs b/Nop.Plugin.Api/Services/OrderApiService.cs index 56b2d9b..69a5ba5 100644 --- a/Nop.Plugin.Api/Services/OrderApiService.cs +++ b/Nop.Plugin.Api/Services/OrderApiService.cs @@ -1,12 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; -using Nop.Core.Data; +using Nop.Data; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Payments; using Nop.Core.Domain.Shipping; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.DataStructures; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { @@ -26,13 +26,15 @@ public IList GetOrdersByCustomerId(int customerId) orderby order.Id select order; - return new ApiList(query, 0, Configurations.MaxLimit); + return new ApiList(query, 0, Constants.Configurations.MaxLimit); } - public IList GetOrders(IList ids = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, - int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId, - OrderStatus? status = null, PaymentStatus? paymentStatus = null, ShippingStatus? shippingStatus = null, int? customerId = null, - int? storeId = null) + public IList GetOrders( + IList ids = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId, + OrderStatus? status = null, PaymentStatus? paymentStatus = null, ShippingStatus? shippingStatus = null, int? customerId = null, + int? storeId = null) { var query = GetOrdersQuery(createdAtMin, createdAtMax, status, paymentStatus, shippingStatus, ids, customerId, storeId); @@ -47,26 +49,30 @@ public IList GetOrders(IList ids = null, DateTime? createdAtMin = nu public Order GetOrderById(int orderId) { if (orderId <= 0) + { return null; + } return _orderRepository.Table.FirstOrDefault(order => order.Id == orderId && !order.Deleted); } - public int GetOrdersCount(DateTime? createdAtMin = null, DateTime? createdAtMax = null, OrderStatus? status = null, - PaymentStatus? paymentStatus = null, ShippingStatus? shippingStatus = null, - int? customerId = null, int? storeId = null) + public int GetOrdersCount( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, OrderStatus? status = null, + PaymentStatus? paymentStatus = null, ShippingStatus? shippingStatus = null, + int? customerId = null, int? storeId = null) { var query = GetOrdersQuery(createdAtMin, createdAtMax, status, paymentStatus, shippingStatus, customerId: customerId, storeId: storeId); return query.Count(); } - private IQueryable GetOrdersQuery(DateTime? createdAtMin = null, DateTime? createdAtMax = null, OrderStatus? status = null, - PaymentStatus? paymentStatus = null, ShippingStatus? shippingStatus = null, IList ids = null, + private IQueryable GetOrdersQuery( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, OrderStatus? status = null, + PaymentStatus? paymentStatus = null, ShippingStatus? shippingStatus = null, IList ids = null, int? customerId = null, int? storeId = null) { var query = _orderRepository.Table; - + if (customerId != null) { query = query.Where(order => order.CustomerId == customerId); @@ -76,20 +82,20 @@ private IQueryable GetOrdersQuery(DateTime? createdAtMin = null, DateTime { query = query.Where(c => ids.Contains(c.Id)); } - + if (status != null) { - query = query.Where(order => order.OrderStatusId == (int)status); + query = query.Where(order => order.OrderStatusId == (int) status); } - + if (paymentStatus != null) { - query = query.Where(order => order.PaymentStatusId == (int)paymentStatus); + query = query.Where(order => order.PaymentStatusId == (int) paymentStatus); } - + if (shippingStatus != null) { - query = query.Where(order => order.ShippingStatusId == (int)shippingStatus); + query = query.Where(order => order.ShippingStatusId == (int) shippingStatus); } query = query.Where(order => !order.Deleted); @@ -125,4 +131,4 @@ private IQueryable GetOrdersQuery(DateTime? createdAtMin = null, DateTime return query; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/OrderItemApiService.cs b/Nop.Plugin.Api/Services/OrderItemApiService.cs index 9542535..d06cd8f 100644 --- a/Nop.Plugin.Api/Services/OrderItemApiService.cs +++ b/Nop.Plugin.Api/Services/OrderItemApiService.cs @@ -2,23 +2,35 @@ using System.Linq; using Nop.Core.Domain.Orders; using Nop.Plugin.Api.DataStructures; +using Nop.Services.Catalog; +using Nop.Services.Orders; namespace Nop.Plugin.Api.Services { public class OrderItemApiService : IOrderItemApiService { + private readonly IOrderService _orderService; + private readonly IProductService _productService; + + public OrderItemApiService(IOrderService orderService + ,IProductService productService) + { + _orderService = orderService; + _productService = productService; + } public IList GetOrderItemsForOrder(Order order, int limit, int page, int sinceId) { - var orderItems = order.OrderItems.AsQueryable(); + var orderItems = _orderService.GetOrderItems(order.Id).AsQueryable(); return new ApiList(orderItems, page - 1, limit); } - + public int GetOrderItemsCount(Order order) { - var orderItemsCount = order.OrderItems.Count(); + var orderItemsCount = _orderService.GetOrderItems(order.Id).Count(); return orderItemsCount; } + } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/ProductApiService.cs b/Nop.Plugin.Api/Services/ProductApiService.cs index 0a55e9e..1733454 100644 --- a/Nop.Plugin.Api/Services/ProductApiService.cs +++ b/Nop.Plugin.Api/Services/ProductApiService.cs @@ -1,23 +1,24 @@ using System; using System.Collections.Generic; using System.Linq; -using Nop.Core.Data; +using Nop.Data; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Vendors; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.DataStructures; +using Nop.Plugin.Api.Infrastructure; using Nop.Services.Stores; namespace Nop.Plugin.Api.Services { public class ProductApiService : IProductApiService { - private readonly IStoreMappingService _storeMappingService; - private readonly IRepository _productRepository; private readonly IRepository _productCategoryMappingRepository; + private readonly IRepository _productRepository; + private readonly IStoreMappingService _storeMappingService; private readonly IRepository _vendorRepository; - public ProductApiService(IRepository productRepository, + public ProductApiService( + IRepository productRepository, IRepository productCategoryMappingRepository, IRepository vendorRepository, IStoreMappingService storeMappingService) @@ -28,10 +29,12 @@ public ProductApiService(IRepository productRepository, _storeMappingService = storeMappingService; } - public IList GetProducts(IList ids = null, + public IList GetProducts( + IList ids = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, - int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId, - int? categoryId = null, string vendorName = null, bool? publishedStatus = null) + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId, + int? categoryId = null, string vendorName = null, bool? publishedStatus = null) { var query = GetProductsQuery(createdAtMin, createdAtMax, updatedAtMin, updatedAtMax, vendorName, publishedStatus, ids, categoryId); @@ -42,9 +45,10 @@ public IList GetProducts(IList ids = null, return new ApiList(query, page - 1, limit); } - - public int GetProductsCount(DateTime? createdAtMin = null, DateTime? createdAtMax = null, - DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, bool? publishedStatus = null, string vendorName = null, + + public int GetProductsCount( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, + DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, bool? publishedStatus = null, string vendorName = null, int? categoryId = null) { var query = GetProductsQuery(createdAtMin, createdAtMax, updatedAtMin, updatedAtMax, vendorName, @@ -56,7 +60,9 @@ public int GetProductsCount(DateTime? createdAtMin = null, DateTime? createdAtMa public Product GetProductById(int productId) { if (productId == 0) + { return null; + } return _productRepository.Table.FirstOrDefault(product => product.Id == productId && !product.Deleted); } @@ -64,15 +70,18 @@ public Product GetProductById(int productId) public Product GetProductByIdNoTracking(int productId) { if (productId == 0) + { return null; + } return _productRepository.Table.FirstOrDefault(product => product.Id == productId && !product.Deleted); } - private IQueryable GetProductsQuery(DateTime? createdAtMin = null, DateTime? createdAtMax = null, - DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, string vendorName = null, + private IQueryable GetProductsQuery( + DateTime? createdAtMin = null, DateTime? createdAtMax = null, + DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, string vendorName = null, bool? publishedStatus = null, IList ids = null, int? categoryId = null) - + { var query = _productRepository.Table; @@ -101,7 +110,7 @@ private IQueryable GetProductsQuery(DateTime? createdAtMin = null, Date if (updatedAtMin != null) { - query = query.Where(c => c.UpdatedOnUtc > updatedAtMin.Value); + query = query.Where(c => c.UpdatedOnUtc > updatedAtMin.Value); } if (updatedAtMax != null) @@ -133,4 +142,4 @@ join productCategoryMapping in categoryMappingsForProduct on product.Id equals p return query; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/ProductAttributeConverter.cs b/Nop.Plugin.Api/Services/ProductAttributeConverter.cs index 4404035..3a74a74 100644 --- a/Nop.Plugin.Api/Services/ProductAttributeConverter.cs +++ b/Nop.Plugin.Api/Services/ProductAttributeConverter.cs @@ -1,30 +1,31 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; -using Nop.Plugin.Api.DTOs; using System.Xml; -using Nop.Services.Catalog; using Nop.Core.Domain.Catalog; -using Nop.Services.Media; using Nop.Plugin.Api.Converters; -using System.Globalization; +using Nop.Plugin.Api.DTO; +using Nop.Services.Catalog; +using Nop.Services.Media; namespace Nop.Plugin.Api.Services { public class ProductAttributeConverter : IProductAttributeConverter { - private readonly IProductAttributeService _productAttributeService; + private readonly IDownloadService _downloadService; private readonly IProductAttributeParser _productAttributeParser; - private readonly IDownloadService _downloadService; + private readonly IProductAttributeService _productAttributeService; - public ProductAttributeConverter(IProductAttributeService productAttributeService, + public ProductAttributeConverter( + IProductAttributeService productAttributeService, IProductAttributeParser productAttributeParser, IDownloadService downloadService, IApiTypeConverter apiTypeConverter) { _productAttributeService = productAttributeService; _productAttributeParser = productAttributeParser; - _downloadService = downloadService; + _downloadService = downloadService; } public string ConvertToXml(List attributeDtos, int productId) @@ -32,7 +33,9 @@ public string ConvertToXml(List attributeDtos, int prod var attributesXml = ""; if (attributeDtos == null) + { return attributesXml; + } var productAttributes = _productAttributeService.GetProductAttributeMappingsByProductId(productId); foreach (var attribute in productAttributes) @@ -43,106 +46,102 @@ public string ConvertToXml(List attributeDtos, int prod case AttributeControlType.RadioList: case AttributeControlType.ColorSquares: case AttributeControlType.ImageSquares: + { + // there should be only one selected value for this attribute + var selectedAttribute = attributeDtos.Where(x => x.Id == attribute.Id).FirstOrDefault(); + if (selectedAttribute != null) { - // there should be only one selected value for this attribute - var selectedAttribute = attributeDtos.Where(x => x.Id == attribute.Id).FirstOrDefault(); - if (selectedAttribute != null) + int selectedAttributeValue; + var isInt = int.TryParse(selectedAttribute.Value, out selectedAttributeValue); + if (isInt && selectedAttributeValue > 0) { - int selectedAttributeValue; - var isInt = int.TryParse(selectedAttribute.Value, out selectedAttributeValue); - if (isInt && selectedAttributeValue > 0) - { - attributesXml = _productAttributeParser.AddProductAttribute(attributesXml, - attribute, selectedAttributeValue.ToString()); - } + attributesXml = _productAttributeParser.AddProductAttribute(attributesXml, + attribute, selectedAttributeValue.ToString()); } } + } break; - case AttributeControlType.Checkboxes: + case AttributeControlType.Checkboxes: + { + // there could be more than one selected value for this attribute + var selectedAttributes = attributeDtos.Where(x => x.Id == attribute.Id); + foreach (var selectedAttribute in selectedAttributes) { - // there could be more than one selected value for this attribute - var selectedAttributes = attributeDtos.Where(x => x.Id == attribute.Id); - foreach (var selectedAttribute in selectedAttributes) + int selectedAttributeValue; + var isInt = int.TryParse(selectedAttribute.Value, out selectedAttributeValue); + if (isInt && selectedAttributeValue > 0) { - int selectedAttributeValue; - var isInt = int.TryParse(selectedAttribute.Value, out selectedAttributeValue); - if (isInt && selectedAttributeValue > 0) - { - // currently there is no support for attribute quantity - var quantity = 1; - - attributesXml = _productAttributeParser.AddProductAttribute(attributesXml, - attribute, selectedAttributeValue.ToString(), quantity); - } + // currently there is no support for attribute quantity + var quantity = 1; + attributesXml = _productAttributeParser.AddProductAttribute(attributesXml, + attribute, selectedAttributeValue.ToString(), quantity); } } + } break; case AttributeControlType.ReadonlyCheckboxes: + { + //load read-only(already server - side selected) values + var attributeValues = _productAttributeService.GetProductAttributeValues(attribute.Id); + foreach (var selectedAttributeId in attributeValues + .Where(v => v.IsPreSelected) + .Select(v => v.Id) + .ToList()) { - //load read-only(already server - side selected) values - var attributeValues = _productAttributeService.GetProductAttributeValues(attribute.Id); - foreach (var selectedAttributeId in attributeValues - .Where(v => v.IsPreSelected) - .Select(v => v.Id) - .ToList()) - { - attributesXml = _productAttributeParser.AddProductAttribute(attributesXml, - attribute, selectedAttributeId.ToString()); - } - } + attributesXml = _productAttributeParser.AddProductAttribute(attributesXml, + attribute, selectedAttributeId.ToString()); + } + } break; case AttributeControlType.TextBox: case AttributeControlType.MultilineTextbox: - { - var selectedAttribute = attributeDtos.Where(x => x.Id == attribute.Id).FirstOrDefault(); - - if (selectedAttribute != null) - { - attributesXml = _productAttributeParser.AddProductAttribute(attributesXml, - attribute, selectedAttribute.Value); - } + { + var selectedAttribute = attributeDtos.Where(x => x.Id == attribute.Id).FirstOrDefault(); + if (selectedAttribute != null) + { + attributesXml = _productAttributeParser.AddProductAttribute(attributesXml, + attribute, selectedAttribute.Value); } + } break; case AttributeControlType.Datepicker: - { - var selectedAttribute = attributeDtos.Where(x => x.Id == attribute.Id).FirstOrDefault(); + { + var selectedAttribute = attributeDtos.Where(x => x.Id == attribute.Id).FirstOrDefault(); - if (selectedAttribute != null) - { - DateTime selectedDate; + if (selectedAttribute != null) + { + DateTime selectedDate; - // Since nopCommerce uses this format to keep the date in the database to keep it consisten we will expect the same format to be passed - var validDate = DateTime.TryParseExact(selectedAttribute.Value, "D", CultureInfo.CurrentCulture, - DateTimeStyles.None, out selectedDate); + // Since nopCommerce uses this format to keep the date in the database to keep it consisten we will expect the same format to be passed + var validDate = DateTime.TryParseExact(selectedAttribute.Value, "D", CultureInfo.CurrentCulture, + DateTimeStyles.None, out selectedDate); - if (validDate) - { - attributesXml = _productAttributeParser.AddProductAttribute(attributesXml, - attribute, selectedDate.ToString("D")); - } + if (validDate) + { + attributesXml = _productAttributeParser.AddProductAttribute(attributesXml, + attribute, selectedDate.ToString("D")); } } + } break; case AttributeControlType.FileUpload: - { - var selectedAttribute = attributeDtos.Where(x => x.Id == attribute.Id).FirstOrDefault(); + { + var selectedAttribute = attributeDtos.Where(x => x.Id == attribute.Id).FirstOrDefault(); - if (selectedAttribute != null) + if (selectedAttribute != null) + { + Guid downloadGuid; + Guid.TryParse(selectedAttribute.Value, out downloadGuid); + var download = _downloadService.GetDownloadByGuid(downloadGuid); + if (download != null) { - Guid downloadGuid; - Guid.TryParse(selectedAttribute.Value, out downloadGuid); - var download = _downloadService.GetDownloadByGuid(downloadGuid); - if (download != null) - { - attributesXml = _productAttributeParser.AddProductAttribute(attributesXml, - attribute, download.DownloadGuid.ToString()); - } + attributesXml = _productAttributeParser.AddProductAttribute(attributesXml, + attribute, download.DownloadGuid.ToString()); } } - break; - default: + } break; } } @@ -150,13 +149,15 @@ public string ConvertToXml(List attributeDtos, int prod // No Gift Card attributes support yet return attributesXml; - } + } public List Parse(string attributesXml) { var attributeDtos = new List(); if (string.IsNullOrEmpty(attributesXml)) + { return attributeDtos; + } try { @@ -165,7 +166,7 @@ public List Parse(string attributesXml) foreach (XmlNode attributeNode in xmlDoc.SelectNodes(@"//Attributes/ProductAttribute")) { - if (attributeNode.Attributes != null && attributeNode.Attributes["ID"] != null) + if (attributeNode.Attributes?["ID"] != null) { int attributeId; if (int.TryParse(attributeNode.Attributes["ID"].InnerText.Trim(), out attributeId)) @@ -175,13 +176,19 @@ public List Parse(string attributesXml) var value = attributeValue.SelectSingleNode("Value").InnerText.Trim(); // no support for quantity yet //var quantityNode = attributeValue.SelectSingleNode("Quantity"); - attributeDtos.Add(new ProductItemAttributeDto { Id = attributeId, Value = value }); + attributeDtos.Add(new ProductItemAttributeDto + { + Id = attributeId, + Value = value + }); } } } } } - catch { } + catch + { + } return attributeDtos; } diff --git a/Nop.Plugin.Api/Services/ProductAttributesApiService.cs b/Nop.Plugin.Api/Services/ProductAttributesApiService.cs index 9d8e8ec..f308812 100644 --- a/Nop.Plugin.Api/Services/ProductAttributesApiService.cs +++ b/Nop.Plugin.Api/Services/ProductAttributesApiService.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using System.Linq; -using Nop.Core.Data; +using Nop.Data; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.DataStructures; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { @@ -16,8 +16,9 @@ public ProductAttributesApiService(IRepository productAttribut _productAttributesRepository = productAttributesRepository; } - public IList GetProductAttributes(int limit = Configurations.DefaultLimit, - int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId) + public IList GetProductAttributes( + int limit = Constants.Configurations.DefaultLimit, + int page = Constants.Configurations.DefaultPageValue, int sinceId = Constants.Configurations.DefaultSinceId) { var query = GetProductAttributesQuery(sinceId); @@ -32,12 +33,14 @@ public int GetProductAttributesCount() ProductAttribute IProductAttributesApiService.GetById(int id) { if (id <= 0) + { return null; + } return _productAttributesRepository.GetById(id); } - private IQueryable GetProductAttributesQuery(int sinceId = Configurations.DefaultSinceId) + private IQueryable GetProductAttributesQuery(int sinceId = Constants.Configurations.DefaultSinceId) { var query = _productAttributesRepository.Table; @@ -51,4 +54,4 @@ private IQueryable GetProductAttributesQuery(int sinceId = Con return query; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/ProductCategoryMappingsApiService.cs b/Nop.Plugin.Api/Services/ProductCategoryMappingsApiService.cs index 1a950fb..74f9086 100644 --- a/Nop.Plugin.Api/Services/ProductCategoryMappingsApiService.cs +++ b/Nop.Plugin.Api/Services/ProductCategoryMappingsApiService.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using System.Linq; -using Nop.Core.Data; +using Nop.Data; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.DataStructures; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { @@ -16,9 +16,10 @@ public ProductCategoryMappingsApiService(IRepository productCat _productCategoryMappingsRepository = productCategoryMappingsRepository; } - public IList GetMappings(int? productId = null, - int? categoryId = null, int limit = Configurations.DefaultLimit, - int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId) + public IList GetMappings( + int? productId = null, + int? categoryId = null, int limit = Constants.Configurations.DefaultLimit, + int page = Constants.Configurations.DefaultPageValue, int sinceId = Constants.Configurations.DefaultSinceId) { var query = GetMappingsQuery(productId, categoryId, sinceId); @@ -33,13 +34,16 @@ public int GetMappingsCount(int? productId = null, int? categoryId = null) public ProductCategory GetById(int id) { if (id <= 0) + { return null; + } return _productCategoryMappingsRepository.GetById(id); } - private IQueryable GetMappingsQuery(int? productId = null, - int? categoryId = null, int sinceId = Configurations.DefaultSinceId) + private IQueryable GetMappingsQuery( + int? productId = null, + int? categoryId = null, int sinceId = Constants.Configurations.DefaultSinceId) { var query = _productCategoryMappingsRepository.Table; @@ -63,4 +67,4 @@ private IQueryable GetMappingsQuery(int? productId = null, return query; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/ProductManufacturerMappingsApiService.cs b/Nop.Plugin.Api/Services/ProductManufacturerMappingsApiService.cs index 76f8c0d..8f4550b 100644 --- a/Nop.Plugin.Api/Services/ProductManufacturerMappingsApiService.cs +++ b/Nop.Plugin.Api/Services/ProductManufacturerMappingsApiService.cs @@ -1,9 +1,9 @@ -using Nop.Core.Data; +using System.Collections.Generic; +using System.Linq; +using Nop.Data; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.DataStructures; -using System.Collections.Generic; -using System.Linq; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { @@ -16,9 +16,10 @@ public ProductManufacturerMappingsApiService(IRepository pr _productManufacturerMappingsRepository = productManufacturerMappingsRepository; } - public IList GetMappings(int? productId = null, - int? manufacturerId = null, int limit = Configurations.DefaultLimit, - int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId) + public IList GetMappings( + int? productId = null, + int? manufacturerId = null, int limit = Constants.Configurations.DefaultLimit, + int page = Constants.Configurations.DefaultPageValue, int sinceId = Constants.Configurations.DefaultSinceId) { var query = GetMappingsQuery(productId, manufacturerId, sinceId); @@ -33,13 +34,16 @@ public int GetMappingsCount(int? productId = null, int? manufacturerId = null) public ProductManufacturer GetById(int id) { if (id <= 0) + { return null; + } return _productManufacturerMappingsRepository.GetById(id); } - private IQueryable GetMappingsQuery(int? productId = null, - int? manufacturerId = null, int sinceId = Configurations.DefaultSinceId) + private IQueryable GetMappingsQuery( + int? productId = null, + int? manufacturerId = null, int sinceId = Constants.Configurations.DefaultSinceId) { var query = _productManufacturerMappingsRepository.Table; @@ -63,4 +67,4 @@ private IQueryable GetMappingsQuery(int? productId = null, return query; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/ProductPictureService.cs b/Nop.Plugin.Api/Services/ProductPictureService.cs index 4c4aa8d..a8c7f26 100644 --- a/Nop.Plugin.Api/Services/ProductPictureService.cs +++ b/Nop.Plugin.Api/Services/ProductPictureService.cs @@ -1,5 +1,5 @@ using System.Linq; -using Nop.Core.Data; +using Nop.Data; using Nop.Core.Domain.Catalog; namespace Nop.Plugin.Api.Services @@ -16,11 +16,13 @@ public ProductPictureService(IRepository productPictureRepositor public ProductPicture GetProductPictureByPictureId(int pictureId) { if (pictureId == 0) + { return null; + } var query = from pp in _productPictureRepository.Table - where pp.PictureId == pictureId - select pp; + where pp.PictureId == pictureId + select pp; var productPictures = query.ToList(); diff --git a/Nop.Plugin.Api/Services/ShoppingCartItemApiService.cs b/Nop.Plugin.Api/Services/ShoppingCartItemApiService.cs index ca341e2..5cbbcf8 100644 --- a/Nop.Plugin.Api/Services/ShoppingCartItemApiService.cs +++ b/Nop.Plugin.Api/Services/ShoppingCartItemApiService.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; -using Nop.Core.Data; +using Nop.Core; +using Nop.Data; using Nop.Core.Domain.Orders; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.DataStructures; -using Nop.Core; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { @@ -20,12 +20,13 @@ public ShoppingCartItemApiService(IRepository shoppingCartItem _storeContext = storeContext; } - public List GetShoppingCartItems(int? customerId = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, - DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, int limit = Configurations.DefaultLimit, - int page = Configurations.DefaultPageValue) + public List GetShoppingCartItems( + int? customerId = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, + DateTime? updatedAtMin = null, DateTime? updatedAtMax = null, int limit = Constants.Configurations.DefaultLimit, + int page = Constants.Configurations.DefaultPageValue) { var query = GetShoppingCartItemsQuery(customerId, createdAtMin, createdAtMax, - updatedAtMin, updatedAtMax); + updatedAtMin, updatedAtMax); return new ApiList(query, page - 1, limit); } @@ -35,8 +36,9 @@ public ShoppingCartItem GetShoppingCartItem(int id) return _shoppingCartItemsRepository.GetById(id); } - private IQueryable GetShoppingCartItemsQuery(int? customerId = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, - DateTime? updatedAtMin = null, DateTime? updatedAtMax = null) + private IQueryable GetShoppingCartItemsQuery( + int? customerId = null, DateTime? createdAtMin = null, DateTime? createdAtMax = null, + DateTime? updatedAtMin = null, DateTime? updatedAtMax = null) { var query = _shoppingCartItemsRepository.Table; @@ -74,4 +76,4 @@ private IQueryable GetShoppingCartItemsQuery(int? customerId = return query; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/SpecificationAttributesApiService.cs b/Nop.Plugin.Api/Services/SpecificationAttributesApiService.cs index 4ddecf0..1ada6e3 100644 --- a/Nop.Plugin.Api/Services/SpecificationAttributesApiService.cs +++ b/Nop.Plugin.Api/Services/SpecificationAttributesApiService.cs @@ -1,9 +1,9 @@ -using Nop.Core.Data; +using System.Collections.Generic; +using System.Linq; +using Nop.Data; using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.Constants; using Nop.Plugin.Api.DataStructures; -using System.Collections.Generic; -using System.Linq; +using Nop.Plugin.Api.Infrastructure; namespace Nop.Plugin.Api.Services { @@ -12,13 +12,18 @@ public class SpecificationAttributesApiService : ISpecificationAttributeApiServi private readonly IRepository _productSpecificationAttributesRepository; private readonly IRepository _specificationAttributesRepository; - public SpecificationAttributesApiService(IRepository productSpecificationAttributesRepository, IRepository specificationAttributesRepository) + public SpecificationAttributesApiService( + IRepository productSpecificationAttributesRepository, + IRepository specificationAttributesRepository) { _productSpecificationAttributesRepository = productSpecificationAttributesRepository; _specificationAttributesRepository = specificationAttributesRepository; } - public IList GetProductSpecificationAttributes(int? productId = null, int? specificationAttributeOptionId = null, bool? allowFiltering = null, bool? showOnProductPage = null, int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId) + public IList GetProductSpecificationAttributes( + int? productId = null, int? specificationAttributeOptionId = null, bool? allowFiltering = null, bool? showOnProductPage = null, + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId) { var query = _productSpecificationAttributesRepository.Table; @@ -52,7 +57,9 @@ public IList GetProductSpecificationAttributes(in return new ApiList(query, page - 1, limit); } - public IList GetSpecificationAttributes(int limit = Configurations.DefaultLimit, int page = Configurations.DefaultPageValue, int sinceId = Configurations.DefaultSinceId) + public IList GetSpecificationAttributes( + int limit = Constants.Configurations.DefaultLimit, int page = Constants.Configurations.DefaultPageValue, + int sinceId = Constants.Configurations.DefaultSinceId) { var query = _specificationAttributesRepository.Table; @@ -66,4 +73,4 @@ public IList GetSpecificationAttributes(int limit = Conf return new ApiList(query, page - 1, limit); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Services/WebHookService.cs b/Nop.Plugin.Api/Services/WebHookService.cs deleted file mode 100644 index 72986e2..0000000 --- a/Nop.Plugin.Api/Services/WebHookService.cs +++ /dev/null @@ -1,81 +0,0 @@ -//using Nop.Plugin.Api.WebHooks; - -//namespace Nop.Plugin.Api.Services -//{ -// using Microsoft.AspNet.WebHooks; -// using Microsoft.AspNet.WebHooks.Diagnostics; -// using Microsoft.AspNet.WebHooks.Services; -// using Nop.Plugin.Api.Domain; -// using Nop.Plugin.Api.Helpers; -// using System; -// using System.Collections.Generic; -// using System.Web.Http.Tracing; - -// public class WebHookService : IWebHookService -// { -// private IWebHookManager _webHookManager; -// private IWebHookSender _webHookSender; -// private IWebHookStore _webHookStore; -// private IWebHookFilterManager _webHookFilterManager; -// private ILogger _logger; - -// private readonly IConfigManagerHelper _configManagerHelper; - -// public WebHookService(IConfigManagerHelper configManagerHelper,ILogger logger) -// { -// _configManagerHelper = configManagerHelper; -// _logger = logger; -// } - -// public IWebHookFilterManager GetWebHookFilterManager() -// { -// if (_webHookFilterManager == null) -// { -// var filterProviders = new List(); -// filterProviders.Add(new FilterProvider()); -// _webHookFilterManager = new WebHookFilterManager(filterProviders); -// } - -// return _webHookFilterManager; -// } - -// public IWebHookManager GetWebHookManager() -// { -// if (_webHookManager == null) -// { -// _webHookManager = new WebHookManager(GetWebHookStore(), GetWebHookSender(), _logger); -// } - -// return _webHookManager; -// } - -// public IWebHookSender GetWebHookSender() -// { -// if (_webHookSender == null) -// { -// _webHookSender = new ApiWebHookSender(_logger); -// } - -// return _webHookSender; -// } - -// public IWebHookStore GetWebHookStore() -// { -// if (_webHookStore == null) -// { -// var dataSettings = _configManagerHelper.DataSettings; -// Microsoft.AspNet.WebHooks.Config.SettingsDictionary settings = new Microsoft.AspNet.WebHooks.Config.SettingsDictionary(); -// settings.Add("MS_SqlStoreConnectionString", dataSettings.DataConnectionString); -// settings.Connections.Add("MS_SqlStoreConnectionString", new Microsoft.AspNet.WebHooks.Config.ConnectionSettings("MS_SqlStoreConnectionString", dataSettings.DataConnectionString)); - -// Microsoft.AspNet.WebHooks.IWebHookStore store = new Microsoft.AspNet.WebHooks.SqlWebHookStore(settings, _logger); - -// Microsoft.AspNet.WebHooks.Services.CustomServices.SetStore(store); - -// _webHookStore = CustomServices.GetStore(); -// } - -// return _webHookStore; -// } -// } -//} diff --git a/Nop.Plugin.Api/Validators/AddressDtoValidator.cs b/Nop.Plugin.Api/Validators/AddressDtoValidator.cs index 483f540..2266d45 100644 --- a/Nop.Plugin.Api/Validators/AddressDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/AddressDtoValidator.cs @@ -1,16 +1,16 @@ -using Microsoft.AspNetCore.Http; -using Nop.Plugin.Api.DTOs; +using System.Collections.Generic; +using Microsoft.AspNetCore.Http; +using Nop.Plugin.Api.DTO; using Nop.Plugin.Api.Helpers; -using System.Collections.Generic; namespace Nop.Plugin.Api.Validators { public class AddressDtoValidator : BaseDtoValidator { - #region Constructors - public AddressDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, jsonHelper, requestJsonDictionary) + public AddressDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : + base(httpContextAccessor, jsonHelper, requestJsonDictionary) { SetFirstNameRule(); SetLastNameRule(); @@ -68,6 +68,5 @@ private void SetZipPostalCodeRule() } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/BaseDtoValidator.cs b/Nop.Plugin.Api/Validators/BaseDtoValidator.cs index a047f1d..dd1e506 100644 --- a/Nop.Plugin.Api/Validators/BaseDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/BaseDtoValidator.cs @@ -1,20 +1,19 @@ -using FluentValidation; -using FluentValidation.Results; -using FluentValidation.Validators; -using Microsoft.AspNetCore.Http; -using Nop.Plugin.Api.DTOs.Base; -using Nop.Plugin.Api.Helpers; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Net.Http; +using FluentValidation; +using FluentValidation.Results; +using FluentValidation.Validators; +using Microsoft.AspNetCore.Http; +using Nop.Plugin.Api.DTO.Base; +using Nop.Plugin.Api.Helpers; namespace Nop.Plugin.Api.Validators { public abstract class BaseDtoValidator : AbstractValidator where T : BaseDto, new() { - #region Private Fields private Dictionary _requestValuesDictionary; @@ -23,12 +22,12 @@ namespace Nop.Plugin.Api.Validators #region Constructors - public BaseDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) + protected BaseDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) { HttpContextAccessor = httpContextAccessor; JsonHelper = jsonHelper; - // this is hacky - can't make requestJsonDictionary an optional parameter because Nop tries to resolve it + // this is a hack - can't make requestJsonDictionary an optional parameter because Nop tries to resolve it // // when DI (or the Nop Engine) resolves this class, requestJsonDictionary will be empty (length 0) // in this case, HttpMethod should be whatever the current context is @@ -51,30 +50,20 @@ public BaseDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper js #endregion - #region Protected Properties - - protected IHttpContextAccessor HttpContextAccessor { get; private set; } + #region Public Properties - protected Dictionary RequestJsonDictionary - { - get - { - if (_requestValuesDictionary == null) - { - _requestValuesDictionary = GetRequestJsonDictionaryDictionaryFromHttpContext(); - } + public HttpMethod HttpMethod { get; set; } - return _requestValuesDictionary; - } - } + #endregion - protected IJsonHelper JsonHelper { get; private set; } + #region Protected Properties - #endregion + protected IHttpContextAccessor HttpContextAccessor { get; } - #region Public Properties + protected Dictionary RequestJsonDictionary => + _requestValuesDictionary ?? (_requestValuesDictionary = GetRequestJsonDictionaryDictionaryFromHttpContext()); - public HttpMethod HttpMethod { get; set; } + protected IJsonHelper JsonHelper { get; } #endregion @@ -93,10 +82,11 @@ protected void MergeValidationResult(CustomContext validationContext, Validation protected Dictionary GetRequestJsonDictionaryCollectionItemDictionary(string collectionKey, TDto dto) where TDto : BaseDto { - var collectionItems = (List)RequestJsonDictionary[collectionKey]; + var collectionItems = (List) RequestJsonDictionary[collectionKey]; var collectionItemDictionary = collectionItems.FirstOrDefault(x => - ((Dictionary)x).ContainsKey("id") && ((int)(long)((Dictionary)x)["id"]) == dto.Id - ) as Dictionary; + ((Dictionary) x).ContainsKey("id") && + (int) (long) ((Dictionary) x)["id"] == dto.Id + ) as Dictionary; return collectionItemDictionary; } @@ -144,7 +134,7 @@ private Dictionary GetRequestJsonDictionaryDictionaryFromHttpCon if (requestJsonDictionary.ContainsKey(rootPropertyName)) { - requestJsonDictionary = (Dictionary)requestJsonDictionary[rootPropertyName]; + requestJsonDictionary = (Dictionary) requestJsonDictionary[rootPropertyName]; } return requestJsonDictionary; @@ -159,6 +149,5 @@ private void SetRequiredIdRule() } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/CategoryDtoValidator.cs b/Nop.Plugin.Api/Validators/CategoryDtoValidator.cs index c043760..632531b 100644 --- a/Nop.Plugin.Api/Validators/CategoryDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/CategoryDtoValidator.cs @@ -1,16 +1,18 @@ -using Microsoft.AspNetCore.Http; -using Nop.Plugin.Api.DTOs.Categories; +using System.Collections.Generic; +using JetBrains.Annotations; +using Microsoft.AspNetCore.Http; +using Nop.Plugin.Api.DTO.Categories; using Nop.Plugin.Api.Helpers; -using System.Collections.Generic; namespace Nop.Plugin.Api.Validators { + [UsedImplicitly] public class CategoryDtoValidator : BaseDtoValidator { - #region Constructors - public CategoryDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, jsonHelper, requestJsonDictionary) + public CategoryDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : + base(httpContextAccessor, jsonHelper, requestJsonDictionary) { SetNameRule(); } @@ -25,6 +27,5 @@ private void SetNameRule() } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/ClientValidator.cs b/Nop.Plugin.Api/Validators/ClientValidator.cs deleted file mode 100644 index 75e1db0..0000000 --- a/Nop.Plugin.Api/Validators/ClientValidator.cs +++ /dev/null @@ -1,18 +0,0 @@ -using FluentValidation; -using Nop.Services.Localization; - -namespace Nop.Plugin.Api.Validators -{ - using IdentityServer4.Models; - - public class ClientValidator : AbstractValidator - { - public ClientValidator(ILocalizationService localizationService) - { - RuleFor(x => x.ClientName).NotEmpty().WithMessage(localizationService.GetResource("Plugins.Api.Admin.Entities.Client.FieldValidationMessages.Name")); - RuleFor(x => x.ClientId).NotEmpty().WithMessage(localizationService.GetResource("Plugins.Api.Admin.Entities.Client.FieldValidationMessages.ClientId")); - RuleFor(x => x.ClientSecrets).NotEmpty().WithMessage(localizationService.GetResource("Plugins.Api.Admin.Entities.Client.FieldValidationMessages.ClientSecret")); - RuleFor(x => x.RedirectUris).NotEmpty().WithMessage(localizationService.GetResource("Plugins.Api.Admin.Entities.Client.FieldValidationMessages.CallbackUrl")); - } - } -} \ No newline at end of file diff --git a/Nop.Plugin.Api/Validators/CustomerDtoValidator.cs b/Nop.Plugin.Api/Validators/CustomerDtoValidator.cs index c3d475d..20dc4d2 100644 --- a/Nop.Plugin.Api/Validators/CustomerDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/CustomerDtoValidator.cs @@ -1,29 +1,28 @@ -using FluentValidation; -using FluentValidation.Results; -using FluentValidation.Validators; +using System.Collections.Generic; +using System.Net.Http; +using FluentValidation; +using JetBrains.Annotations; using Microsoft.AspNetCore.Http; using Nop.Core.Domain.Customers; -using Nop.Plugin.Api.DTOs; -using Nop.Plugin.Api.DTOs.Customers; +using Nop.Plugin.Api.DTO.Customers; using Nop.Plugin.Api.Helpers; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; namespace Nop.Plugin.Api.Validators { + [UsedImplicitly] public class CustomerDtoValidator : BaseDtoValidator { - #region Private Fields private readonly ICustomerRolesHelper _customerRolesHelper; #endregion - + #region Constructors - public CustomerDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary, ICustomerRolesHelper customerRolesHelper) : base(httpContextAccessor, jsonHelper, requestJsonDictionary) + public CustomerDtoValidator( + IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary, + ICustomerRolesHelper customerRolesHelper) : base(httpContextAccessor, jsonHelper, requestJsonDictionary) { _customerRolesHelper = customerRolesHelper; @@ -72,7 +71,8 @@ private void SetBillingAddressRule() var key = "billing_address"; if (RequestJsonDictionary.ContainsKey(key)) { - RuleFor(c => c.BillingAddress).SetValidator(new AddressDtoValidator(HttpContextAccessor, JsonHelper, (Dictionary)RequestJsonDictionary[key])); + RuleFor(c => c.BillingAddress) + .SetValidator(new AddressDtoValidator(HttpContextAccessor, JsonHelper, (Dictionary) RequestJsonDictionary[key])); } } @@ -81,7 +81,8 @@ private void SetShippingAddressRule() var key = "shipping_address"; if (RequestJsonDictionary.ContainsKey(key)) { - RuleFor(c => c.ShippingAddress).SetValidator(new AddressDtoValidator(HttpContextAccessor, JsonHelper, (Dictionary)RequestJsonDictionary[key])); + RuleFor(c => c.ShippingAddress) + .SetValidator(new AddressDtoValidator(HttpContextAccessor, JsonHelper, (Dictionary) RequestJsonDictionary[key])); } } @@ -106,37 +107,37 @@ private void SetRolesRule() .Must(roles => roles.Count > 0) .WithMessage("role_ids required") .DependentRules(() => RuleFor(dto => dto.RoleIds) - .Must(roleIds => - { - if (customerRoles == null) - { - customerRoles = _customerRolesHelper.GetValidCustomerRoles(roleIds); - } - - var isInGuestAndRegisterRoles = _customerRolesHelper.IsInGuestsRole(customerRoles) && - _customerRolesHelper.IsInRegisteredRole(customerRoles); - - // Customer can not be in guest and register roles simultaneously - return !isInGuestAndRegisterRoles; - }) - .WithMessage("must not be in guest and register roles simultaneously") - .DependentRules(() => RuleFor(dto => dto.RoleIds) - .Must(roleIds => - { - if (customerRoles == null) - { - customerRoles = _customerRolesHelper.GetValidCustomerRoles(roleIds); - } - - var isInGuestOrRegisterRoles = _customerRolesHelper.IsInGuestsRole(customerRoles) || - _customerRolesHelper.IsInRegisteredRole(customerRoles); - - // Customer must be in either guest or register role. - return isInGuestOrRegisterRoles; - }) - .WithMessage("must be in guest or register role") - ) - ); + .Must(roleIds => + { + if (customerRoles == null) + { + customerRoles = _customerRolesHelper.GetValidCustomerRoles(roleIds); + } + + var isInGuestAndRegisterRoles = _customerRolesHelper.IsInGuestsRole(customerRoles) && + _customerRolesHelper.IsInRegisteredRole(customerRoles); + + // Customer can not be in guest and register roles simultaneously + return !isInGuestAndRegisterRoles; + }) + .WithMessage("must not be in guest and register roles simultaneously") + .DependentRules(() => RuleFor(dto => dto.RoleIds) + .Must(roleIds => + { + if (customerRoles == null) + { + customerRoles = _customerRolesHelper.GetValidCustomerRoles(roleIds); + } + + var isInGuestOrRegisterRoles = _customerRolesHelper.IsInGuestsRole(customerRoles) || + _customerRolesHelper.IsInRegisteredRole(customerRoles); + + // Customer must be in either guest or register role. + return isInGuestOrRegisterRoles; + }) + .WithMessage("must be in guest or register role") + ) + ); } } @@ -166,6 +167,5 @@ private void SetShoppingCartItemsRule() } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/FieldsValidator.cs b/Nop.Plugin.Api/Validators/FieldsValidator.cs index ce477cc..64c52fa 100644 --- a/Nop.Plugin.Api/Validators/FieldsValidator.cs +++ b/Nop.Plugin.Api/Validators/FieldsValidator.cs @@ -7,17 +7,6 @@ namespace Nop.Plugin.Api.Validators { public class FieldsValidator : IFieldsValidator { - private static IEnumerable GetPropertiesIntoList(string fields) - { - var properties = fields.ToLowerInvariant() - .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) - .Select(x => x.Trim()) - .Distinct() - .ToList(); - - return properties; - } - public Dictionary GetValidFields(string fields, Type type) { // This check ensures that the fields won't be null, because it can couse exception. @@ -27,8 +16,8 @@ public Dictionary GetValidFields(string fields, Type type) fields = fields.Replace("_", string.Empty); var validFields = new Dictionary(); - var fieldsAsList = GetPropertiesIntoList(fields); - + var fieldsAsList = GetPropertiesIntoList(fields); + foreach (var field in fieldsAsList) { var propertyExists = type.GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) != null; @@ -41,5 +30,19 @@ public Dictionary GetValidFields(string fields, Type type) return validFields; } + + private static IEnumerable GetPropertiesIntoList(string fields) + { + var properties = fields.ToLowerInvariant() + .Split(new[] + { + ',' + }, StringSplitOptions.RemoveEmptyEntries) + .Select(x => x.Trim()) + .Distinct() + .ToList(); + + return properties; + } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/IFieldsValidator.cs b/Nop.Plugin.Api/Validators/IFieldsValidator.cs index 66870ff..26e89cb 100644 --- a/Nop.Plugin.Api/Validators/IFieldsValidator.cs +++ b/Nop.Plugin.Api/Validators/IFieldsValidator.cs @@ -8,4 +8,4 @@ public interface IFieldsValidator //TODO: Why this needs to be dictionary??? Dictionary GetValidFields(string fields, Type type); } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/ManufacturerDtoValidator.cs b/Nop.Plugin.Api/Validators/ManufacturerDtoValidator.cs index 6717dab..21c6f1f 100644 --- a/Nop.Plugin.Api/Validators/ManufacturerDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/ManufacturerDtoValidator.cs @@ -1,16 +1,18 @@ -using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using JetBrains.Annotations; +using Microsoft.AspNetCore.Http; +using Nop.Plugin.Api.DTO.Manufacturers; using Nop.Plugin.Api.Helpers; -using System.Collections.Generic; -using Nop.Plugin.Api.DTOs.Manufacturers; namespace Nop.Plugin.Api.Validators { + [UsedImplicitly] public class ManufacturerDtoValidator : BaseDtoValidator { - #region Constructors - public ManufacturerDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, jsonHelper, requestJsonDictionary) + public ManufacturerDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : + base(httpContextAccessor, jsonHelper, requestJsonDictionary) { SetNameRule(); } @@ -25,6 +27,5 @@ private void SetNameRule() } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/OrderDtoValidator.cs b/Nop.Plugin.Api/Validators/OrderDtoValidator.cs index 5d7d6cb..5de61ba 100644 --- a/Nop.Plugin.Api/Validators/OrderDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/OrderDtoValidator.cs @@ -1,18 +1,20 @@ -using FluentValidation; +using System.Collections.Generic; +using System.Net.Http; +using FluentValidation; +using JetBrains.Annotations; using Microsoft.AspNetCore.Http; -using Nop.Plugin.Api.DTOs.Orders; +using Nop.Plugin.Api.DTO.Orders; using Nop.Plugin.Api.Helpers; -using System.Collections.Generic; -using System.Net.Http; namespace Nop.Plugin.Api.Validators { + [UsedImplicitly] public class OrderDtoValidator : BaseDtoValidator { - #region Constructors - public OrderDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, jsonHelper, requestJsonDictionary) + public OrderDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : + base(httpContextAccessor, jsonHelper, requestJsonDictionary) { SetCustomerIdRule(); SetOrderItemsRule(); @@ -30,7 +32,8 @@ private void SetBillingAddressRule() var key = "billing_address"; if (RequestJsonDictionary.ContainsKey(key)) { - RuleFor(o => o.BillingAddress).SetValidator(new AddressDtoValidator(HttpContextAccessor, JsonHelper, (Dictionary)RequestJsonDictionary[key])); + RuleFor(o => o.BillingAddress) + .SetValidator(new AddressDtoValidator(HttpContextAccessor, JsonHelper, (Dictionary) RequestJsonDictionary[key])); } } @@ -39,7 +42,8 @@ private void SetShippingAddressRule() var key = "shipping_address"; if (RequestJsonDictionary.ContainsKey(key)) { - RuleFor(o => o.ShippingAddress).SetValidator(new AddressDtoValidator(HttpContextAccessor, JsonHelper, (Dictionary)RequestJsonDictionary[key])); + RuleFor(o => o.ShippingAddress) + .SetValidator(new AddressDtoValidator(HttpContextAccessor, JsonHelper, (Dictionary) RequestJsonDictionary[key])); } } @@ -73,6 +77,5 @@ private void SetOrderItemsRule() } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/OrderItemDtoValidator.cs b/Nop.Plugin.Api/Validators/OrderItemDtoValidator.cs index 886ec32..06fbc76 100644 --- a/Nop.Plugin.Api/Validators/OrderItemDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/OrderItemDtoValidator.cs @@ -1,16 +1,16 @@ -using Microsoft.AspNetCore.Http; -using Nop.Plugin.Api.DTOs.OrderItems; +using System.Collections.Generic; +using Microsoft.AspNetCore.Http; +using Nop.Plugin.Api.DTO.OrderItems; using Nop.Plugin.Api.Helpers; -using System.Collections.Generic; namespace Nop.Plugin.Api.Validators { public class OrderItemDtoValidator : BaseDtoValidator { - #region Constructors - public OrderItemDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, jsonHelper, requestJsonDictionary) + public OrderItemDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : + base(httpContextAccessor, jsonHelper, requestJsonDictionary) { SetProductIdRule(); SetQuantityRule(); @@ -31,6 +31,5 @@ private void SetQuantityRule() } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/ProductAttributeCombinationDtoValidator.cs b/Nop.Plugin.Api/Validators/ProductAttributeCombinationDtoValidator.cs index 2b8b643..c71a252 100644 --- a/Nop.Plugin.Api/Validators/ProductAttributeCombinationDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/ProductAttributeCombinationDtoValidator.cs @@ -1,16 +1,20 @@ -using Microsoft.AspNetCore.Http; -using Nop.Plugin.Api.DTOs.Products; +using System.Collections.Generic; +using JetBrains.Annotations; +using Microsoft.AspNetCore.Http; +using Nop.Plugin.Api.DTO.Products; using Nop.Plugin.Api.Helpers; -using System.Collections.Generic; namespace Nop.Plugin.Api.Validators { + [UsedImplicitly] public class ProductAttributeCombinationDtoValidator : BaseDtoValidator { - #region Constructors - public ProductAttributeCombinationDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, jsonHelper, requestJsonDictionary) + public ProductAttributeCombinationDtoValidator( + IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, + jsonHelper, + requestJsonDictionary) { SetAttributesXmlRule(); SetProductIdRule(); @@ -31,6 +35,5 @@ private void SetProductIdRule() } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/ProductAttributeDtoValidator.cs b/Nop.Plugin.Api/Validators/ProductAttributeDtoValidator.cs index db0f379..479c935 100644 --- a/Nop.Plugin.Api/Validators/ProductAttributeDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/ProductAttributeDtoValidator.cs @@ -1,16 +1,18 @@ -using Microsoft.AspNetCore.Http; -using Nop.Plugin.Api.DTOs.ProductAttributes; +using System.Collections.Generic; +using JetBrains.Annotations; +using Microsoft.AspNetCore.Http; +using Nop.Plugin.Api.DTO.ProductAttributes; using Nop.Plugin.Api.Helpers; -using System.Collections.Generic; namespace Nop.Plugin.Api.Validators { + [UsedImplicitly] public class ProductAttributeDtoValidator : BaseDtoValidator { - #region Constructors - public ProductAttributeDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, jsonHelper, requestJsonDictionary) + public ProductAttributeDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : + base(httpContextAccessor, jsonHelper, requestJsonDictionary) { SetNameRule(); } @@ -25,6 +27,5 @@ private void SetNameRule() } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/ProductCategoryMappingDtoValidator.cs b/Nop.Plugin.Api/Validators/ProductCategoryMappingDtoValidator.cs index d6c4ede..1fdab9a 100644 --- a/Nop.Plugin.Api/Validators/ProductCategoryMappingDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/ProductCategoryMappingDtoValidator.cs @@ -1,16 +1,20 @@ -using Microsoft.AspNetCore.Http; -using Nop.Plugin.Api.DTOs.ProductCategoryMappings; +using System.Collections.Generic; +using JetBrains.Annotations; +using Microsoft.AspNetCore.Http; +using Nop.Plugin.Api.DTO.ProductCategoryMappings; using Nop.Plugin.Api.Helpers; -using System.Collections.Generic; namespace Nop.Plugin.Api.Validators { + [UsedImplicitly] public class ProductCategoryMappingDtoValidator : BaseDtoValidator { - #region Constructors - public ProductCategoryMappingDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, jsonHelper, requestJsonDictionary) + public ProductCategoryMappingDtoValidator( + IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, + jsonHelper, + requestJsonDictionary) { SetCategoryIdRule(); SetProductIdRule(); @@ -31,6 +35,5 @@ private void SetProductIdRule() } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/ProductDtoValidator.cs b/Nop.Plugin.Api/Validators/ProductDtoValidator.cs index 673e3ba..218a51f 100644 --- a/Nop.Plugin.Api/Validators/ProductDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/ProductDtoValidator.cs @@ -1,16 +1,18 @@ -using Microsoft.AspNetCore.Http; -using Nop.Plugin.Api.DTOs.Products; +using System.Collections.Generic; +using JetBrains.Annotations; +using Microsoft.AspNetCore.Http; +using Nop.Plugin.Api.DTO.Products; using Nop.Plugin.Api.Helpers; -using System.Collections.Generic; namespace Nop.Plugin.Api.Validators { + [UsedImplicitly] public class ProductDtoValidator : BaseDtoValidator { - #region Constructors - public ProductDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, jsonHelper, requestJsonDictionary) + public ProductDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : + base(httpContextAccessor, jsonHelper, requestJsonDictionary) { SetNameRule(); } @@ -25,6 +27,5 @@ private void SetNameRule() } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/ProductManufacturerMappingDtoValidator.cs b/Nop.Plugin.Api/Validators/ProductManufacturerMappingDtoValidator.cs index 177df5d..b81bb36 100644 --- a/Nop.Plugin.Api/Validators/ProductManufacturerMappingDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/ProductManufacturerMappingDtoValidator.cs @@ -1,17 +1,20 @@ - +using System.Collections.Generic; +using JetBrains.Annotations; using Microsoft.AspNetCore.Http; -using Nop.Plugin.Api.DTOs.ProductManufacturerMappings; +using Nop.Plugin.Api.DTO.ProductManufacturerMappings; using Nop.Plugin.Api.Helpers; -using System.Collections.Generic; namespace Nop.Plugin.Api.Validators { + [UsedImplicitly] public class ProductManufacturerMappingDtoValidator : BaseDtoValidator { - #region Constructors - public ProductManufacturerMappingDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, jsonHelper, requestJsonDictionary) + public ProductManufacturerMappingDtoValidator( + IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, + jsonHelper, + requestJsonDictionary) { SetManufacturerIdRule(); SetProductIdRule(); @@ -32,6 +35,5 @@ private void SetProductIdRule() } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/ProductSpecificationAttributeDtoValidator.cs b/Nop.Plugin.Api/Validators/ProductSpecificationAttributeDtoValidator.cs index d1bf8dd..2a69925 100644 --- a/Nop.Plugin.Api/Validators/ProductSpecificationAttributeDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/ProductSpecificationAttributeDtoValidator.cs @@ -1,15 +1,17 @@ -using FluentValidation; -using Nop.Core.Domain.Catalog; -using Nop.Plugin.Api.DTOs.SpecificationAttributes; -using System; +using System; using System.Collections.Generic; using System.Linq; +using FluentValidation; +using JetBrains.Annotations; +using Nop.Core.Domain.Catalog; +using Nop.Plugin.Api.DTO.SpecificationAttributes; namespace Nop.Plugin.Api.Validators { + [UsedImplicitly] public class ProductSpecificationAttributeDtoValidator : AbstractValidator { - public ProductSpecificationAttributeDtoValidator(string httpMethod, Dictionary passedPropertyValuePaires) + public ProductSpecificationAttributeDtoValidator(string httpMethod, Dictionary passedPropertyValuePairs) { if (string.IsNullOrEmpty(httpMethod) || httpMethod.Equals("post", StringComparison.InvariantCultureIgnoreCase)) { @@ -19,7 +21,7 @@ public ProductSpecificationAttributeDtoValidator(string httpMethod, Dictionary x.Id).GreaterThan(0).WithMessage("invalid id"); - if (passedPropertyValuePaires.ContainsKey("product_id")) + if (passedPropertyValuePairs.ContainsKey("product_id")) { ApplyProductIdRule(); } - if (passedPropertyValuePaires.ContainsKey("attribute_type_id")) + if (passedPropertyValuePairs.ContainsKey("attribute_type_id")) { ApplyAttributeTypeIdRule(); } - if (passedPropertyValuePaires.ContainsKey("specification_attribute_option_id")) + if (passedPropertyValuePairs.ContainsKey("specification_attribute_option_id")) { ApplySpecificationAttributeOptoinIdRule(); } @@ -53,8 +55,9 @@ private void ApplyProductIdRule() private void ApplyAttributeTypeIdRule() { - var specificationAttributeTypes = (SpecificationAttributeType[])Enum.GetValues(typeof(SpecificationAttributeType)); - RuleFor(x => x.AttributeTypeId).InclusiveBetween((int)specificationAttributeTypes.First(), (int)specificationAttributeTypes.Last()).WithMessage("invalid attribute type id"); + var specificationAttributeTypes = (SpecificationAttributeType[]) Enum.GetValues(typeof(SpecificationAttributeType)); + RuleFor(x => x.AttributeTypeId).InclusiveBetween((int) specificationAttributeTypes.First(), (int) specificationAttributeTypes.Last()) + .WithMessage("invalid attribute type id"); } private void ApplySpecificationAttributeOptoinIdRule() @@ -62,4 +65,4 @@ private void ApplySpecificationAttributeOptoinIdRule() RuleFor(x => x.SpecificationAttributeOptionId).GreaterThan(0).WithMessage("invalid specification attribute option id"); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/ShoppingCartItemDtoValidator.cs b/Nop.Plugin.Api/Validators/ShoppingCartItemDtoValidator.cs index 69c5d3e..6589d6f 100644 --- a/Nop.Plugin.Api/Validators/ShoppingCartItemDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/ShoppingCartItemDtoValidator.cs @@ -1,20 +1,20 @@ -using FluentValidation; +using System; +using System.Collections.Generic; +using System.Net.Http; +using FluentValidation; using Microsoft.AspNetCore.Http; using Nop.Core.Domain.Orders; -using Nop.Plugin.Api.DTOs.ShoppingCarts; +using Nop.Plugin.Api.DTO.ShoppingCarts; using Nop.Plugin.Api.Helpers; -using System; -using System.Collections.Generic; -using System.Net.Http; namespace Nop.Plugin.Api.Validators { public class ShoppingCartItemDtoValidator : BaseDtoValidator { - #region Constructors - public ShoppingCartItemDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : base(httpContextAccessor, jsonHelper, requestJsonDictionary) + public ShoppingCartItemDtoValidator(IHttpContextAccessor httpContextAccessor, IJsonHelper jsonHelper, Dictionary requestJsonDictionary) : + base(httpContextAccessor, jsonHelper, requestJsonDictionary) { SetCustomerIdRule(); SetProductIdRule(); @@ -52,8 +52,8 @@ private void SetRentalDateRules() .WithMessage("Please provide a rental start date"); RuleFor(x => x.RentalEndDateUtc) - .NotNull() - .WithMessage("Please provide a rental end date"); + .NotNull() + .WithMessage("Please provide a rental end date"); RuleFor(dto => dto) .Must(dto => dto.RentalStartDateUtc < dto.RentalEndDateUtc) @@ -64,8 +64,8 @@ private void SetRentalDateRules() .WithMessage("Rental start date should be the future date"); RuleFor(dto => dto) - .Must(dto => dto.RentalEndDateUtc > dto.CreatedOnUtc) - .WithMessage("Rental end date should be the future date"); + .Must(dto => dto.RentalEndDateUtc > dto.CreatedOnUtc) + .WithMessage("Rental end date should be the future date"); } } @@ -85,6 +85,5 @@ private void SetShoppingCartTypeRule() } #endregion - } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/SpecificationAttributeDtoValidator.cs b/Nop.Plugin.Api/Validators/SpecificationAttributeDtoValidator.cs index 054dd98..7e0e75c 100644 --- a/Nop.Plugin.Api/Validators/SpecificationAttributeDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/SpecificationAttributeDtoValidator.cs @@ -1,13 +1,15 @@ -using FluentValidation; -using Nop.Plugin.Api.DTOs.SpecificationAttributes; -using System; +using System; using System.Collections.Generic; +using FluentValidation; +using JetBrains.Annotations; +using Nop.Plugin.Api.DTO.SpecificationAttributes; namespace Nop.Plugin.Api.Validators { + [UsedImplicitly] public class SpecificationAttributeDtoValidator : AbstractValidator { - public SpecificationAttributeDtoValidator(string httpMethod, Dictionary passedPropertyValuePaires) + public SpecificationAttributeDtoValidator(string httpMethod, Dictionary passedPropertyValuePairs) { if (string.IsNullOrEmpty(httpMethod) || httpMethod.Equals("post", StringComparison.InvariantCultureIgnoreCase)) { @@ -29,4 +31,4 @@ private void ApplyNameRule() RuleFor(x => x.Name).NotEmpty().WithMessage("invalid name"); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/SpecificationAttributeOptionDtoValidator.cs b/Nop.Plugin.Api/Validators/SpecificationAttributeOptionDtoValidator.cs index a57cefa..57f083a 100644 --- a/Nop.Plugin.Api/Validators/SpecificationAttributeOptionDtoValidator.cs +++ b/Nop.Plugin.Api/Validators/SpecificationAttributeOptionDtoValidator.cs @@ -1,13 +1,15 @@ -using FluentValidation; -using Nop.Plugin.Api.DTOs.SpecificationAttributes; -using System; +using System; using System.Collections.Generic; +using FluentValidation; +using JetBrains.Annotations; +using Nop.Plugin.Api.DTO.SpecificationAttributes; namespace Nop.Plugin.Api.Validators { + [UsedImplicitly] public class SpecificationAttributeOptionDtoValidator : AbstractValidator { - public SpecificationAttributeOptionDtoValidator(string httpMethod, Dictionary passedPropertyValuePaires) + public SpecificationAttributeOptionDtoValidator(string httpMethod, Dictionary passedPropertyValuePairs) { if (string.IsNullOrEmpty(httpMethod) || httpMethod.Equals("post", StringComparison.InvariantCultureIgnoreCase)) { @@ -22,12 +24,12 @@ public SpecificationAttributeOptionDtoValidator(string httpMethod, Dictionary x.Id).GreaterThan(0).WithMessage("invalid id"); - if (passedPropertyValuePaires.ContainsKey("name")) + if (passedPropertyValuePairs.ContainsKey("name")) { ApplyNameRule(); } - if (passedPropertyValuePaires.ContainsKey("specification_attribute_id")) + if (passedPropertyValuePairs.ContainsKey("specification_attribute_id")) { ApplySpecificationAttributeIdRule(); } @@ -44,4 +46,4 @@ private void ApplySpecificationAttributeIdRule() RuleFor(x => x.SpecificationAttributeId).GreaterThan(0).WithMessage("invalid specification attribute id"); } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Validators/TypeValidator.cs b/Nop.Plugin.Api/Validators/TypeValidator.cs index 74463ad..af455b1 100644 --- a/Nop.Plugin.Api/Validators/TypeValidator.cs +++ b/Nop.Plugin.Api/Validators/TypeValidator.cs @@ -10,14 +10,14 @@ namespace Nop.Plugin.Api.Validators { public class TypeValidator { - public List InvalidProperties { get; set; } - public TypeValidator() { InvalidProperties = new List(); } - public bool IsValid(Dictionary propertyValuePaires) + public List InvalidProperties { get; set; } + + public bool IsValid(Dictionary propertyValuePairs) { var isValid = true; @@ -36,7 +36,7 @@ public bool IsValid(Dictionary propertyValuePaires) } } - foreach (var pair in propertyValuePaires) + foreach (var pair in propertyValuePairs) { var isCurrentPropertyValid = true; @@ -59,7 +59,10 @@ public bool IsValid(Dictionary propertyValuePaires) { isCurrentPropertyValid = IsCurrentPropertyValid(elementsType, item); - if (!isCurrentPropertyValid) break; + if (!isCurrentPropertyValid) + { + break; + } } } else @@ -85,7 +88,10 @@ private static bool ValidateNestedProperty(Type propertyType, Dictionary)value); + isCurrentPropertyValid = ValidateNestedProperty(type, (Dictionary) value); } } return isCurrentPropertyValid; } } -} \ No newline at end of file +} diff --git a/Nop.Plugin.Api/Views/Clients/ClientSettings.cshtml b/Nop.Plugin.Api/Views/Clients/ClientSettings.cshtml deleted file mode 100644 index 23f7d9d..0000000 --- a/Nop.Plugin.Api/Views/Clients/ClientSettings.cshtml +++ /dev/null @@ -1,76 +0,0 @@ -@model ClientApiModel - -
-
- -
-
-
-
-
- -
-
- - -
-
-
-
- -
-
- - -
-
-
-
- -
-
- - -
-
-
-
- -
-
- - -
-
-
-
- -
-
- - -
-
-
-
- -
-
- - -
-
-
-
- -
-
- - -
-
-
-
-
-
-
\ No newline at end of file diff --git a/Nop.Plugin.Api/Views/Clients/Create.cshtml b/Nop.Plugin.Api/Views/Clients/Create.cshtml deleted file mode 100644 index a74e4f3..0000000 --- a/Nop.Plugin.Api/Views/Clients/Create.cshtml +++ /dev/null @@ -1,33 +0,0 @@ -@model ClientApiModel - -@{ - Layout = ViewNames.AdminLayout; - - //page title - ViewBag.Title = T("Plugins.Api.Admin.Page.Clients.Create.Title").Text; - //active menu item (system name) - Html.SetActiveMenuItemSystemName("Api-Clients-Menu"); -} - -
- @Html.AntiForgeryToken() - -
-

- @T("Plugins.Api.Admin.Page.Clients.Create.Title") - @Html.ActionLink(T("Plugins.Api.Admin.Client.BackToList").Text, "List") -

-
- - -
-
- - @await Html.PartialAsync(ViewNames.AdminApiClientsCreateOrUpdate, Model) -
\ No newline at end of file diff --git a/Nop.Plugin.Api/Views/Clients/CreateOrUpdate.cshtml b/Nop.Plugin.Api/Views/Clients/CreateOrUpdate.cshtml deleted file mode 100644 index 2a3f6ab..0000000 --- a/Nop.Plugin.Api/Views/Clients/CreateOrUpdate.cshtml +++ /dev/null @@ -1,7 +0,0 @@ -@model ClientApiModel - -
-
- @await Html.PartialAsync(ViewNames.AdminApiClientsSettings, Model) -
-
diff --git a/Nop.Plugin.Api/Views/Clients/Edit.cshtml b/Nop.Plugin.Api/Views/Clients/Edit.cshtml deleted file mode 100644 index 36f3629..0000000 --- a/Nop.Plugin.Api/Views/Clients/Edit.cshtml +++ /dev/null @@ -1,41 +0,0 @@ -@model ClientApiModel - -@{ - Layout = ViewNames.AdminLayout; - - //page title - ViewBag.Title = T("Plugins.Api.Admin.Page.Clients.Edit.Title").Text; - //active menu item (system name) - Html.SetActiveMenuItemSystemName("Api-Clients-Menu"); -} - -
- @Html.HiddenFor(model => model.Id) - @Html.AntiForgeryToken() - -
-

- @T("Plugins.Api.Admin.Page.Clients.Edit.Title") - @Model.ClientName - @Html.ActionLink(T("Plugins.Api.Admin.Client.BackToList").Text, "List") -

-
- - - - - @T("Admin.Common.Delete") - -
-
- - @await Html.PartialAsync(ViewNames.AdminApiClientsCreateOrUpdate, Model) - -
- - \ No newline at end of file diff --git a/Nop.Plugin.Api/Views/Clients/List.cshtml b/Nop.Plugin.Api/Views/Clients/List.cshtml deleted file mode 100644 index f2e9050..0000000 --- a/Nop.Plugin.Api/Views/Clients/List.cshtml +++ /dev/null @@ -1,100 +0,0 @@ -@{ - Layout = ViewNames.AdminLayout; - - //page title - ViewBag.Title = T("Plugins.Api.Admin.Page.Clients.Title").Text; - //active menu item (system name) - Html.SetActiveMenuItemSystemName("Api-Clients-Menu"); -} - -@Html.AntiForgeryToken() - -
-

- @T("Plugins.Api.Admin.Page.Clients.Title") -

- -
- -
-
-
-
-
-
- - -
-
-
-
-
\ No newline at end of file diff --git a/Nop.Plugin.Api/WebHooks/ApiWebHookSender.cs b/Nop.Plugin.Api/WebHooks/ApiWebHookSender.cs deleted file mode 100644 index 4a9761e..0000000 --- a/Nop.Plugin.Api/WebHooks/ApiWebHookSender.cs +++ /dev/null @@ -1,35 +0,0 @@ -//using System.Collections.Generic; -//using Newtonsoft.Json.Linq; - -//namespace Nop.Plugin.Api.WebHooks -//{ -// using Microsoft.AspNet.WebHooks; -// using Microsoft.AspNet.WebHooks.Diagnostics; - -// public class ApiWebHookSender : DataflowWebHookSender -// { -// private const string WebHookIdKey = "WebHookId"; - -// public ApiWebHookSender(ILogger logger) : base(logger) -// { -// } - -// /// -// protected override JObject CreateWebHookRequestBody(WebHookWorkItem workItem) -// { -// JObject data = base.CreateWebHookRequestBody(workItem); - -// Dictionary body = data.ToObject>(); - -// // The web hook id is added to the web hook body. -// // This is required in order to properly validate the web hook. -// // When a web hook is created, it is created with a Secred field. -// // The web hook id and the secret can be stored in the client's database, so that when a web hook is received -// // it can be validated with the secret in the database. -// // This ensures that the web hook is send from the proper location and that it's content were not tampered with. -// body[WebHookIdKey] = workItem.WebHook.Id; - -// return JObject.FromObject(body); -// } -// } -//} diff --git a/Nop.Plugin.Api/WebHooks/FilterProvider.cs b/Nop.Plugin.Api/WebHooks/FilterProvider.cs deleted file mode 100644 index 9f1f9ee..0000000 --- a/Nop.Plugin.Api/WebHooks/FilterProvider.cs +++ /dev/null @@ -1,44 +0,0 @@ -//using System.Collections.ObjectModel; -//using System.Threading.Tasks; -//using Nop.Plugin.Api.Constants; - -//namespace Nop.Plugin.Api.WebHooks -//{ -// using Microsoft.AspNet.WebHooks; - -// public class FilterProvider : IWebHookFilterProvider -// { -// private readonly Collection filters = new Collection -// { -// new WebHookFilter { Name = WebHookNames.CustomersCreate, Description = "A customer has been registered."}, -// new WebHookFilter { Name = WebHookNames.CustomersUpdate, Description = "A customer has been updated."}, -// new WebHookFilter { Name = WebHookNames.CustomersDelete, Description = "A customer has been deleted."}, -// new WebHookFilter { Name = WebHookNames.ProductsCreate, Description = "A product has been created."}, -// new WebHookFilter { Name = WebHookNames.ProductsUpdate, Description = "A product has been updated."}, -// new WebHookFilter { Name = WebHookNames.ProductsDelete, Description = "A product has been deleted."}, -// new WebHookFilter { Name = WebHookNames.ProductsUnmap, Description = "A product has been unmapped from the store."}, -// new WebHookFilter { Name = WebHookNames.CategoriesCreate, Description = "A category has been created."}, -// new WebHookFilter { Name = WebHookNames.CategoriesUpdate, Description = "A category has been updated."}, -// new WebHookFilter { Name = WebHookNames.CategoriesDelete, Description = "A category has been deleted."}, -// new WebHookFilter { Name = WebHookNames.CategoriesUnmap, Description = "A category has been unmapped from the store."}, -// new WebHookFilter { Name = WebHookNames.OrdersCreate, Description = "An order has been created."}, -// new WebHookFilter { Name = WebHookNames.OrdersUpdate, Description = "An order has been updated."}, -// new WebHookFilter { Name = WebHookNames.OrdersDelete, Description = "An order has been deleted."}, -// new WebHookFilter { Name = WebHookNames.ProductCategoryMapsCreate, Description = "A product category map has been created."}, -// new WebHookFilter { Name = WebHookNames.ProductCategoryMapsUpdate, Description = "A product category map has been updated."}, -// new WebHookFilter { Name = WebHookNames.ProductCategoryMapsDelete, Description = "A product category map has been deleted."}, -// new WebHookFilter { Name = WebHookNames.StoresUpdate, Description = "A store has been updated."}, -// new WebHookFilter { Name = WebHookNames.LanguagesCreate, Description = "A language has been created."}, -// new WebHookFilter { Name = WebHookNames.LanguagesUpdate, Description = "A language has been updated."}, -// new WebHookFilter { Name = WebHookNames.LanguagesDelete, Description = "A language has been deleted."}, -// new WebHookFilter { Name = WebHookNames.NewsLetterSubscriptionCreate, Description = "A news letter subscription has been created."}, -// new WebHookFilter { Name = WebHookNames.NewsLetterSubscriptionUpdate, Description = "A news letter subscription has been updated."}, -// new WebHookFilter { Name = WebHookNames.NewsLetterSubscriptionDelete, Description = "A news letter subscription has been deleted."} -// }; - -// public Task> GetFiltersAsync() -// { -// return Task.FromResult(this.filters); -// } -// } -//} diff --git a/Nop.Plugin.Api/WebHooks/NopWebHooksLogger.cs b/Nop.Plugin.Api/WebHooks/NopWebHooksLogger.cs deleted file mode 100644 index 748c436..0000000 --- a/Nop.Plugin.Api/WebHooks/NopWebHooksLogger.cs +++ /dev/null @@ -1,65 +0,0 @@ -//using Microsoft.AspNet.WebHooks.Diagnostics; -//using Nop.Core; -//using Nop.Core.Data; -//using Nop.Core.Domain.Logging; -//using Nop.Core.Infrastructure; -//using Nop.Plugin.Api.Domain; -//using System; -//using System.IO; -//using System.Web.Http.Tracing; - -//namespace Nop.Plugin.Api.WebHooks -//{ -// /// -// /// This Logger is injected into the WebHooks classes that use async calls, which are -// /// executed in different threads and at the time of execution the HttpContext as well its -// /// HttpContext.RequestServices may not be avilable. So any calls to EngineContext.Current.Resolve() will throw -// /// an exception i.e we can't use the nopCommerce ILogger service which tries to resolve the current store etc. -// /// -// public class NopWebHooksLogger : ILogger -// { -// private readonly bool _enableLogging; -// private readonly IRepository _logRepository; - -// private static object lockObject = new object(); - -// public NopWebHooksLogger(ApiSettings apiSettings, IRepository logRepository) -// { -// _enableLogging = apiSettings.EnableLogging; -// _logRepository = logRepository; -// } - -// public void Log(TraceLevel level, string message, Exception ex) -// { -// try -// { -// if (_enableLogging) -// { -// if (message != null) -// { -// lock (lockObject) -// { -// var log = new Log -// { -// LogLevel = LogLevel.Information, -// ShortMessage = message, -// FullMessage = ex?.ToString(), -// IpAddress = "", -// Customer = null, -// PageUrl = "", -// ReferrerUrl = "", -// CreatedOnUtc = DateTime.UtcNow -// }; - -// _logRepository.Insert(log); -// } -// } - -// } -// } -// catch (Exception e) -// { -// } -// } -// } -//} diff --git a/Nop.Plugin.Api/WebHooks/WebHookEventConsumer.cs b/Nop.Plugin.Api/WebHooks/WebHookEventConsumer.cs deleted file mode 100644 index f2ce8eb..0000000 --- a/Nop.Plugin.Api/WebHooks/WebHookEventConsumer.cs +++ /dev/null @@ -1,558 +0,0 @@ -//using System.Collections.Generic; -//using System.Linq; -//using Nop.Core; -//using Nop.Core.Domain.Catalog; -//using Nop.Core.Domain.Common; -//using Nop.Core.Domain.Customers; -//using Nop.Core.Domain.Localization; -//using Nop.Core.Domain.Media; -//using Nop.Core.Events; -//using Nop.Core.Infrastructure; -//using Nop.Plugin.Api.Services; -//using Nop.Services.Events; -//using Nop.Plugin.Api.DTOs.Customers; -//using Nop.Plugin.Api.Constants; -//using Nop.Plugin.Api.DTOs.Products; -//using Nop.Plugin.Api.Helpers; -//using Nop.Plugin.Api.DTOs.Categories; -//using Nop.Core.Domain.Orders; -//using Nop.Core.Domain.Stores; -//using Nop.Plugin.Api.DTOs.Languages; -//using Nop.Plugin.Api.DTOs.Orders; -//using Nop.Plugin.Api.DTOs.ProductCategoryMappings; -//using Nop.Plugin.Api.DTOs.Stores; -//using Nop.Plugin.Api.MappingExtensions; -//using Nop.Services.Catalog; -//using Nop.Services.Stores; - -//namespace Nop.Plugin.Api.WebHooks -//{ -// using Microsoft.AspNet.WebHooks; -// using Nop.Core.Caching; -// using Nop.Core.Domain.Messages; - -// public class WebHookEventConsumer : IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer>, -// IConsumer> -// { -// private IWebHookManager _webHookManager; -// private readonly ICustomerApiService _customerApiService; -// private readonly ICategoryApiService _categoryApiService; -// private readonly IProductApiService _productApiService; -// private readonly IProductService _productService; -// private readonly ICategoryService _categoryService; -// private readonly IStoreMappingService _storeMappingService; -// private readonly IProductPictureService _productPictureService; -// private readonly IStaticCacheManager _cacheManager; - -// private IDTOHelper _dtoHelper; - -// public WebHookEventConsumer(IStoreService storeService) -// { -// _customerApiService = EngineContext.Current.Resolve(); -// _categoryApiService = EngineContext.Current.Resolve(); -// _productApiService = EngineContext.Current.Resolve(); -// _dtoHelper = EngineContext.Current.Resolve(); -// _productPictureService = EngineContext.Current.Resolve(); -// _productService = EngineContext.Current.Resolve(); -// _categoryService = EngineContext.Current.Resolve(); -// _storeMappingService = EngineContext.Current.Resolve(); -// _cacheManager = EngineContext.Current.Resolve(); -// } - -// private IWebHookManager WebHookManager -// { -// get -// { -// if (_webHookManager == null) -// { -// IWebHookService webHookService = EngineContext.Current.Resolve(); -// _webHookManager = webHookService.GetWebHookManager(); -// } - -// return _webHookManager; -// } -// } - -// public void HandleEvent(EntityInsertedEvent eventMessage) -// { -// // There is no need to send webhooks for guest customers. -// if (eventMessage.Entity.IsGuest()) -// { -// return; -// } - -// CustomerDto customer = _customerApiService.GetCustomerById(eventMessage.Entity.Id); -// var storeIds = new List(); - -// if (customer.RegisteredInStoreId.HasValue) -// { -// storeIds.Add(customer.RegisteredInStoreId.Value); -// } - -// NotifyRegisteredWebHooks(customer, WebHookNames.CustomersCreate, storeIds); -// } - -// public void HandleEvent(EntityUpdatedEvent eventMessage) -// { -// // There is no need to send webhooks for guest customers. -// if (eventMessage.Entity.IsGuest()) -// { -// return; -// } - -// CustomerDto customer = _customerApiService.GetCustomerById(eventMessage.Entity.Id, true); - -// // In nopCommerce the Customer, Product, Category and Order entities are not deleted. -// // Instead the Deleted property of the entity is set to true. -// string webhookEvent = WebHookNames.CustomersUpdate; - -// if (customer.Deleted == true) -// { -// webhookEvent = WebHookNames.CustomersDelete; -// } - -// var storeIds = new List(); - -// if (customer.RegisteredInStoreId.HasValue) -// { -// storeIds.Add(customer.RegisteredInStoreId.Value); -// } - -// NotifyRegisteredWebHooks(customer, webhookEvent, storeIds); -// } - -// public void HandleEvent(EntityInsertedEvent eventMessage) -// { -// ProductDto productDto = _dtoHelper.PrepareProductDTO(eventMessage.Entity); - -// // The Store mappings of the product are still not saved, so all webhooks will be triggered -// // no matter for which store are registered. -// NotifyRegisteredWebHooks(productDto, WebHookNames.ProductsCreate, productDto.StoreIds); -// } - -// public void HandleEvent(EntityUpdatedEvent eventMessage) -// { -// ProductDto productDto = _dtoHelper.PrepareProductDTO(eventMessage.Entity); - -// ProductUpdated(productDto); -// } - -// public void HandleEvent(EntityInsertedEvent eventMessage) -// { -// CategoryDto categoryDto = _dtoHelper.PrepareCategoryDTO(eventMessage.Entity); - -// // The Store mappings of the category are still not saved, so all webhooks will be triggered -// // no matter for which store are registered. -// NotifyRegisteredWebHooks(categoryDto, WebHookNames.CategoriesCreate, categoryDto.StoreIds); -// } - -// public void HandleEvent(EntityUpdatedEvent eventMessage) -// { -// CategoryDto categoryDto = _dtoHelper.PrepareCategoryDTO(eventMessage.Entity); - -// string webhookEvent = WebHookNames.CategoriesUpdate; - -// if (categoryDto.Deleted == true) -// { -// webhookEvent = WebHookNames.CategoriesDelete; -// } - -// NotifyRegisteredWebHooks(categoryDto, webhookEvent, categoryDto.StoreIds); -// } - -// public void HandleEvent(EntityInsertedEvent eventMessage) -// { -// OrderDto orderDto = _dtoHelper.PrepareOrderDTO(eventMessage.Entity); - -// var storeIds = new List(); - -// if (orderDto.StoreId.HasValue) -// { -// storeIds.Add(orderDto.StoreId.Value); -// } - -// NotifyRegisteredWebHooks(orderDto, WebHookNames.OrdersCreate, storeIds); -// } - -// public void HandleEvent(EntityUpdatedEvent eventMessage) -// { -// OrderDto orderDto = _dtoHelper.PrepareOrderDTO(eventMessage.Entity); - -// string webhookEvent = WebHookNames.OrdersUpdate; - -// if (orderDto.Deleted == true) -// { -// webhookEvent = WebHookNames.OrdersDelete; -// } - -// var storeIds = new List(); - -// if (orderDto.StoreId.HasValue) -// { -// storeIds.Add(orderDto.StoreId.Value); -// } - -// NotifyRegisteredWebHooks(orderDto, webhookEvent, storeIds); -// } - -// public void HandleEvent(EntityInsertedEvent eventMessage) -// { -// HandleStoreMappingEvent(eventMessage.Entity.EntityId, eventMessage.Entity.EntityName); -// } - -// public void HandleEvent(EntityDeletedEvent eventMessage) -// { -// HandleStoreMappingEvent(eventMessage.Entity.EntityId, eventMessage.Entity.EntityName); -// } - -// public void HandleEvent(EntityInsertedEvent eventMessage) -// { -// if (eventMessage.Entity.Key == NopCustomerDefaults.FirstNameAttribute || -// eventMessage.Entity.Key == NopCustomerDefaults.LastNameAttribute || -// eventMessage.Entity.Key == NopCustomerDefaults.LanguageIdAttribute) -// { -// var customerDto = _customerApiService.GetCustomerById(eventMessage.Entity.EntityId); - -// var storeIds = new List(); - -// if (customerDto.RegisteredInStoreId.HasValue) -// { -// storeIds.Add(customerDto.RegisteredInStoreId.Value); -// } - -// NotifyRegisteredWebHooks(customerDto, WebHookNames.CustomersUpdate, storeIds); -// } -// } - -// public void HandleEvent(EntityUpdatedEvent eventMessage) -// { -// if (eventMessage.Entity.Key == NopCustomerDefaults.FirstNameAttribute || -// eventMessage.Entity.Key == NopCustomerDefaults.LastNameAttribute || -// eventMessage.Entity.Key == NopCustomerDefaults.LanguageIdAttribute) -// { -// var customerDto = _customerApiService.GetCustomerById(eventMessage.Entity.EntityId); - -// var storeIds = new List(); - -// if (customerDto.RegisteredInStoreId.HasValue) -// { -// storeIds.Add(customerDto.RegisteredInStoreId.Value); -// } - -// NotifyRegisteredWebHooks(customerDto, WebHookNames.CustomersUpdate, storeIds); -// } -// } - -// public void HandleEvent(EntityUpdatedEvent eventMessage) -// { -// StoreDto storeDto = _dtoHelper.PrepareStoreDTO(eventMessage.Entity); - -// int storeId; - -// if (int.TryParse(storeDto.Id, out storeId)) -// { -// var storeIds = new List(); -// storeIds.Add(storeId); - -// NotifyRegisteredWebHooks(storeDto, WebHookNames.StoresUpdate, storeIds); -// } -// } - -// public void HandleEvent(EntityInsertedEvent eventMessage) -// { -// NotifyProductCategoryMappingWebhook(eventMessage.Entity, WebHookNames.ProductCategoryMapsCreate); -// } - -// public void HandleEvent(EntityUpdatedEvent eventMessage) -// { -// NotifyProductCategoryMappingWebhook(eventMessage.Entity, WebHookNames.ProductCategoryMapsUpdate); -// } - -// public void HandleEvent(EntityDeletedEvent eventMessage) -// { -// NotifyProductCategoryMappingWebhook(eventMessage.Entity, WebHookNames.ProductCategoryMapsDelete); -// } - -// public void HandleEvent(EntityInsertedEvent eventMessage) -// { -// LanguageDto langaDto = _dtoHelper.PrepateLanguageDto(eventMessage.Entity); - -// NotifyRegisteredWebHooks(langaDto, WebHookNames.LanguagesCreate, langaDto.StoreIds); -// } - -// public void HandleEvent(EntityUpdatedEvent eventMessage) -// { -// LanguageDto langaDto = _dtoHelper.PrepateLanguageDto(eventMessage.Entity); - -// NotifyRegisteredWebHooks(langaDto, WebHookNames.LanguagesUpdate, langaDto.StoreIds); -// } - -// public void HandleEvent(EntityDeletedEvent eventMessage) -// { -// LanguageDto langaDto = _dtoHelper.PrepateLanguageDto(eventMessage.Entity); - -// NotifyRegisteredWebHooks(langaDto, WebHookNames.LanguagesDelete, langaDto.StoreIds); -// } - -// public void HandleEvent(EntityInsertedEvent eventMessage) -// { -// var product = _productApiService.GetProductById(eventMessage.Entity.ProductId); - -// if (product != null) -// { -// ProductDto productDto = _dtoHelper.PrepareProductDTO(product); - -// ProductUpdated(productDto); -// } -// } - -// public void HandleEvent(EntityUpdatedEvent eventMessage) -// { -// var product = _productApiService.GetProductById(eventMessage.Entity.ProductId); - -// if (product != null) -// { -// ProductDto productDto = _dtoHelper.PrepareProductDTO(product); - -// ProductUpdated(productDto); -// } -// } - -// public void HandleEvent(EntityDeletedEvent eventMessage) -// { -// var product = _productApiService.GetProductById(eventMessage.Entity.ProductId); - -// if (product != null) -// { -// ProductDto productDto = _dtoHelper.PrepareProductDTO(product); - -// ProductUpdated(productDto); -// } -// } - -// // We trigger a product updated WebHook when a picture used in a product is updated. -// // This is required, because when the product title is changed, the product is updated first -// // and then the picture urls are chaged. In order for the WebHook consumer to have the latest -// // product picture urls the following code is used. -// public void HandleEvent(EntityUpdatedEvent eventMessage) -// { -// var productPicture = _productPictureService.GetProductPictureByPictureId(eventMessage.Entity.Id); - -// if (productPicture != null) -// { -// var product = _productApiService.GetProductById(productPicture.ProductId); - -// if (product != null) -// { -// ProductDto productDto = _dtoHelper.PrepareProductDTO(product); - -// ProductUpdated(productDto); -// } -// } -// } - -// public void HandleEvent(EntityDeletedEvent eventMessage) -// { -// _cacheManager.RemoveByPattern(Configurations.NEWSLETTER_SUBSCRIBERS_KEY); - -// NewsLetterSubscriptionDto newsLetterSubscriptionDto = eventMessage.Entity.ToDto(); - -// var storeIds = new List -// { -// newsLetterSubscriptionDto.StoreId -// }; - -// NotifyRegisteredWebHooks(newsLetterSubscriptionDto, WebHookNames.NewsLetterSubscriptionDelete, storeIds); -// } - -// public void HandleEvent(EntityInsertedEvent eventMessage) -// { -// _cacheManager.RemoveByPattern(Configurations.NEWSLETTER_SUBSCRIBERS_KEY); - -// NewsLetterSubscriptionDto newsLetterSubscriptionDto = eventMessage.Entity.ToDto(); - -// var storeIds = new List -// { -// newsLetterSubscriptionDto.StoreId -// }; - -// NotifyRegisteredWebHooks(newsLetterSubscriptionDto, WebHookNames.NewsLetterSubscriptionCreate, storeIds); -// } - -// public void HandleEvent(EntityUpdatedEvent eventMessage) -// { -// _cacheManager.RemoveByPattern(Configurations.NEWSLETTER_SUBSCRIBERS_KEY); - -// NewsLetterSubscriptionDto newsLetterSubscriptionDto = eventMessage.Entity.ToDto(); - -// var storeIds = new List -// { -// newsLetterSubscriptionDto.StoreId -// }; - -// NotifyRegisteredWebHooks(newsLetterSubscriptionDto, WebHookNames.NewsLetterSubscriptionUpdate, storeIds); -// } - -// private void NotifyProductCategoryMappingWebhook(ProductCategory productCategory, string eventName) -// { -// var storeIds = GetStoreIdsForProductCategoryMap(productCategory); - -// if (storeIds == null) -// { -// return; -// } - -// ProductCategoryMappingDto productCategoryMappingDto = productCategory.ToDto(); - -// NotifyRegisteredWebHooks(productCategoryMappingDto, eventName, storeIds); -// } - -// private List GetStoreIdsForProductCategoryMap(ProductCategory productCategory) -// { -// // Send a webhook event only for the stores that can access the product and category -// // in the current product category map. -// Product product = _productService.GetProductById(productCategory.ProductId); -// Category category = _categoryService.GetCategoryById(productCategory.CategoryId); - -// if (product == null || category == null) -// { -// return null; -// } - -// var productStoreIds = _storeMappingService.GetStoresIdsWithAccess(product); - -// var categoryStoreIds = _storeMappingService.GetStoresIdsWithAccess(category); - -// return productStoreIds.Intersect(categoryStoreIds).ToList(); -// } - -// private void ProductUpdated(ProductDto productDto) -// { -// string webhookEvent = WebHookNames.ProductsUpdate; - -// if (productDto.Deleted == true) -// { -// webhookEvent = WebHookNames.ProductsDelete; -// } - -// NotifyRegisteredWebHooks(productDto, webhookEvent, productDto.StoreIds); -// } - -// private void HandleStoreMappingEvent(int entityId, string entityName) -// { -// // When creating or editing a category after saving the store mapping the category is not updated -// // so we should listen for StoreMapping update/delete and fire a webhook with the updated entityDto(with correct storeIds). -// if (entityName == "Category") -// { -// var category = _categoryApiService.GetCategoryById(entityId); - -// if (category != null) -// { -// CategoryDto categoryDto = _dtoHelper.PrepareCategoryDTO(category); - -// string webhookEvent = WebHookNames.CategoriesUpdate; - -// if (categoryDto.Deleted == true) -// { -// webhookEvent = WebHookNames.CategoriesDelete; -// } - -// NotifyRegisteredWebHooks(categoryDto, webhookEvent, categoryDto.StoreIds); -// } -// } -// else if (entityName == "Product") -// { -// var product = _productApiService.GetProductById(entityId); - -// if (product != null) -// { -// ProductDto productDto = _dtoHelper.PrepareProductDTO(product); - -// string webhookEvent = WebHookNames.ProductsUpdate; - -// if (productDto.Deleted == true) -// { -// webhookEvent = WebHookNames.ProductsDelete; -// } - -// NotifyRegisteredWebHooks(productDto, webhookEvent, productDto.StoreIds); -// } -// } -// } - -// private void NotifyRegisteredWebHooks(T entityDto, string webhookEvent, List storeIds) -// { -// if (storeIds.Count > 0) -// { -// // Notify all webhooks that the entity is mapped to their store. -// WebHookManager.NotifyAllAsync(webhookEvent, new { Item = entityDto }, (hook, hookUser) => IsEntityMatchingTheWebHookStoreId(hookUser, storeIds)); - -// if (typeof(T) == typeof(ProductDto) || typeof(T) == typeof(CategoryDto)) -// { -// NotifyUnmappedEntityWebhooks(entityDto, storeIds); -// } -// } -// else -// { -// WebHookManager.NotifyAllAsync(webhookEvent, new { Item = entityDto }); -// } -// } - -// private void NotifyUnmappedEntityWebhooks(T entityDto, List storeIds) -// { -// if (typeof(T) == typeof(ProductDto)) -// { -// // The product is not mapped to the store. -// // Notify all webhooks that the entity is not mapped to their store. -// WebHookManager.NotifyAllAsync(WebHookNames.ProductsUnmap, new { Item = entityDto }, -// (hook, hookUser) => !IsEntityMatchingTheWebHookStoreId(hookUser, storeIds)); -// } -// else if (typeof(T) == typeof(CategoryDto)) -// { -// // The category is not mapped to the store. -// // Notify all webhooks that the entity is not mapped to their store. -// WebHookManager.NotifyAllAsync(WebHookNames.CategoriesUnmap, new { Item = entityDto }, -// (hook, hookUser) => !IsEntityMatchingTheWebHookStoreId(hookUser, storeIds)); -// } -// } - -// private bool IsEntityMatchingTheWebHookStoreId(string webHookUser, List storeIds) -// { -// // When we register the webhooks we add "-storeId" at the end of the webHookUser string. -// // That way we can check to which store is mapped the webHook. -// foreach (var id in storeIds) -// { -// if (webHookUser.EndsWith("-" + id)) -// { -// return true; -// } -// } - -// return false; -// } -// } -//} diff --git a/Nop.Plugin.Api/plugin.json b/Nop.Plugin.Api/plugin.json index 9e9cba6..b0170da 100644 --- a/Nop.Plugin.Api/plugin.json +++ b/Nop.Plugin.Api/plugin.json @@ -3,7 +3,7 @@ "FriendlyName": "Api plugin", "SystemName": "Nop.Plugin.Api", "Version": "4.2.0", - "SupportedVersions": [ "4.20" ], + "SupportedVersions": [ "4.30" ], "Author": "Nop-Templates team", "DisplayOrder": -1, "FileName": "Nop.Plugin.Api.dll", diff --git a/Nop.Plugin.Api/upgrade_script.sql b/Nop.Plugin.Api/upgrade_script.sql deleted file mode 100644 index 0643f57..0000000 --- a/Nop.Plugin.Api/upgrade_script.sql +++ /dev/null @@ -1,74 +0,0 @@ --- Used to migrate the clients tables used prior to 4.0 into the tables used by the Identity Server -- - -BEGIN TRANSACTION; - - -- Clients -- - Insert into Clients - Select 2592000 as AbsoluteRefreshTokenLifetime, - 3600 as AccessTokenLifetime, - 0 as AccessTokenType, - 0 as AllowAccessTokensViaBrowser, - 1 as AllowOfflineAccess, - 0 as AllowPlainTextPkce, - 1 as AllowRememberConsent, - 0 as AlwaysIncludeUserClaimsInIdToken, - 0 as AlwaysSendClientClaims, - 300 as AuthorizationCodeLifetime, - [ClientId] as ClientId, - [Name] as ClientName, - NULL as ClientUri, - 1 as EnableLocalLogin, - [IsActive] as [Enabled], - 300 as IdentityTokenLifetime, - 0 as IncludeJwtId, - NULL as LogoUri, - 'oidc' as ProtocolType, - 1 as RefreshTokenExpiration, - 1 as RefreshTokenUsage, - 1 as RequireClientSecret, - 1 as RequireConsent, - 0 as RequirePkce, - 1296000 as SlidingRefreshTokenLifetime, - 0 as UpdateAccessTokenClaimsOnRefresh, - 1 as BackChannelLogoutSessionRequired, - NULL as BackChannelLogoutUri, - 'client_' as ClientClaimsPrefix, - NULL as ConsentLifetime, - NULL as [Description], - 1 as FrontChannelLogoutSessionRequired, - NULL as FrontChannelLogoutUri, - NULL as PairWiseSubjectSalt from API_Clients - - -- ClientClaims -- - Insert into ClientClaims - Select Id as ClientId, 'sub' as [Type], ClientId as [Value] from Clients - - Insert into ClientClaims - Select Id as ClientId, 'name' as [Type], [ClientName] as [Value] from Clients - - -- ClientGrantTypes -- - Insert into ClientGrantTypes - Select Id as ClientId, 'authorization_code' as GrantType from Clients - - Insert into ClientGrantTypes - Select Id as ClientId, 'refresh_token' as GrantType from Clients - - Insert into ClientGrantTypes - Select Id as ClientId, 'urn:ietf:params:oauth:grant-type:jwt-bearer' as GrantType from Clients - - -- ClientRedirectUris -- - Insert into ClientRedirectUris - Select Client_id as ClientId, CallbackUrl as RedirectUri from (Select Clients.Id as Client_id, Clients.ClientId, CallbackUrl from Clients - inner join API_Clients on Clients.ClientId = API_Clients.ClientId) as JoinedClients - -- ClientScopes -- - Insert into ClientScopes - Select Id as ClientId, 'nop_api' as Scope from Clients - - -- ClientSecrets -- - Insert into ClientSecrets - Select Client_id as ClientId, ClientSecret as [Description], NULL as Expiration, 'SharedSecret' as [Type], ClientSecret as [Value] - from (Select Clients.Id as Client_id, Clients.ClientId, ClientSecret from Clients - inner join API_Clients on Clients.ClientId = API_Clients.ClientId) as JoinedClients - - drop table API_Clients; -COMMIT; \ No newline at end of file diff --git a/README.md b/README.md index a71fdc9..8cb0a66 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# API plugin for nopCommerce +# API plugin for nopCommerce 4.3 This plugin provides a RESTful API for managing resources in nopCommerce. @@ -18,7 +18,7 @@ In a HTTP request, you need to define the type of action that you want to perfor **DELETE** (Delete) -A resource is a data object that can be accessed via an HTTP request. The API allows you to “access your nopCommerce site’s data (resources) through an easy-to-use HTTP REST API”. In the case of the most recent version of the API (nopCommerce version 3.80), the resources include the following 7 nopCommerce objects: +A resource is a data object that can be accessed via an HTTP request. The API allows you to “access your nopCommerce site’s data (resources) through an easy-to-use HTTP REST API”. In the case of the most recent version of the API (nopCommerce version 4.30), the resources include the following 7 nopCommerce objects: [**Customers**](Customers.md) @@ -38,4 +38,4 @@ With the nopCommerce API, you can perform any of the four CRUD actions against a ## What about security? -The API plugin currently supports OAuth 2.0 Authorization Code grant type flow. So in order to access the resource endpoints you need to provide a valid AccessToken. To understand how the authorization code grant flow works please refer to the [**Sample Application**](https://github.com/SevenSpikes/nopCommerce-Api-SampleApplication). +## The API plugin currently supports only JWT Bearer Authentication. Will add support of OAuth 2.0 Authorization Code grant type flow later.