Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Json SerializerSettings #2069

Open
VikneshSubramaniyan opened this issue May 15, 2024 · 2 comments
Open

Json SerializerSettings #2069

VikneshSubramaniyan opened this issue May 15, 2024 · 2 comments
Labels

Comments

@VikneshSubramaniyan
Copy link

Hi Tidyui,

I have faced the some issue. Before using Piranha, I used AddMVC. When I use the AddMVC function, it breaks the Piranha manager function. The code I provided below:

services.AddMvc(options => options.EnableEndpointRouting = true)
.AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

However, I tried to add internally in

options.UseManager(o =>
{
o.JsonOptions(options =>
{
// I don't know how to add here for JSON serialization
});
});.
Could you please give me an idea?

@tidyui
Copy link
Member

tidyui commented May 15, 2024

There seems to be a typo in the official documentation. This would be the correct way to add the options in your Program.cs

builder.AddPiranha(options =>
{

   ...

   options.UseManager(o => {
        o.JsonOptions = (jsonOptions) =>
        {
            jsonOptions.SerializerSettings.ContractResolver = new DefaultContractResolver();
        };
    });

   ...

});

Regards

@VikneshSubramaniyan
Copy link
Author

using System;
using Dapper;
//using Hangfire;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Serialization;
using Piranha;
using Piranha.AttributeBuilder;
using Piranha.ImageSharp;
using Piranha.Local;
//using Piranha.Manager.Binders;
using SendbackPortal.Data;
using SendbackPortal.Jobs;
using SendbackPortal.Models;
using SendbackPortal.Models.AccountViewModels;
using SendbackPortal.Models.Templates;
using SendbackPortal.Repositories;
using SendbackPortal.Services;
using EntityFrameworkCore.UseRowNumberForPaging;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Newtonsoft.Json;
using Piranha.Manager.TinyMCE;
using Piranha.Data.EF.SQLServer;
using Piranha.Manager.LocalAuth;
using Piranha.Manager.Editor;

namespace SendbackPortal
{

/// <summary>
/// Application configuration
/// </summary>
public class Startup
{
    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        Configuration = configuration;
        var contentRoot = configuration.GetValue<string>(WebHostDefaults.ContentRootKey);
    }

    public IConfiguration Configuration { get; }
    public string conn; 
    // This method gets called by the runtime. Use this method to add services to the container.
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        // Get connection strings from the appsettings.json file
        var defaultConnection = Configuration.GetConnectionString("DefaultConnection");
        var advConnection = Configuration.GetConnectionString("ADVConnection");
        conn = advConnection;
       
        // BB 5/16/2018 - make compatible with SQL Server 2008R2
        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(defaultConnection, b => b.UseRowNumberForPaging()));
        services.AddDbContext<SQLServerDb>(options => options.UseSqlServer(defaultConnection, b => b.UseRowNumberForPaging()));
        services.AddDbContext<DefaultDBContext>(options => options.UseSqlServer(defaultConnection, b => b.UseRowNumberForPaging()));
        services.AddDbContext<AdvDbContext>(options => options.UseSqlServer(advConnection, b => b.UseRowNumberForPaging()));
        //services.AddDbContext<AdvPhysicianMessengerDbContext>(options => options.UseSqlServer(advPhysicianMessengerConnection, b => b.UseRowNumberForPaging()));
        
        // Set up the authentication for the application
        services.AddIdentity<ApplicationUser, IdentityRole>(options => {
            options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+/' ";
        })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders()
            .AddErrorDescriber<CustomIdentityErrorDescriber>(); // Add this line

        
        services.Configure<DataProtectionTokenProviderOptions>(o => o.TokenLifespan = TimeSpan.FromDays(14));
        //services.Configure<DataProtectionTokenProviderOptions>(o => o.TokenLifespan = TimeSpan.FromMinutes(2));   // minutes for testing purposes

        // Add Global singletons
        services.AddSingleton(Configuration);
        services.AddSingleton<IStorage, FileStorage>();
        services.AddSingleton<IImageProcessor, ImageSharpProcessor>();
        services.AddTransient<ISecurity, IdentitySecurity>();
        services.AddScoped<IDb, SQLServerDb>();
        services.AddScoped<IApi, Api>();

        // Allow the this application to use the Piranha manager
        services.AddPiranha(options =>
        {
            options.UseCms();
            options.UseManager(o => {
                o.JsonOptions = (jsonOptions) =>
                {
                    jsonOptions.SerializerSettings.ContractResolver = new DefaultContractResolver();
                };
            });
            options.UseFileStorage(naming: Piranha.Local.FileStorageNaming.UniqueFolderNames);
            options.UseImageSharp();
           
            options.UseTinyMCE();
            
            //options.UseMemoryCache();
            options.UseEF<SQLServerDb>(db =>
                db.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            //options.UseIdentityWithSeed<IdentitySQLServerDb>(db =>
            //    db.UseSqlServer("DefaultConnection"));
        });


       
        services.AddTransient<IEmailSender, EmailSender>();
        services.AddTransient<IUserRepository, UserRepository>();
        services.AddTransient<ISendbackRepository, SendbackRepository>();
        services.AddTransient<IUsersMappingRepository, UsersMappingRepository>();
        services.AddTransient<IPhysicianMessengerRepository, PhysicianMessengerRepository>();
        services.AddTransient<ILocationExclusionRepository, LocationExclusionRepository>();

        services.AddSession();

        return services.BuildServiceProvider();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services)
    {

        // Show useful error messages if the application is in development
        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        DefaultTypeMap.MatchNamesWithUnderscores = true;
       
        // Initialize Piranha
        var api = services.GetService<IApi>();
        App.Init(api);

        var pageTypeBuilder = new ContentTypeBuilder(api)
            .AddType(typeof(BlogArchive))
            .AddType(typeof(StandardPage));
        pageTypeBuilder.Build(); 
        var postTypeBuilder = new ContentTypeBuilder(api)
            .AddType(typeof(BlogPost));
       postTypeBuilder.Build(); 
        EditorConfig.FromFile("editorconfig.json");

        // Register middleware
        app.UseStaticFiles();
        //app.UseRouting();
        app.UseAuthentication();
      // app.UseAuthorization();
        app.UseMiddleware<PasswordMiddleware>();

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

}

still piranha manger function is breaking ..JSON serialization did not work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants