Ejemplo n.º 1
0
        public void PostInitialize(IApplicationBuilder appBuilder)
        {
            var permissionsProvider = appBuilder.ApplicationServices.GetRequiredService <IPermissionsRegistrar>();

            permissionsProvider.RegisterPermissions(ModuleConstants.Security.Permissions.AllPermissions.Select(x => new Permission()
            {
                GroupName = "BulkActions", Name = x
            }).ToArray());

            PolymorphJsonConverter.RegisterTypeForDiscriminator(typeof(BulkActionContext), nameof(BulkActionContext.ContextTypeName));
        }
Ejemplo n.º 2
0
        public void DeserializeObject_DeserializeWithDiscriminator()
        {
            //Arrange
            AbstractTypeFactory <PermissionScope> .RegisterType <PermissionScope>();

            AbstractTypeFactory <PermissionScope> .RegisterType <PermissionScopeExt1>();

            AbstractTypeFactory <PermissionScope> .RegisterType <PermissionScopeExt2>();

            var json0 = "{'scope':'Scope000'}".Replace("'", "\"");
            var json1 = "{'Type':'PermissionScopeExt1','scope':'Scope111'}".Replace("'", "\"");
            var json2 = "{'Type':'PermissionScopeExt2','scope':'Scope123'}".Replace("'", "\"");

            var converter = new PolymorphJsonConverter();

            PolymorphJsonConverter.RegisterTypeForDiscriminator(typeof(PermissionScope), nameof(PermissionScope.Type));

            //Act
            var scope0 = JsonConvert.DeserializeObject <PermissionScope>(json0, converter);

            //Assert
            scope0.Should().NotBeNull();
            scope0.Should().BeOfType <PermissionScope>();
            scope0.Should().NotBeOfType <PermissionScopeExt1>();
            scope0.Should().NotBeOfType <PermissionScopeExt2>();

            //Act
            var scope1 = JsonConvert.DeserializeObject <PermissionScope>(json1, converter);

            //Assert
            scope1.Should().NotBeNull();
            scope1.Should().BeOfType <PermissionScopeExt1>();
            scope1.Should().NotBeOfType <PermissionScope>();
            scope1.Should().NotBeOfType <PermissionScopeExt2>();

            //Act
            var scope2 = JsonConvert.DeserializeObject <PermissionScope>(json2, converter);

            //Assert
            scope2.Should().NotBeNull();
            scope2.Should().BeOfType <PermissionScopeExt2>();
            scope2.Should().NotBeOfType <PermissionScope>();
            scope2.Should().NotBeOfType <PermissionScopeExt1>();
        }
        public PolicyBenchmark()
        {
            // Register discriminators for promotion rewards to allow custom jsonconverters work correctly
            PolymorphJsonConverter.RegisterTypeForDiscriminator(typeof(PromotionReward), nameof(PromotionReward.Id));

            // Register the resulting trees expressions into the AbstractFactory<IConditionTree> to allow custom jsonconverters work correctly
            foreach (var conditionTree in AbstractTypeFactory <PromotionConditionAndRewardTreePrototype> .TryCreateInstance().Traverse <IConditionTree>(x => x.AvailableChildren))
            {
                AbstractTypeFactory <IConditionTree> .RegisterType(conditionTree.GetType());
            }
            foreach (var conditionTree in AbstractTypeFactory <DynamicContentConditionTreePrototype> .TryCreateInstance().Traverse <IConditionTree>(x => x.AvailableChildren))
            {
                AbstractTypeFactory <IConditionTree> .RegisterType(conditionTree.GetType());
            }

            // Create disabled memory cache to test full calculations every policy call
            var memoryCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));

            disabledPlatformMemoryCache = new PlatformMemoryCache(memoryCache, Options.Create(new CachingOptions()
            {
                CacheEnabled = false
            }), new Mock <ILogger <PlatformMemoryCache> >().Object);


            // Mock evaluation context from pctx_mock.json file
            pCtx = MockPromotionEvaluationContext();

            // Mock promotions from promotions_mock.json file
            // If you want to have jsons like this from live system to benchmark different promotions combination, just call
            // in marketing module debug:
            // JsonConvert.SerializeObject(dynamicPromotion.DynamicExpression, new ConditionJsonConverter(doNotSerializeAvailCondition: true))
            // in immediate or watch
            promoSearchServiceMock = new Moq.Mock <IPromotionSearchService>();
            promoSearchServiceMock.Setup(x => x.SearchPromotionsAsync(It.IsAny <PromotionSearchCriteria>())).ReturnsAsync(MockPromotionSearchResult());


            _bestRewardPolicy = GetBestRewardPromotionPolicy();
            _stackablePolicy  = GetCombineStackablePromotionPolicy();
        }
