3, Custom Abp Vnext project generation template

We know that we can quickly build a basic abp project environment through the abp cli command, but we generally need to use our own UI, database and basic configuration in our projects. If we use the official default template to create the project every time, we need to repeat the process of the previous two chapters to build the basic environment every time, which is obviously a waste of time;

In this chapter, we will introduce how to create our own abp project template.

First, download the abp source code from github, https://github.com/abpframework/abp/releases , v5.0.0-rc.1 version used in this paper; After decompression, copy the templates directory to any location on the disk

Here, we only modify the template of the app project and open the MyCompanyName.MyProjectName.sln solution file in the app / aspnet core directory. Before, our projects were all Anglar front-end, mysql database and apiHost integrated with IdentityServer. We only need to modify the following projects:

In order to publish the template independently from the abp source code, first replace all abp project references in the project file with package references, such as MyCompanyName.Application project:

 

Then follow Chapter I Modify MyCompanyName.MyProjectName.EntityFrameworkCore project to support MySql database;

In addition, on this basis, we can add some other basic functions or delete some useless things

1. Delete redundant multilingual resources

Locate the Localization/MyProjectName directory of MyCompanyName.MyProjectName.Domain.Shared project, delete redundant multilingual resources, and only keep their common ones. Here we only keep Chinese and English

Continue to navigate to MyProjectNameHttpApiHostModule file of MyCompanyName.MyProjectName.HttpApi.HostWithIds project and remove redundant language definitions

2. Configure audit log parameters

Open the MyProjectNameHttpApiHostModule file of MyCompanyName.MyProjectName.HttpApi.HostWithIds project, and add the following content in the ConfigureServices method

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();
            var hostingEnvironment = context.Services.GetHostingEnvironment();

            Configure<AbpAuditingOptions>(options =>
            {
                options.IsEnabled = true;
                options.IsEnabledForAnonymousUsers = false; // Do not log anonymous users
                options.IsEnabledForGetRequests = false; // Do not log Get request users
            });
            
            ...
            ...
          }

  Set it here according to your own situation. According to the default option, a large number of logs may be generated in the actual production environment. I generated more than 100000 logs in the previous project in one month. It's much better to follow the above configuration

  3. Add file upload and download support

In order to cooperate with the contents of the following chapters, the configuration related to file processing is included in the template, and the later generated code directly supports file processing

Or in the MyProjectNameHttpApiHostModule file of the MyCompanyName.MyProjectName.HttpApi.HostWithIds project, modify the ConfigureConventionalControllers method as follows

        private void ConfigureConventionalControllers()
        {
            Configure<AbpAspNetCoreMvcOptions>(options =>
            {
                options.ConventionalControllers.Create(typeof(MyProjectNameApplicationModule).Assembly);
                options.ConventionalControllers.FormBodyBindingIgnoredTypes.Add(typeof(RemoteStreamContent));
            });
        }

The code to modify the ConfigureSwaggerServices method is as follows

                options =>
                {
                    options.SwaggerDoc("v1", new OpenApiInfo {Title = "FixtrueControl API", Version = "v1"});
                    options.DocInclusionPredicate((docName, description) => true);
                    options.CustomSchemaIds(type => type.FullName);
                    options.MapType<FileContentResult>(() => new OpenApiSchema { Type = "string", Format = "binary" });
                });

  Modify the code added in the ConfigureCors method as follows:

                options.AddPolicy(DefaultCorsPolicyName, builder =>
                {
                    builder
                        .WithOrigins(
                            configuration["App:CorsOrigins"]
                                .Split(",", StringSplitOptions.RemoveEmptyEntries)
                                .Select(o => o.RemovePostFix("/"))
                                .ToArray()
                        )
                        .WithAbpExposedHeaders()
                        .WithExposedHeaders("Content-Disposition") // file-download
                        .SetIsOriginAllowedToAllowWildcardSubdomains()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                });

4. Modify the Serilog logging parameters

Open the Program.cs file of MyCompanyName.MyProjectName.HttpApi.HostWithIds project, and modify the following contents as follows:

                // Always print console log
                .WriteTo.Async(c => c.Console())
#if RELEASE
                // Include file logs in the release version whenever possible
                .WriteTo.Async(c => c.File("logs/logs.txt", rollingInterval: RollingInterval.Day))
#endif
                .Crea

The reason for this modification is that according to the original method, when I deploy the program to docker, I can't view the console log. In addition, in the debug mode, I just need to look at the console log instead of writing the file log

5. Inherited multilingual resources

Open the MyProjectNameHttpApiModule file of MyCompanyName.MyProjectName.HttpApi and locate it at AddBaseTypes. This should not be necessary because multilingual resources of any other module can be located through resource prefix in angular. Adding AddBaseTypes will attach all resource items in BaseType in appConfiguration, We can access and view the results through the API / abp / application configuration interface. We can find that each abp's own business module contains the same AbpUiResource multilingual resource project. If all our own modules add these resources, the json content returned by this interface will increase a lot; Personally, it is recommended to inherit AbpUiResource in the main project at most, so that the front end can access multilingual resources without resource prefix; Do not inherit AbpUiResource in self built modules

6. Front end api access proxy class generation configuration

This configuration is used in the user-defined module, because we usually do not complete all functions in one module. The generation of front-end agent classes after module division also needs to be divided into modules, which will be described in detail in later chapters

Add MyProjectNameRemoteServiceConsts.cs class in MyCompanyName.MyProjectName.Application.Contracts project, and the filling file contents are as follows:

namespace MyCompanyName.MyProjectName
{
    public class MyProjectNameRemoteServiceConsts
    {
        public const string RemoteServiceName = "MyProjectName";

        public const string AreaName = "my-project-name";
    }
}

7. Add default roles during database migration

Add the directory Identity in the MyCompanyName.MyProjectName.Domain project, and add the DefaultRolesDataSeedContributor.cs file under the changed directory. The contents of the file are as follows:

using Microsoft.AspNetCore.Identity;
using System.Threading.Tasks;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Guids;
using Volo.Abp.Identity;
using Volo.Abp.MultiTenancy;

namespace MyCompanyName.MyProjectName.Identity
{
    public class DefaultRolesDataSeedContributor : IDataSeedContributor, ITransientDependency
    {
        protected IGuidGenerator GuidGenerator { get; }
        protected IdentityRoleManager RoleManager { get; }
        protected ICurrentTenant CurrentTenant { get; }
        protected ILookupNormalizer LookupNormalizer { get; }
        protected IIdentityRoleRepository RoleRepository { get; }
        public DefaultRolesDataSeedContributor(IGuidGenerator guidGenerator, ILookupNormalizer lookupNormalizer,
            IdentityRoleManager roleManager, ICurrentTenant currentTenant, IIdentityRoleRepository roleRepository)
        {
            LookupNormalizer = lookupNormalizer;
            GuidGenerator = guidGenerator;
            CurrentTenant = currentTenant;
            RoleManager = roleManager;
            RoleRepository = roleRepository;
        }
        public async Task SeedAsync(DataSeedContext context)
        {
            var tenantId = context?.TenantId;
            using (CurrentTenant.Change(tenantId))
            {

                // Add an ordinary role
                const string ordinaryRoleName = "ordinary";
                var ordinaryRole =
                    await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName(ordinaryRoleName));
                if (ordinaryRole == null)
                {
                    ordinaryRole = new Volo.Abp.Identity.IdentityRole(
                          GuidGenerator.Create(),
                          ordinaryRoleName,
                          tenantId
                      )
                    {
                        IsStatic = true,
                        IsPublic = true, 
                        IsDefault = true // Set the role as the default role, which will be automatically assigned when creating users
                    };

                    (await RoleManager.CreateAsync(ordinaryRole)).CheckErrors();
                }
            }
        }
    }

}

abp will detect all idataseedcontributors during data migration. Therefore, it will execute the SeedAsync method in DefaultRolesDataSeedContributor and insert the default role. In this way, the user will have the authority of order by default when registering himself or when the administrator adds a user

8. angular front end modification

This is modified according to the scheme of coreui in the previous section, so I won't repeat it

9. Building projects using templates

Enter the F:\BlogSamples\templates\app directory (where personal templates are stored), select the angular and aspnet core directories, and package the two directories into app-5.0.0-rc.1.zip

Open the console program in any directory and execute the abp cli command as follows:

abp new MyGroup.TestProject  -u angular --mobile none -d ef -csf -cs "server=192.168.100.175;port=3306;database=abp_test2;uid=test;pwd=Test123$;SslMode=none" -ts "F:\BlogSamples\templates\app" -v 5.0.0-rc.1

After the code generation is successful, open the aspnet core solution with vs2022, run the MyGroup.TestProject.DbMigrator project to perform data migration, then compile and run the Api.Host project, open the angular directory with vscode, execute npm install and npm start, and open the browser http://localhost:4200/ After that, the familiar interface came back, and we also found that the default role has been added

  You can also upload the app-5.0.0-rc.1.zip file to the personal website. In the command, you only need to replace the local disk address with the network address

Project generation template source code (only the parts used in the article have been modified)

Tags: C# angular abp

Posted on Sun, 05 Dec 2021 03:51:40 -0500 by slava_php