Exemple #1
0
        /// <summary>
        /// Renders a view to string.
        /// </summary>
        public async Task <string> RenderToStringAsync(string viewName, object model, HttpContext httpContext = null)
        {
            if (httpContext == null)
            {
                httpContext = new DefaultHttpContext {
                    RequestServices = _serviceProvider
                }
            }
            ;

            var actionContext = new ActionContext(httpContext, httpContext.GetRouteData(), new ActionDescriptor());

            using var sw = new StringWriter();
            var viewResult = _razorViewEngine.GetView("", viewName, false);

            if (viewResult.View == null)
            {
                throw new ArgumentNullException($"{viewName} does not match any available view.");
            }

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

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

            await viewResult.View.RenderAsync(viewContext);

            return(sw.ToString());
        }

        #endregion
    }
Exemple #2
0
        public async Task Invoke_BackCompatGetRouteValue_ValueUsedFromEndpointFeature()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();

            httpContext.RequestServices = new TestServiceProvider();

            var middleware = CreateMiddleware();

            // Act
            await middleware.Invoke(httpContext);

            var routeData       = httpContext.GetRouteData();
            var routeValue      = httpContext.GetRouteValue("controller");
            var endpointFeature = httpContext.Features.Get <IEndpointFeature>();

            // Assert
            Assert.NotNull(routeData);
            Assert.Equal("Home", (string)routeValue);

            // changing route data value is reflected in endpoint feature values
            routeData.Values["testKey"] = "testValue";
            Assert.Equal("testValue", endpointFeature.Values["testKey"]);
        }
        static BaseNopTest()
        {
            TypeDescriptor.AddAttributes(typeof(List <int>),
                                         new TypeConverterAttribute(typeof(GenericListTypeConverter <int>)));
            TypeDescriptor.AddAttributes(typeof(List <string>),
                                         new TypeConverterAttribute(typeof(GenericListTypeConverter <string>)));

            var services = new ServiceCollection();

            services.AddHttpClient();

            var memoryCache = new MemoryCache(new MemoryCacheOptions());
            var typeFinder  = new AppDomainTypeFinder();

            Singleton <DataSettings> .Instance = new DataSettings
            {
                ConnectionString = "Data Source=nopCommerceTest.sqlite;Mode=Memory;Cache=Shared"
            };

            var mAssemblies = typeFinder.FindClassesOfType <AutoReversingMigration>()
                              .Select(t => t.Assembly)
                              .Distinct()
                              .ToArray();

            //add configuration parameters
            var appSettings = new AppSettings();

            services.AddSingleton(appSettings);
            Singleton <AppSettings> .Instance = appSettings;

            var hostApplicationLifetime = new Mock <IHostApplicationLifetime>();

            services.AddSingleton(hostApplicationLifetime.Object);

            var rootPath =
                new DirectoryInfo(
                    $@"{Directory.GetCurrentDirectory().Split("bin")[0]}{Path.Combine(@"\..\..\Presentation\Nop.Web".Split('\\', '/').ToArray())}")
                .FullName;

            //Presentation\Nop.Web\wwwroot
            var webHostEnvironment = new Mock <IWebHostEnvironment>();

            webHostEnvironment.Setup(p => p.WebRootPath).Returns(Path.Combine(rootPath, "wwwroot"));
            webHostEnvironment.Setup(p => p.ContentRootPath).Returns(rootPath);
            webHostEnvironment.Setup(p => p.EnvironmentName).Returns("test");
            webHostEnvironment.Setup(p => p.ApplicationName).Returns("nopCommerce");
            services.AddSingleton(webHostEnvironment.Object);

            var httpContext = new DefaultHttpContext
            {
                Request = { Headers = { { HeaderNames.Host, NopTestsDefaults.HostIpAddress } } }
            };

            var httpContextAccessor = new Mock <IHttpContextAccessor>();

            httpContextAccessor.Setup(p => p.HttpContext).Returns(httpContext);

            services.AddSingleton(httpContextAccessor.Object);

            var actionContextAccessor = new Mock <IActionContextAccessor>();

            actionContextAccessor.Setup(x => x.ActionContext)
            .Returns(new ActionContext(httpContext, httpContext.GetRouteData(), new ActionDescriptor()));

            services.AddSingleton(actionContextAccessor.Object);

            var urlHelperFactory = new Mock <IUrlHelperFactory>();
            var urlHelper        = new NopTestUrlHelper(actionContextAccessor.Object.ActionContext);

            urlHelperFactory.Setup(x => x.GetUrlHelper(It.IsAny <ActionContext>()))
            .Returns(urlHelper);

            services.AddTransient(provider => actionContextAccessor.Object);

            services.AddSingleton(urlHelperFactory.Object);

            var tempDataDictionaryFactory = new Mock <ITempDataDictionaryFactory>();
            var dataDictionary            = new TempDataDictionary(httpContextAccessor.Object.HttpContext,
                                                                   new Mock <ITempDataProvider>().Object);

            tempDataDictionaryFactory.Setup(f => f.GetTempData(It.IsAny <HttpContext>())).Returns(dataDictionary);
            services.AddSingleton(tempDataDictionaryFactory.Object);

            services.AddSingleton <ITypeFinder>(typeFinder);

            //file provider
            services.AddTransient <INopFileProvider, NopFileProvider>();

            //web helper
            services.AddTransient <IWebHelper, WebHelper>();

            //user agent helper
            services.AddTransient <IUserAgentHelper, UserAgentHelper>();

            //data layer
            services.AddTransient <IDataProviderManager, TestDataProviderManager>();
            services.AddTransient <INopDataProvider, SqLiteNopDataProvider>();

            //repositories
            services.AddTransient(typeof(IRepository <>), typeof(EntityRepository <>));

            //plugins
            services.AddTransient <IPluginService, PluginService>();

            services.AddSingleton <IMemoryCache>(memoryCache);
            services.AddSingleton <IStaticCacheManager, MemoryCacheManager>();
            services.AddSingleton <ILocker, MemoryCacheManager>();

            //services
            services.AddTransient <IBackInStockSubscriptionService, BackInStockSubscriptionService>();
            services.AddTransient <ICategoryService, CategoryService>();
            services.AddTransient <ICompareProductsService, CompareProductsService>();
            services.AddTransient <IRecentlyViewedProductsService, RecentlyViewedProductsService>();
            services.AddTransient <IManufacturerService, ManufacturerService>();
            services.AddTransient <IPriceFormatter, PriceFormatter>();
            services.AddTransient <IProductAttributeFormatter, ProductAttributeFormatter>();
            services.AddTransient <IProductAttributeParser, ProductAttributeParser>();
            services.AddTransient <IProductAttributeService, ProductAttributeService>();
            services.AddTransient <IProductService, ProductService>();
            services.AddTransient <ICopyProductService, CopyProductService>();
            services.AddTransient <ISpecificationAttributeService, SpecificationAttributeService>();
            services.AddTransient <IProductTemplateService, ProductTemplateService>();
            services.AddTransient <ICategoryTemplateService, CategoryTemplateService>();
            services.AddTransient <IManufacturerTemplateService, ManufacturerTemplateService>();
            services.AddTransient <ITopicTemplateService, TopicTemplateService>();
            services.AddTransient <IProductTagService, ProductTagService>();
            services.AddTransient <IAddressAttributeFormatter, AddressAttributeFormatter>();
            services.AddTransient <IAddressAttributeParser, AddressAttributeParser>();
            services.AddTransient <IAddressAttributeService, AddressAttributeService>();
            services.AddTransient <IAddressService, AddressService>();
            services.AddTransient <IAffiliateService, AffiliateService>();
            services.AddTransient <IVendorService, VendorService>();
            services.AddTransient <IVendorAttributeFormatter, VendorAttributeFormatter>();
            services.AddTransient <IVendorAttributeParser, VendorAttributeParser>();
            services.AddTransient <IVendorAttributeService, VendorAttributeService>();
            services.AddTransient <ISearchTermService, SearchTermService>();
            services.AddTransient <IGenericAttributeService, GenericAttributeService>();
            services.AddTransient <IMaintenanceService, MaintenanceService>();
            services.AddTransient <ICustomerAttributeFormatter, CustomerAttributeFormatter>();
            services.AddTransient <ICustomerAttributeParser, CustomerAttributeParser>();
            services.AddTransient <ICustomerAttributeService, CustomerAttributeService>();
            services.AddTransient <ICustomerService, CustomerService>();
            services.AddTransient <ICustomerRegistrationService, CustomerRegistrationService>();
            services.AddTransient <ICustomerReportService, CustomerReportService>();
            services.AddTransient <IPermissionService, PermissionService>();
            services.AddTransient <IAclService, AclService>();
            services.AddTransient <IPriceCalculationService, PriceCalculationService>();
            services.AddTransient <IGeoLookupService, GeoLookupService>();
            services.AddTransient <ICountryService, CountryService>();
            services.AddTransient <ICurrencyService, CurrencyService>();
            services.AddTransient <IMeasureService, MeasureService>();
            services.AddTransient <IStateProvinceService, StateProvinceService>();
            services.AddTransient <IStoreService, StoreService>();
            services.AddTransient <IStoreMappingService, StoreMappingService>();
            services.AddTransient <IDiscountService, DiscountService>();
            services.AddTransient <ILocalizationService, LocalizationService>();
            services.AddTransient <ILocalizedEntityService, LocalizedEntityService>();
            services.AddTransient <IInstallationLocalizationService, InstallationLocalizationService>();
            services.AddTransient <ILanguageService, LanguageService>();
            services.AddTransient <IDownloadService, DownloadService>();
            services.AddTransient <IMessageTemplateService, MessageTemplateService>();
            services.AddTransient <IQueuedEmailService, QueuedEmailService>();
            services.AddTransient <INewsLetterSubscriptionService, NewsLetterSubscriptionService>();
            services.AddTransient <INotificationService, NotificationService>();
            services.AddTransient <ICampaignService, CampaignService>();
            services.AddTransient <IEmailAccountService, EmailAccountService>();
            services.AddTransient <IWorkflowMessageService, WorkflowMessageService>();
            services.AddTransient <IMessageTokenProvider, MessageTokenProvider>();
            services.AddTransient <ITokenizer, Tokenizer>();
            services.AddTransient <ISmtpBuilder, SmtpBuilder>();
            services.AddTransient <IEmailSender, EmailSender>();
            services.AddTransient <ICheckoutAttributeFormatter, CheckoutAttributeFormatter>();
            services.AddTransient <ICheckoutAttributeParser, CheckoutAttributeParser>();
            services.AddTransient <ICheckoutAttributeService, CheckoutAttributeService>();
            services.AddTransient <IGiftCardService, GiftCardService>();
            services.AddTransient <IOrderService, OrderService>();
            services.AddTransient <IOrderReportService, OrderReportService>();
            services.AddTransient <IOrderProcessingService, OrderProcessingService>();
            services.AddTransient <IOrderTotalCalculationService, OrderTotalCalculationService>();
            services.AddTransient <IReturnRequestService, ReturnRequestService>();
            services.AddTransient <IRewardPointService, RewardPointService>();
            services.AddTransient <IShoppingCartService, ShoppingCartService>();
            services.AddTransient <ICustomNumberFormatter, CustomNumberFormatter>();
            services.AddTransient <IPaymentService, PaymentService>();
            services.AddTransient <IEncryptionService, EncryptionService>();
            services.AddTransient <IAuthenticationService, TestAuthenticationService>();
            services.AddTransient <IUrlRecordService, UrlRecordService>();
            services.AddTransient <IShipmentService, ShipmentService>();
            services.AddTransient <IShippingService, ShippingService>();
            services.AddTransient <IDateRangeService, DateRangeService>();
            services.AddTransient <ITaxCategoryService, TaxCategoryService>();
            services.AddTransient <ITaxService, TaxService>();
            services.AddTransient <ILogger, DefaultLogger>();
            services.AddTransient <ICustomerActivityService, CustomerActivityService>();
            services.AddTransient <IForumService, ForumService>();
            services.AddTransient <IGdprService, GdprService>();
            services.AddTransient <IPollService, PollService>();
            services.AddTransient <IBlogService, BlogService>();
            services.AddTransient <ITopicService, TopicService>();
            services.AddTransient <INewsService, NewsService>();
            services.AddTransient <IDateTimeHelper, DateTimeHelper>();
            services.AddTransient <ISitemapGenerator, SitemapGenerator>();
            services.AddTransient <IScheduleTaskService, ScheduleTaskService>();
            services.AddTransient <IExportManager, ExportManager>();
            services.AddTransient <IImportManager, ImportManager>();
            services.AddTransient <IPdfService, PdfService>();
            services.AddTransient <IUploadService, UploadService>();
            services.AddTransient <IThemeProvider, ThemeProvider>();
            services.AddTransient <IExternalAuthenticationService, ExternalAuthenticationService>();

            //slug route transformer
            services.AddSingleton <IReviewTypeService, ReviewTypeService>();
            services.AddSingleton <IEventPublisher, EventPublisher>();
            services.AddTransient <ISettingService, SettingService>();

            //plugin managers
            services.AddTransient(typeof(IPluginManager <>), typeof(PluginManager <>));
            services.AddTransient <IAuthenticationPluginManager, AuthenticationPluginManager>();
            services.AddTransient <IMultiFactorAuthenticationPluginManager, MultiFactorAuthenticationPluginManager>();
            services.AddTransient <IWidgetPluginManager, WidgetPluginManager>();
            services.AddTransient <IExchangeRatePluginManager, ExchangeRatePluginManager>();
            services.AddTransient <IDiscountPluginManager, DiscountPluginManager>();
            services.AddTransient <IPaymentPluginManager, PaymentPluginManager>();
            services.AddTransient <IPickupPluginManager, PickupPluginManager>();
            services.AddTransient <IShippingPluginManager, ShippingPluginManager>();
            services.AddTransient <ITaxPluginManager, TaxPluginManager>();

            services.AddTransient <IPictureService, TestPictureService>();

            //register all settings
            var settings = typeFinder.FindClassesOfType(typeof(ISettings), false).ToList();

            foreach (var setting in settings)
            {
                services.AddTransient(setting,
                                      context => context.GetRequiredService <ISettingService>().LoadSettingAsync(setting).Result);
            }

            //event consumers
            var consumers = typeFinder.FindClassesOfType(typeof(IConsumer <>)).ToList();

            foreach (var consumer in consumers)
            {
                foreach (var findInterface in consumer.FindInterfaces((type, criteria) =>
                {
                    var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());
                    return(isMatch);
                }, typeof(IConsumer <>)))
                {
                    services.AddTransient(findInterface, consumer);
                }
            }

            services.AddSingleton <IInstallationService, InstallationService>();

            services
            // add common FluentMigrator services
            .AddFluentMigratorCore()
            .AddScoped <IProcessorAccessor, TestProcessorAccessor>()
            // set accessor for the connection string
            .AddScoped <IConnectionStringAccessor>(x => DataSettingsManager.LoadSettings())
            .AddScoped <IMigrationManager, MigrationManager>()
            .AddSingleton <IConventionSet, NopTestConventionSet>()
            .ConfigureRunner(rb =>
                             rb.WithVersionTable(new MigrationVersionInfo()).AddSQLite()
                             // define the assembly containing the migrations
                             .ScanIn(mAssemblies).For.Migrations());

            services.AddTransient <IStoreContext, WebStoreContext>();
            services.AddTransient <IWorkContext, WebWorkContext>();
            services.AddTransient <IThemeContext, ThemeContext>();

            services.AddTransient <IPageHeadBuilder, PageHeadBuilder>();

            //common factories
            services.AddTransient <IAclSupportedModelFactory, AclSupportedModelFactory>();
            services.AddTransient <IDiscountSupportedModelFactory, DiscountSupportedModelFactory>();
            services.AddTransient <ILocalizedModelFactory, LocalizedModelFactory>();
            services.AddTransient <IStoreMappingSupportedModelFactory, StoreMappingSupportedModelFactory>();

            //admin factories
            services.AddTransient <IBaseAdminModelFactory, BaseAdminModelFactory>();
            services.AddTransient <IActivityLogModelFactory, ActivityLogModelFactory>();
            services.AddTransient <IAddressAttributeModelFactory, AddressAttributeModelFactory>();
            services.AddTransient <IAffiliateModelFactory, AffiliateModelFactory>();
            services.AddTransient <IBlogModelFactory, BlogModelFactory>();
            services.AddTransient <ICampaignModelFactory, CampaignModelFactory>();
            services.AddTransient <ICategoryModelFactory, CategoryModelFactory>();
            services.AddTransient <ICheckoutAttributeModelFactory, CheckoutAttributeModelFactory>();
            services.AddTransient <ICommonModelFactory, CommonModelFactory>();
            services.AddTransient <ICountryModelFactory, CountryModelFactory>();
            services.AddTransient <ICurrencyModelFactory, CurrencyModelFactory>();
            services.AddTransient <ICustomerAttributeModelFactory, CustomerAttributeModelFactory>();
            services.AddTransient <ICustomerModelFactory, CustomerModelFactory>();
            services.AddTransient <ICustomerRoleModelFactory, CustomerRoleModelFactory>();
            services.AddTransient <IDiscountModelFactory, DiscountModelFactory>();
            services.AddTransient <IEmailAccountModelFactory, EmailAccountModelFactory>();
            services
            .AddTransient <IExternalAuthenticationMethodModelFactory, ExternalAuthenticationMethodModelFactory>();
            services.AddTransient <IForumModelFactory, ForumModelFactory>();
            services.AddTransient <IGiftCardModelFactory, GiftCardModelFactory>();
            services.AddTransient <IHomeModelFactory, HomeModelFactory>();
            services.AddTransient <ILanguageModelFactory, LanguageModelFactory>();
            services.AddTransient <ILogModelFactory, LogModelFactory>();
            services.AddTransient <IManufacturerModelFactory, ManufacturerModelFactory>();
            services.AddTransient <IMeasureModelFactory, MeasureModelFactory>();
            services.AddTransient <IMessageTemplateModelFactory, MessageTemplateModelFactory>();
            services.AddTransient <INewsletterSubscriptionModelFactory, NewsletterSubscriptionModelFactory>();
            services.AddTransient <INewsModelFactory, NewsModelFactory>();
            services.AddTransient <IOrderModelFactory, OrderModelFactory>();
            services.AddTransient <IPaymentModelFactory, PaymentModelFactory>();
            services.AddTransient <IPluginModelFactory, PluginModelFactory>();
            services.AddTransient <IPollModelFactory, PollModelFactory>();
            services.AddTransient <IProductModelFactory, ProductModelFactory>();
            services.AddTransient <IProductAttributeModelFactory, ProductAttributeModelFactory>();
            services.AddTransient <IProductReviewModelFactory, ProductReviewModelFactory>();
            services.AddTransient <IReportModelFactory, ReportModelFactory>();
            services.AddTransient <IQueuedEmailModelFactory, QueuedEmailModelFactory>();
            services.AddTransient <IRecurringPaymentModelFactory, RecurringPaymentModelFactory>();
            services.AddTransient <IReturnRequestModelFactory, ReturnRequestModelFactory>();
            services.AddTransient <IReviewTypeModelFactory, ReviewTypeModelFactory>();
            services.AddTransient <IScheduleTaskModelFactory, ScheduleTaskModelFactory>();
            services.AddTransient <ISecurityModelFactory, SecurityModelFactory>();
            services.AddTransient <ISettingModelFactory, SettingModelFactory>();
            services.AddTransient <IShippingModelFactory, ShippingModelFactory>();
            services.AddTransient <IShoppingCartModelFactory, ShoppingCartModelFactory>();
            services.AddTransient <ISpecificationAttributeModelFactory, SpecificationAttributeModelFactory>();
            services.AddTransient <IStoreModelFactory, StoreModelFactory>();
            services.AddTransient <ITaxModelFactory, TaxModelFactory>();
            services.AddTransient <ITemplateModelFactory, TemplateModelFactory>();
            services.AddTransient <ITopicModelFactory, TopicModelFactory>();
            services.AddTransient <IVendorAttributeModelFactory, VendorAttributeModelFactory>();
            services.AddTransient <IVendorModelFactory, VendorModelFactory>();
            services.AddTransient <IWidgetModelFactory, WidgetModelFactory>();

            //factories
            services.AddTransient <Web.Factories.IAddressModelFactory, Web.Factories.AddressModelFactory>();
            services.AddTransient <Web.Factories.IBlogModelFactory, Web.Factories.BlogModelFactory>();
            services.AddTransient <Web.Factories.ICatalogModelFactory, Web.Factories.CatalogModelFactory>();
            services.AddTransient <Web.Factories.ICheckoutModelFactory, Web.Factories.CheckoutModelFactory>();
            services.AddTransient <Web.Factories.ICommonModelFactory, Web.Factories.CommonModelFactory>();
            services.AddTransient <Web.Factories.ICountryModelFactory, Web.Factories.CountryModelFactory>();
            services.AddTransient <Web.Factories.ICustomerModelFactory, Web.Factories.CustomerModelFactory>();
            services.AddTransient <Web.Factories.IForumModelFactory, Web.Factories.ForumModelFactory>();
            services
            .AddTransient <Web.Factories.IExternalAuthenticationModelFactory,
                           Web.Factories.ExternalAuthenticationModelFactory>();
            services.AddTransient <Web.Factories.INewsModelFactory, Web.Factories.NewsModelFactory>();
            services.AddTransient <Web.Factories.INewsletterModelFactory, Web.Factories.NewsletterModelFactory>();
            services.AddTransient <Web.Factories.IOrderModelFactory, Web.Factories.OrderModelFactory>();
            services.AddTransient <Web.Factories.IPollModelFactory, Web.Factories.PollModelFactory>();
            services
            .AddTransient <Web.Factories.IPrivateMessagesModelFactory, Web.Factories.PrivateMessagesModelFactory>();
            services.AddTransient <Web.Factories.IProductModelFactory, Web.Factories.ProductModelFactory>();
            services.AddTransient <Web.Factories.IProfileModelFactory, Web.Factories.ProfileModelFactory>();
            services.AddTransient <Web.Factories.IReturnRequestModelFactory, Web.Factories.ReturnRequestModelFactory>();
            services.AddTransient <Web.Factories.IShoppingCartModelFactory, Web.Factories.ShoppingCartModelFactory>();
            services.AddTransient <Web.Factories.ITopicModelFactory, Web.Factories.TopicModelFactory>();
            services.AddTransient <Web.Factories.IVendorModelFactory, Web.Factories.VendorModelFactory>();
            services.AddTransient <Web.Factories.IWidgetModelFactory, Web.Factories.WidgetModelFactory>();

            _serviceProvider = services.BuildServiceProvider();

            EngineContext.Replace(new NopTestEngine(_serviceProvider));

            _serviceProvider.GetService <INopDataProvider>().CreateDatabase(null);
            _serviceProvider.GetService <INopDataProvider>().InitializeDatabase();

            var languagePackInfo = (DownloadUrl : string.Empty, Progress : 0);

            _serviceProvider.GetService <IInstallationService>()
            .InstallRequiredDataAsync(NopTestsDefaults.AdminEmail, NopTestsDefaults.AdminPassword, languagePackInfo, null, null).Wait();
            _serviceProvider.GetService <IInstallationService>().InstallSampleDataAsync(NopTestsDefaults.AdminEmail).Wait();

            var provider = (IPermissionProvider)Activator.CreateInstance(typeof(StandardPermissionProvider));

            EngineContext.Current.Resolve <IPermissionService>().InstallPermissionsAsync(provider).Wait();
        }