Ejemplo n.º 4
0
        public void PostInitialize(IApplicationBuilder appBuilder)
        {
            var settingsRegistrar = appBuilder.ApplicationServices.GetRequiredService <ISettingsRegistrar>();

            settingsRegistrar.RegisterSettings(ModuleConstants.Settings.AllSettings, ModuleInfo.Id);

            //Register module permissions
            var permissionsProvider = appBuilder.ApplicationServices.GetRequiredService <IPermissionsRegistrar>();

            permissionsProvider.RegisterPermissions(ModuleConstants.Security.Permissions.AllPermissions.Select(x => new Permission()
            {
                GroupName = "Generic Export", Name = x
            }).ToArray());

            PolymorphJsonConverter.RegisterTypeForDiscriminator(typeof(ExportDataQuery), nameof(ExportDataQuery.ExportTypeName));

            AbstractTypeFactory <IExportProviderConfiguration> .RegisterType <JsonProviderConfiguration>();

            AbstractTypeFactory <IExportProviderConfiguration> .RegisterType <CsvProviderConfiguration>();

            PolymorphJsonConverter.RegisterTypeForDiscriminator(typeof(IExportProviderConfiguration), nameof(IExportProviderConfiguration.Type));
        }
Ejemplo n.º 5
0
        public void PostInitialize(IApplicationBuilder appBuilder)
        {
            _appBuilder = appBuilder;

            var settingsRegistrar = appBuilder.ApplicationServices.GetRequiredService <ISettingsRegistrar>();

            settingsRegistrar.RegisterSettings(ModuleConstants.Settings.AllSettings, ModuleInfo.Id);

            var paymentMethodsRegistrar = appBuilder.ApplicationServices.GetRequiredService <IPaymentMethodsRegistrar>();

            paymentMethodsRegistrar.RegisterPaymentMethod <DefaultManualPaymentMethod>();
            settingsRegistrar.RegisterSettingsForType(ModuleConstants.Settings.DefaultManualPaymentMethod.AllSettings, typeof(DefaultManualPaymentMethod).Name);

            PolymorphJsonConverter.RegisterTypeForDiscriminator(typeof(PaymentMethod), nameof(PaymentMethod.TypeName));

            using (var serviceScope = appBuilder.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <PaymentDbContext>();
                dbContext.Database.MigrateIfNotApplied(MigrationName.GetUpdateV2MigrationName(ModuleInfo.Id));
                dbContext.Database.EnsureCreated();
                dbContext.Database.Migrate();
            }
        }
Ejemplo n.º 6
0
        public void PostInitialize(IApplicationBuilder applicationBuilder)
        {
            _appBuilder = applicationBuilder;

            var settingsRegistrar = applicationBuilder.ApplicationServices.GetRequiredService <ISettingsRegistrar>();

            settingsRegistrar.RegisterSettings(Core.ModuleConstants.Settings.AllSettings, ModuleInfo.Id);

            PolymorphJsonConverter.RegisterTypeForDiscriminator(typeof(TaxProvider), nameof(TaxProvider.TypeName));

            var taxProviderRegistrar = applicationBuilder.ApplicationServices.GetRequiredService <ITaxProviderRegistrar>();

            taxProviderRegistrar.RegisterTaxProvider <FixedRateTaxProvider>();
            settingsRegistrar.RegisterSettingsForType(Core.ModuleConstants.Settings.FixedTaxProviderSettings.AllSettings, typeof(FixedRateTaxProvider).Name);

            using (var serviceScope = applicationBuilder.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <TaxDbContext>();
                dbContext.Database.MigrateIfNotApplied(MigrationName.GetUpdateV2MigrationName(ModuleInfo.Id));
                dbContext.Database.EnsureCreated();
                dbContext.Database.Migrate();
            }
        }
