public async Task ShouldProcess(string cdnBaseUrl, string text, string expected)
        {
            var sanitizerOptions = new HtmlSanitizerOptions();

            sanitizerOptions.Configure.Add(opt => opt.AllowedAttributes.Add("class"));

            var fileStore = new DefaultMediaFileStore(
                Mock.Of <IFileStore>(),
                "/media",
                cdnBaseUrl,
                Enumerable.Empty <IMediaEventHandler>(),
                Enumerable.Empty <IMediaCreatingEventHandler>(),
                Mock.Of <ILogger <DefaultMediaFileStore> >());

            var sanitizer = new HtmlSanitizerService(Options.Create(sanitizerOptions));

            var defaultHttpContext = new DefaultHttpContext();

            defaultHttpContext.Request.PathBase = new PathString("/tenant");
            var httpContextAccessor = Mock.Of <IHttpContextAccessor>(hca => hca.HttpContext == defaultHttpContext);

            var options = Options.Create(new ResourceManagementOptions {
                CdnBaseUrl = cdnBaseUrl
            });

            var imageProvider = new ImageShortcodeProvider(fileStore, sanitizer, httpContextAccessor, options);

            var processor = new ShortcodeService(new IShortcodeProvider[] { imageProvider }, Enumerable.Empty <IShortcodeContextProvider>());

            var processed = await processor.ProcessAsync(text);

            Assert.Equal(expected, processed);
        }
        public async Task ShouldProcess(string cdnBaseUrl, string text, string expected)
        {
            var fileStore = new DefaultMediaFileStore(
                Mock.Of <IFileStore>(),
                "/media",
                cdnBaseUrl,
                Enumerable.Empty <IMediaEventHandler>(),
                Enumerable.Empty <IMediaCreatingEventHandler>(),
                Mock.Of <ILogger <DefaultMediaFileStore> >());

            var sanitizer = new HtmlSanitizerService(Options.Create(new HtmlSanitizerOptions()));

            var defaultHttpContext = new DefaultHttpContext();

            defaultHttpContext.Request.PathBase = new PathString("/tenant");
            var httpContextAccessor = Mock.Of <IHttpContextAccessor>(hca => hca.HttpContext == defaultHttpContext);

            var options = Options.Create(new ResourceManagementOptions {
                CdnBaseUrl = cdnBaseUrl
            });

            var assetUrlProvider = new AssetUrlShortcodeProvider(fileStore, httpContextAccessor, options);

            var processor = new ShortcodeService(new IShortcodeProvider[] { assetUrlProvider }, Enumerable.Empty <IShortcodeContextProvider>());

            var processed = await processor.ProcessAsync(text);

            // The markdown part sanitizes after processing.
            var sanitized = sanitizer.Sanitize(processed);

            Assert.Equal(expected, sanitized);
        }
        /// <summary>
        /// Adds the <see cref="ShortcodeService"/> as a singleton.
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddShortcodes(this IServiceCollection services)
        {
            var shortcodeService = new ShortcodeService();

            shortcodeService.Add <SourceCodeShortcode>(tag: "code");
            shortcodeService.Add <YouTubeShortcode>(tag: "youtube");
            services.AddSingleton <IShortcodeService>(shortcodeService);

            return(services);
        }
Beispiel #4
0
        public async Task ShouldProcess(string currentCulture, string text, string expected)
        {
            CultureInfo.CurrentUICulture = new CultureInfo(currentCulture);

            var localeProvider = new LocaleShortcodeProvider();
            var processor      = new ShortcodeService(new IShortcodeProvider[] { localeProvider }, Enumerable.Empty <IShortcodeContextProvider>());
            var processed      = await processor.ProcessAsync(text);

            Assert.Equal(expected, processed);
        }
Beispiel #5
0
        public override void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <INotificationHandler <ModelPreRender <BlogPostViewModel> >, ShortcodesHandler>();
            services.AddScoped <INotificationHandler <ModelPreRender <BlogPostListViewModel> >, ShortcodesHandler>();

            var shortcodeService = new ShortcodeService();

            shortcodeService.Add <SourceCodeShortcode>(tag: "code");
            shortcodeService.Add <YouTubeShortcode>(tag: "youtube");
            services.AddSingleton <IShortcodeService>(shortcodeService);
        }
Beispiel #6
0
 protected ParserState(ShortcodeService shortcodeParser)
 {
     _shortcodeParser = shortcodeParser;
     _textParser      = shortcodeParser.TextParser;
 }
Beispiel #7
0
 public ParsingCloseTagState(ShortcodeService shortcodeParser)
     : base(shortcodeParser)
 {
 }
 public ParsingAttributesState(ShortcodeService shortcodeParser) : base(shortcodeParser)
 {
 }
Beispiel #9
0
 public LookingForTagState(ShortcodeService shortcodeParser) : base(shortcodeParser)
 {
 }
Beispiel #10
0
        public void ConfigureServices(IServiceCollection services)
        {
            // Db

            /**
             * AddDbContextPool is an EF Core 2.0 performance enhancement https://docs.microsoft.com/en-us/ef/core/what-is-new/
             * unfortunately it has limitations and cannot be used here.
             * 1. It interferes with dbcontext implicit transactions when events are raised and event handlers call SaveChangesAsync
             * 2. Multiple dbcontexts will fail https://github.com/aspnet/EntityFrameworkCore/issues/9433
             * 3. To use AddDbContextPool, FanDbContext can only have a single public constructor accepting a single parameter of type DbContextOptions
             */
            services.AddDbContext <FanDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            // Identity
            services.AddIdentity <User, Role>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 4;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;
            })
            .AddEntityFrameworkStores <FanDbContext>()
            .AddDefaultTokenProviders();

            // Caching
            services.AddDistributedMemoryCache();

            // Mapper
            services.AddAutoMapper();
            services.AddSingleton(BlogUtil.Mapper);

            // Mediatr
            services.AddMediatR();

            // Repos & Services
            services.AddScoped <IMetaRepository, SqlMetaRepository>();
            services.AddScoped <IMediaRepository, SqlMediaRepository>();
            services.AddScoped <IPostRepository, SqlPostRepository>();
            services.AddScoped <ICategoryRepository, SqlCategoryRepository>();
            services.AddScoped <ITagRepository, SqlTagRepository>();
            services.AddScoped <ISettingService, SettingService>();
            services.AddScoped <IMediaService, MediaService>();
            services.AddScoped <IEmailSender, EmailSender>();
            services.AddScoped <IBlogService, BlogService>();
            services.AddScoped <IXmlRpcHelper, XmlRpcHelper>();
            services.AddScoped <IMetaWeblogService, MetaWeblogService>();
            services.AddScoped <IHttpWwwRewriter, HttpWwwRewriter>();
            var appSettingsConfigSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsConfigSection);
            var appSettings = appSettingsConfigSection.Get <AppSettings>();

            if (appSettings.MediaStorageType == EMediaStorageType.AzureBlob)
            {
                services.AddScoped <IStorageProvider, AzureBlobStorageProvider>();
            }
            else
            {
                services.AddScoped <IStorageProvider, FileSysStorageProvider>();
            }
            var shortcodeService = new ShortcodeService();

            shortcodeService.Add <SourceCodeShortcode>(tag: "code");
            shortcodeService.Add <YouTubeShortcode>(tag: "youtube");
            services.AddSingleton <IShortcodeService>(shortcodeService);
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // Mvc
            services.AddMvc();

            // AppInsights
            services.AddApplicationInsightsTelemetry(Configuration);
        }
Beispiel #11
0
        public void ConfigureServices(IServiceCollection services)
        {
            // GDPR support
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            // Db

            /**
             * AddDbContextPool is an EF Core 2.0 performance enhancement https://docs.microsoft.com/en-us/ef/core/what-is-new/
             * unfortunately it has limitations and cannot be used here.
             * 1. It interferes with dbcontext implicit transactions when events are raised and event handlers call SaveChangesAsync
             * 2. Multiple dbcontexts will fail https://github.com/aspnet/EntityFrameworkCore/issues/9433
             * 3. To use AddDbContextPool, FanDbContext can only have a single public constructor accepting a single parameter of type DbContextOptions
             */
            services.AddDbContext <FanDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            // Identity
            services.AddIdentity <User, Role>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 8;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;
                options.User.RequireUniqueEmail         = true;
            })
            .AddEntityFrameworkStores <FanDbContext>()
            .AddDefaultTokenProviders();

            // LoginPath https://github.com/aspnet/Identity/issues/1414#issuecomment-328185754
            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath        = "/login";
                options.AccessDeniedPath = "/denied";
            });

            // Caching
            services.AddDistributedMemoryCache();

            // Mapper
            services.AddAutoMapper();
            services.AddSingleton(BlogUtil.Mapper);

            // Mediatr
            services.AddMediatR();

            // Repos & Services
            services.AddScoped <IMetaRepository, SqlMetaRepository>();
            services.AddScoped <IMediaRepository, SqlMediaRepository>();
            services.AddScoped <IPostRepository, SqlPostRepository>();
            services.AddScoped <ICategoryRepository, SqlCategoryRepository>();
            services.AddScoped <ITagRepository, SqlTagRepository>();
            services.AddScoped <ISettingService, SettingService>();
            services.AddScoped <IMediaService, MediaService>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IEmailSender, EmailSender>();
            services.AddScoped <IBlogService, BlogService>();
            services.AddScoped <IXmlRpcHelper, XmlRpcHelper>();
            services.AddScoped <IMetaWeblogService, MetaWeblogService>();
            services.AddScoped <IPreferredDomainRewriter, PreferredDomainRewriter>();
            var appSettingsConfigSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsConfigSection);
            var appSettings = appSettingsConfigSection.Get <AppSettings>();

            if (appSettings.MediaStorageType == EMediaStorageType.AzureBlob)
            {
                services.AddScoped <IStorageProvider, AzureBlobStorageProvider>();
            }
            else
            {
                services.AddScoped <IStorageProvider, FileSysStorageProvider>();
            }
            var shortcodeService = new ShortcodeService();

            shortcodeService.Add <SourceCodeShortcode>(tag: "code");
            shortcodeService.Add <YouTubeShortcode>(tag: "youtube");
            services.AddSingleton <IShortcodeService>(shortcodeService);
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // Mvc and Razor Pages

            // theme
            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new ThemeViewLocationExpander());
            });

            // if you update the roles and find the app not working, try logout then login https://stackoverflow.com/a/48177723/32240
            services.AddAuthorization(options =>
            {
                options.AddPolicy("AdminRoles", policy => policy.RequireRole("Administrator", "Editor"));
            });

            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(options => {
                options.SerializerSettings.ContractResolver      = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            })
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/Admin", "AdminRoles");
            });

            // https://stackoverflow.com/q/50472962/32240
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                ContractResolver      = new CamelCasePropertyNamesContractResolver(),
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };

            // To make ajax work with razor pages, without this ajax post will get 404
            // http://www.talkingdotnet.com/handle-ajax-requests-in-asp-net-core-razor-pages/
            services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

            // AppInsights
            services.AddApplicationInsightsTelemetry(Configuration);
        }