Ejemplo n.º 7
0
        public void PostInitialize(IApplicationBuilder appBuilder)
        {
            _appBuilder = appBuilder;

            AbstractTypeFactory <NotificationTemplate> .RegisterType <EmailNotificationTemplate>();

            AbstractTypeFactory <NotificationTemplate> .RegisterType <SmsNotificationTemplate>();

            AbstractTypeFactory <NotificationMessage> .RegisterType <EmailNotificationMessage>();

            AbstractTypeFactory <NotificationMessage> .RegisterType <SmsNotificationMessage>();

            AbstractTypeFactory <NotificationEntity> .RegisterType <EmailNotificationEntity>();

            AbstractTypeFactory <NotificationEntity> .RegisterType <SmsNotificationEntity>();

            AbstractTypeFactory <NotificationTemplateEntity> .RegisterType <EmailNotificationTemplateEntity>();

            AbstractTypeFactory <NotificationTemplateEntity> .RegisterType <SmsNotificationTemplateEntity>();

            AbstractTypeFactory <NotificationMessageEntity> .RegisterType <EmailNotificationMessageEntity>();

            AbstractTypeFactory <NotificationMessageEntity> .RegisterType <SmsNotificationMessageEntity>();

            AbstractTypeFactory <NotificationScriptObject> .RegisterType <NotificationScriptObject>()
            .WithFactory(() => appBuilder.ApplicationServices.GetRequiredService <NotificationScriptObject>());

            var settingsRegistrar = appBuilder.ApplicationServices.GetRequiredService <ISettingsRegistrar>();

            settingsRegistrar.RegisterSettings(ModuleConstants.Settings.AllSettings, ModuleInfo.Id);

            var permissionsRegistrar = appBuilder.ApplicationServices.GetRequiredService <IPermissionsRegistrar>();

            permissionsRegistrar.RegisterPermissions(ModuleConstants.Security.Permissions.AllPermissions.Select(x =>
                                                                                                                new Permission()
            {
                GroupName = "Notifications",
                ModuleId  = ModuleInfo.Id,
                Name      = x
            }).ToArray());

            PolymorphJsonConverter.RegisterTypeForDiscriminator(typeof(Notification), nameof(Notification.Type));
            PolymorphJsonConverter.RegisterTypeForDiscriminator(typeof(NotificationTemplate), nameof(NotificationTemplate.Type));
            PolymorphJsonConverter.RegisterTypeForDiscriminator(typeof(NotificationMessage), nameof(NotificationMessage.Type));

            using (var serviceScope = appBuilder.ApplicationServices.CreateScope())
            {
                using var notificationDbContext = serviceScope.ServiceProvider.GetRequiredService <NotificationDbContext>();
                notificationDbContext.Database.EnsureCreated();
                notificationDbContext.Database.Migrate();
            }

            var registrar = appBuilder.ApplicationServices.GetService <INotificationRegistrar>();

            registrar.RegisterNotification <ResetPasswordEmailNotification>();
            registrar.RegisterNotification <ConfirmationEmailNotification>();
            registrar.RegisterNotification <RegistrationEmailNotification>();
            registrar.RegisterNotification <RegistrationInvitationEmailNotification>();
            registrar.RegisterNotification <RemindUserNameEmailNotification>();
            registrar.RegisterNotification <ResetPasswordSmsNotification>();
            registrar.RegisterNotification <TwoFactorEmailNotification>();
            registrar.RegisterNotification <TwoFactorSmsNotification>();
            registrar.RegisterNotification <ChangePhoneNumberSmsNotification>();

            //Save all registered notifications in the database after application start
            var hostLifeTime = appBuilder.ApplicationServices.GetService <IHostApplicationLifetime>();

            hostLifeTime.ApplicationStarted.Register(() =>
            {
                var notificationService        = appBuilder.ApplicationServices.GetService <INotificationService>();
                var allRegisteredNotifications = registrar.AllRegisteredNotifications.Select(x =>
                {
                    //Do not save predefined templates in the database to prevent rewrite of exists data
                    x.ReduceDetails(NotificationResponseGroup.Default.ToString());
                    return(x);
                }).ToArray();
                notificationService.SaveChangesAsync(allRegisteredNotifications).GetAwaiter().GetResult();
            });
        }
Ejemplo n.º 8
0
        public void PostInitialize(IApplicationBuilder appBuilder)
        {
            _appBuilder = appBuilder;

            var settingsRegistrar = appBuilder.ApplicationServices.GetRequiredService <ISettingsRegistrar>();

            settingsRegistrar.RegisterSettings(ModuleConstants.Settings.General.AllSettings, ModuleInfo.Id);

            var permissionsRegistrar = appBuilder.ApplicationServices.GetRequiredService <IPermissionsRegistrar>();

            permissionsRegistrar.RegisterPermissions(ModuleConstants.Security.Permissions.AllPermissions.Select(x =>
                                                                                                                new Permission()
            {
                GroupName = "Marketing",
                ModuleId  = ModuleInfo.Id,
                Name      = x
            }).ToArray());

            //Register Permission scopes
            AbstractTypeFactory <PermissionScope> .RegisterType <MarketingStoreSelectedScope>();

            permissionsRegistrar.WithAvailabeScopesForPermissions(new[] { ModuleConstants.Security.Permissions.Read }, new MarketingStoreSelectedScope());


            var eventHandlerRegistrar = appBuilder.ApplicationServices.GetService <IHandlerRegistrar>();

            //Create order observer. record order coupon usage
            eventHandlerRegistrar.RegisterHandler <OrderChangedEvent>(async(message, token) => await appBuilder.ApplicationServices.GetService <CouponUsageRecordHandler>().Handle(message));

            eventHandlerRegistrar.RegisterHandler <PromotionChangedEvent>(async(message, token) => await appBuilder.ApplicationServices.GetService <LogChangesChangedEventHandler>().Handle(message));
            eventHandlerRegistrar.RegisterHandler <CouponChangedEvent>(async(message, token) => await appBuilder.ApplicationServices.GetService <LogChangesChangedEventHandler>().Handle(message));

            using (var serviceScope = appBuilder.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <MarketingDbContext>();
                dbContext.Database.MigrateIfNotApplied(MigrationName.GetUpdateV2MigrationName(ModuleInfo.Id));
                dbContext.Database.EnsureCreated();
                dbContext.Database.Migrate();
            }

            var dynamicPropertyRegistrar = appBuilder.ApplicationServices.GetRequiredService <IDynamicPropertyRegistrar>();

            dynamicPropertyRegistrar.RegisterType <DynamicContentItem>();

            var dynamicContentService = appBuilder.ApplicationServices.GetService <IDynamicContentService>();

            foreach (var id in new[] { ModuleConstants.MarketingConstants.ContentPlacesRootFolderId, ModuleConstants.MarketingConstants.CotentItemRootFolderId })
            {
                var folders    = dynamicContentService.GetFoldersByIdsAsync(new[] { id }).GetAwaiter().GetResult();
                var rootFolder = folders.FirstOrDefault();
                if (rootFolder == null)
                {
                    rootFolder = new DynamicContentFolder
                    {
                        Id   = id,
                        Name = id
                    };
                    dynamicContentService.SaveFoldersAsync(new[] { rootFolder }).GetAwaiter().GetResult();
                }
            }

            //Create standard dynamic properties for dynamic content item
            var dynamicPropertyService  = appBuilder.ApplicationServices.GetService <IDynamicPropertyService>();
            var contentItemTypeProperty = new DynamicProperty
            {
                Id           = "Marketing_DynamicContentItem_Type_Property",
                IsDictionary = true,
                Name         = "Content type",
                ObjectType   = typeof(DynamicContentItem).FullName,
                ValueType    = DynamicPropertyValueType.ShortText,
                CreatedBy    = "Auto",
            };

            dynamicPropertyService.SaveDynamicPropertiesAsync(new[] { contentItemTypeProperty }).GetAwaiter().GetResult();

            PolymorphJsonConverter.RegisterTypeForDiscriminator(typeof(PromotionReward), nameof(PromotionReward.Id));

            //Register the resulting trees expressions into the AbstractFactory<IConditionTree>
            foreach (var conditionTree in AbstractTypeFactory <PromotionConditionAndRewardTreePrototype> .TryCreateInstance().Traverse <IConditionTree>(x => x.AvailableChildren))
            {
                AbstractTypeFactory <IConditionTree> .RegisterType(conditionTree.GetType());
            }
            foreach (var conditionTree in AbstractTypeFactory <DynamicContentConditionTreePrototype> .TryCreateInstance().Traverse <IConditionTree>(x => x.AvailableChildren))
            {
                AbstractTypeFactory <IConditionTree> .RegisterType(conditionTree.GetType());
            }
        }
Ejemplo n.º 9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
                app.UseDatabaseErrorPage();
#if DEBUG
                TelemetryDebugWriter.IsTracingDisabled = true;
#endif
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            //Return all errors as Json response
            app.UseMiddleware <ApiErrorWrappingMiddleware>();

            // Engages the forwarded header support in the pipeline  (see description above)
            app.UseForwardedHeaders();

            app.UseHttpsRedirection();

            // Add default MimeTypes with additional bindings
            var fileExtensionsBindings = new Dictionary <string, string>()
            {
                { ".liquid", "text/html" },
                { ".md", "text/html" }
            };

            // Create default provider (with default Mime types)
            var fileExtensionContentTypeProvider = new FileExtensionContentTypeProvider();

            // Add custom bindings
            foreach (var binding in fileExtensionsBindings)
            {
                fileExtensionContentTypeProvider.Mappings[binding.Key] = binding.Value;
            }

            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = fileExtensionContentTypeProvider
            });

            app.UseRouting();
            app.UseCookiePolicy();

            //Handle all requests like a $(Platform) and Modules/$({ module.ModuleName }) as static files in correspond folder
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(WebHostEnvironment.MapPath("~/js")),
                RequestPath  = new PathString($"/$(Platform)/Scripts")
            });

            var localModules = app.ApplicationServices.GetRequiredService <ILocalModuleCatalog>().Modules;
            foreach (var module in localModules.OfType <ManifestModuleInfo>())
            {
                app.UseStaticFiles(new StaticFileOptions()
                {
                    FileProvider = new PhysicalFileProvider(module.FullPhysicalPath),
                    RequestPath  = new PathString($"/modules/$({ module.ModuleName })")
                });
            }

            app.UseDefaultFiles();

            app.UseAuthentication();
            app.UseAuthorization();

            app.WithDistributedLock(() =>
            {
                // This method contents will run inside of critical section of instance distributed lock.
                // Main goal is to apply the migrations (Platform, Hangfire, modules) sequentially instance by instance.
                // This ensures only one active EF-migration ran simultaneously to avoid DB-related side-effects.

                // Apply platform migrations
                app.UsePlatformMigrations();

                app.UseDbTriggers();

                // Register platform settings
                app.UsePlatformSettings();

                // Complete hangfire init and apply Hangfire migrations
                app.UseHangfire(Configuration);

                // Register platform permissions
                app.UsePlatformPermissions();
                app.UseSecurityHandlers();
                app.UsePruneExpiredTokensJob();

                // Complete modules startup and apply their migrations
                app.UseModules();
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");

                //Setup SignalR hub
                endpoints.MapHub <PushNotificationHub>("/pushNotificationHub");
            });

            //Seed default users
            app.UseDefaultUsersAsync().GetAwaiter().GetResult();

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Use app insights telemetry
            app.UseAppInsightsTelemetry();


            var mvcJsonOptions = app.ApplicationServices.GetService <IOptions <MvcNewtonsoftJsonOptions> >();
            mvcJsonOptions.Value.SerializerSettings.Converters.Add(new PolymorphJsonConverter());
            PolymorphJsonConverter.RegisterTypeForDiscriminator(typeof(PermissionScope), nameof(PermissionScope.Type));
        }