diff --git a/README.md b/README.md index 1b4d56dd26..8d872160ca 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![Build Status](http://vjenkins.dynu.net:5480/job/abp/badge/icon)](http://ci.volosoft.com:5480/blue/organizations/jenkins/abp/activity) [![NuGet](https://img.shields.io/nuget/v/Volo.Abp.Core.svg?style=flat-square)](https://www.nuget.org/packages/Volo.Abp.Core) [![NuGet Download](https://img.shields.io/nuget/dt/Volo.Abp.Core.svg?style=flat-square)](https://www.nuget.org/packages/Volo.Abp.Core) -[![MyGet (with prereleases)](https://img.shields.io/myget/abp-nightly/vpre/Volo.Abp.Core.svg?style=flat-square)](https://docs.abp.io/en/abp/latest/Nightly-Builds) +[![MyGet (with prereleases)](https://img.shields.io/myget/abp-nightly/vpre/Volo.Abp.svg?style=flat-square)](https://docs.abp.io/en/abp/latest/Nightly-Builds) This project is the next generation of the [ASP.NET Boilerplate](https://aspnetboilerplate.com/) web application framework. See [the announcement](https://blog.abp.io/abp/Abp-vNext-Announcement). diff --git a/docs/en/AspNet-Boilerplate-Migration-Guide.md b/docs/en/AspNet-Boilerplate-Migration-Guide.md new file mode 100644 index 0000000000..d47b266839 --- /dev/null +++ b/docs/en/AspNet-Boilerplate-Migration-Guide.md @@ -0,0 +1,734 @@ +# ASP.NET Boilerplate v5+ to ABP Framework Migration + +ABP Framework is **the successor** of the open source [ASP.NET Boilerplate](https://aspnetboilerplate.com/) framework. This guide aims to help you to **migrate your existing solutions** (you developed with the ASP.NET Boilerplate framework) to the ABP Framework. + +## Introduction + +**ASP.NET Boilerplate** is being **actively developed** [since 2013](https://github.com/aspnetboilerplate/aspnetboilerplate/graphs/contributors). It is loved, used and contributed by the community. It started as a side project of [a developer](http://halilibrahimkalkan.com/), but now it is officially maintained and improved by the company [Volosoft](https://volosoft.com/) in addition to the great community support. + +ABP Framework has the same goal of the ASP.NET Boilerplate framework: **Don't Repeat Yourself**! It provides infrastructure, tools and startup templates to make a developer's life easier while developing enterprise software solutions. + +See [the introduction blog post](https://blog.abp.io/abp/Abp-vNext-Announcement) if you wonder why we needed to re-write the ASP.NET Boilerplate framework. + +### Should I Migrate? + +No, you don't have to! + +* ASP.NET Boilerplate is still in active development and maintenance. +* It also works on the latest ASP.NET Core and related libraries and tools. It is up to date. + +However, if you want to take the advantage of the new ABP Framework [features](https://abp.io/features) and the new architecture opportunities (like support for NoSQL databases, microservice compatibility, advanced modularity), you can use this document as a guide. + +### What About the ASP.NET Zero? + +[ASP.NET Zero](https://aspnetzero.com/) is a commercial product developed by the core ASP.NET Boilerplate team, on top of the ASP.NET Boilerplate framework. It provides pre-built application [features](https://aspnetzero.com/Features), code generation tooling and a nice looking modern UI. It is trusted and used by thousands of companies from all around the World. + +We have created the [ABP Commercial](https://commercial.abp.io/) as an alternative to the ASP.NET Zero. ABP Commercial is more modular and upgradeable compared to the ASP.NET Zero. It currently has less features compared to ASP.NET Zero, but the gap will be closed by the time (it also has some features don't exist in the ASP.NET Zero). + +We think ASP.NET Zero is still a good choice while starting a new application. It is production ready and mature solution delivered as a full source code. It is being actively developed and we are constantly adding new features. + +We don't suggest to migrate your ASP.NET Zero based solution to the ABP Commercial if; + +* Your ASP.NET Zero solution is mature and it is in maintenance rather than a rapid development. +* You don't have enough development time to perform the migration. +* A monolithic solution fits in your business. +* You've customized existing ASP.NET Zero features too much based on your requirements. + +We also suggest you to compare the features of two products based on your needs. + +If you have an ASP.NET Zero based solution and want to migrate to the ABP Commercial, this guide will also help you. + +### ASP.NET MVC 5.x Projects + +The ABP Framework doesn't support ASP.NET MVC 5.x, it only works with ASP.NET Core. So, if you migrate your ASP.NET MVC 5.x based projects, you will also deal with the .NET Core migration. + +## The Migration Progress + +We've designed the ABP Framework by **getting the best parts** of the ASP.NET Boilerplate framework, so it will be familiar to you if you've developed ASP.NET Boilerplate based applications. + +In the ASP.NET Boilerplate, we have not worked much on the UI side, but used some free themes (we've used [metronic theme](https://keenthemes.com/metronic/) for ASP.NET Zero on the other side). In the ABP Framework, we worked a lot on the UI side (especially for the MVC / Razor Pages UI, because Angular already has a good modular system of its own). So, the **most challenging part** of the migration will be the **User Interface** of your solution. + +ABP Framework is (and ASP.NET Boilerplate was) designed based on the [Domain Driven Design](https://docs.abp.io/en/abp/latest/Domain-Driven-Design) patterns & principles and the startup templates are layered based on the DDD layers. So, this guide respects to that layering model and explains the migration layer by layer. + +## Creating the Solution + +First step of the migration is to create a new solution. We suggest you to create a fresh new project using [the startup templates](https://abp.io/get-started) (see [this document](https://docs.abp.io/en/commercial/latest/getting-started) for the ABP Commercial). + +After creating the project and running the application, you can copy your code from your existing solution to the new solution step by step, layer by layer. + +### About Pre-Built Modules + +The startup projects for the ABP Framework use the [pre-built modules](https://docs.abp.io/en/abp/latest/Modules/Index) (not all of them, but the essentials) and themes as NuGet/NPM packages. So, you don't see the source code of the modules/themes in your solution. This has an advantage that you can easily update these packages when a new version is released. However, you can not easily customize them as their source code in your hands. + +We suggest to continue to use these modules as package references, in this way you can get new features easily (see [abp update command](https://docs.abp.io/en/abp/latest/CLI#update)). In this case, you have a few options to customize or extend the functionality of the used modules; + +* You can create your own entity and share the same database table with an entity in a used module. An example of this is the `AppUser` entity comes in the startup template. +* You can [replace](https://docs.abp.io/en/abp/latest/Dependency-Injection#replace-a-service) a domain service, application service, controller, page model or other types of services with your own implementation. We suggest you to inherit from the existing implementation and override the method you need. +* You can replace a `.cshtml` view, page, view component, partial view... with your own one using the [Virtual File System](https://docs.abp.io/en/abp/latest/Virtual-File-System). +* You can override javascript, css, image or any other type of static files using the [Virtual File System](https://docs.abp.io/en/abp/latest/Virtual-File-System). + +More extend/customization options will be developed and documented by the time. However, if you need to fully change the module implementation, it is best to add the [source code](https://github.com/abpframework/abp/tree/dev/modules) of the related module into your own solution and remove the package dependencies. + +The source code of the modules and the themes are [MIT](https://opensource.org/licenses/MIT) licensed, you can fully own and customize it without any limitation (for the ABP Commercial, you can download the source code of a [module](https://commercial.abp.io/modules)/[theme](https://commercial.abp.io/themes) if you have a [license](https://commercial.abp.io/pricing) type that includes the source code). + +## The Domain Layer + +Most of your domain layer code will remain same, while you need to perform some minor changes in your domain objects. + +### Aggregate Roots & Entities + +The ABP Framework and the ASP.NET Boilerplate both have the `IEntity` and `IEntity` interfaces and `Entity` and `Entity` base classes to define entities but they have some differences. + +If you have an entity in the ASP.NET Boilerplate application like that: + +````csharp +public class Person : Entity //Default PK is int for the ASP.NET Boilerplate +{ + ... +} +```` + +Then your primary key (the `Id` property in the base class) is `int` which is the **default primary key** (PK) type for the ASP.NET Boilerplate. If you want to set another type of PK, you need to explicitly declare it: + +````csharp +public class Person : Entity //Set explicit PK in the ASP.NET Boilerplate +{ + ... +} +```` + +ABP Framework behaves differently and expects to **always explicitly set** the PK type: + +````csharp +public class Person : Entity //Set explicit PK in the ASP.NET Boilerplate +{ + ... +} +```` + +`Id` property (and the corresponding PK in the database) will be `Guid` in this case. + +#### Composite Primary Keys + +ABP Framework also has a non-generic `Entity` base class, but this time it has no `Id` property. Its purpose is to allow you to create entities with composite PKs. See [the documentation](https://docs.abp.io/en/abp/latest/Entities#entities-with-composite-keys) to learn more about the composite PKs. + +#### Aggregate Root + +It is best practice now to use the `AggregateRoot` base class instead of `Entity` for aggregate root entities. See [the documentation](https://docs.abp.io/en/abp/latest/Entities#aggregateroot-class) to learn more about the aggregate roots. + +In opposite to the ASP.NET Boilerplate, the ABP Framework creates default repositories (`IRepository`) **only for the aggregate roots**. It doesn't create for other types derived from the `Entity`. + +If you still want to create default repositories for all entity types, find the *YourProjectName*EntityFrameworkCoreModule class in your solution and change `options.AddDefaultRepositories()` to `options.AddDefaultRepositories(includeAllEntities: true)` (it may be already like that for the application startup template). + +#### Migrating the Existing Entities + +We suggest & use the GUID as the PK type for all the ABP Framework modules. However, you can continue to use your existing PK types to migrate your database tables easier. + +The challenging part will be the primary keys of the ASP.NET Boilerplate related entities, like Users, Roles, Tenants, Settings... etc. Our suggestion is to copy data from existing database to the new database tables using a tool or in a manual way (be careful about the foreign key values). + +#### Documentation + +See the documentation for details on the entities: + +* [ASP.NET Boilerplate - Entity documentation](https://aspnetboilerplate.com/Pages/Documents/Entities) +* [ABP Framework - Entity documentation](https://docs.abp.io/en/abp/latest/Entities) + +### Repositories + +> ABP Framework creates default repositories (`IRepository`) **only for the aggregate roots**. It doesn't create for other types derived from the `Entity`. See the "Aggregate Root" section above for more information. + +The ABP Framework and the ASP.NET Boilerplate both have the default generic repository system, but has some differences. + +#### Injecting the Repositories + +In the ASP.NET Boilerplate, there are two default repository interfaces you can directly inject and use: + +* `IRepository` (e.g. `IRepository`) is used for entities with `int` primary key (PK) which is the default PK type. +* `IRepository` (e.g. `IRepository`) is used for entities with other types of PKs. + +ABP Framework doesn't have a default PK type, so you need to **explicitly declare the PK type** of your entity, like `IRepository` or `IRepository`. + +ABP Framework also has the `IRepository` (without PK), but it is mostly used when your entity has a composite PK (because this repository has no methods work with the `Id` property). See [the documentation](https://docs.abp.io/en/abp/latest/Entities#entities-with-composite-keys) to learn more about the **composite PKs**. + +#### Restricted Repositories + +ABP Framework additionally provides a few repository interfaces: + +* `IBasicRepository` has the same methods with the `IRepository` except it doesn't have `IQueryable` support. It can be useful if you don't want to expose complex querying code to the application layer. In this case, you typically want to create custom repositories to encapsulate the querying logic. It is also useful for database providers those don't support `IQueryable`. +* `IReadOnlyRepository` has the methods get data from the database, but doesn't contain any method change the database. +* `IReadOnlyBasicRepository` is similar to the read only repository but also doesn't support `IQueryable`. + +All the interfaces also have versions without `TKey` (like ``IReadOnlyRepository`) those can be used for composite PKs just like explained above. + +#### GetAll() vs IQueryable + +ASP.NET Boilerplate's repository has a `GetAll()` method that is used to obtain an `IQueryable` object to execute LINQ on it. An example application service calls the `GetAll()` method: + +````csharp +public class PersonAppService : ApplicationService, IPersonAppService +{ + private readonly IRepository _personRepository; + + public PersonAppService(IRepository personRepository) + { + _personRepository = personRepository; + } + + public async Task DoIt() + { + var people = await _personRepository + .GetAll() //GetAll() returns IQueryable + .Where(p => p.BirthYear > 2000) //Use LINQ extension methods + .ToListAsync(); + } +} +```` + +ABP Framework's repository doesn't have this method. Instead, it implements the `IQueryable` itself. So, you can directly use LINQ on the repository: + +````csharp +public class PersonAppService : ApplicationService, IPersonAppService +{ + private readonly IRepository _personRepository; + + public PersonAppService(IRepository personRepository) + { + _personRepository = personRepository; + } + + public async Task DoIt() + { + var people = await _personRepository + .Where(p => p.BirthYear > 2000) //Use LINQ extension methods + .ToListAsync(); + } +} +```` + +> Note that in order to use the async LINQ extension methods (like `ToListAsync` here), you may need to depend on the database provider (like EF Core) since these methods are defined in the database provider package, they are not standard LINQ methods. + +#### FirstOrDefault(predicate), Single()... Methods + +ABP Framework repository has not such methods get predicate (expression) since the repository itself is `IQueryable` and all these methods are already standard LINQ extension methods those can be directly used. + +However, it provides the following methods those can be used to query a single entity by its Id: + +* `FindAsync(id)` returns the entity or null if not found. +* `GetAsync(id)` method returns the entity or throws an `EntityNotFoundException` (which causes HTTP 404 status code) if not found. + +#### Sync vs Async + +ABP Framework repository has no sync methods (like `Insert`). All the methods are async (like `InsertAsync`). So, if your application has sync repository method usages, convert them to async versions. + +In general, ABP Framework forces you to completely use async everywhere, because mixing async & sync methods is not a recommended approach. + +#### Documentation + +See the documentation for details on the repositories: + +* [ASP.NET Boilerplate - Repository documentation](https://aspnetboilerplate.com/Pages/Documents/Repositories) +* [ABP Framework - Repository documentation](https://docs.abp.io/en/abp/latest/Repositories) + +### Domain Services + +Your domain service logic mostly remains same on the migration. ABP Framework also defines the base `DomainService` class and the `IDomainService` interface just works like the ASP.NET Boilerplate. + +## The Application Layer + +Your application service logic remains similar on the migration. ABP Framework also defines the base `ApplicationService` class and the `IApplicationService` interface just works like the ASP.NET Boilerplate, but there are some differences in details. + +### Declarative Authorization + +ASP.NET Boilerplate has `AbpAuthorize` and `AbpMvcAuthorize` attributes for declarative authorization. Example usage: + +````csharp +[AbpAuthorize("MyUserDeletionPermissionName")] +public async Task DeleteUserAsync(...) +{ + ... +} +```` + +ABP Framework doesn't has such a custom attribute. It uses the standard `Authorize` attribute in all layers. + +````csharp +[Authorize("MyUserDeletionPermissionName")] +public async Task DeleteUserAsync(...) +{ + ... +} +```` + +This is possible with the better integration to the Microsoft Authorization Extensions libraries. See the Authorization section below for more information about the authorization system. + +### CrudAppService and AsyncCrudAppService Classes + +ASP.NET Boilerplate has `CrudAppService` (with sync service methods) and `AsyncCrudAppService` (with async service methods) classes. + +ABP Framework only has the `CrudAppService` which actually has only the async methods (instead of sync methods). + +ABP Framework's `CrudAppService` method signatures are slightly different than the old one. For example, old update method signature was ` Task UpdateAsync(TUpdateInput input) ` while the new one is ` Task UpdateAsync(TKey id, TUpdateInput input) `. The main difference is that it gets the Id of the updating entity as a separate parameter instead of including in the input DTO. + +### Data Transfer Objects (DTOs) + +There are similar base DTO classes (like `EntityDto`) in the ABP Framework too. So, you can find the corresponding DTO base class if you need. + +#### Validation + +You can continue to use the data annotation attributes to validate your DTOs just like in the ASP.NET Boilerplate. + +ABP Framework doesn't include the ` ICustomValidate ` that does exists in the ASP.NET Boilerplate. Instead, you should implement the standard `IValidatableObject` interface for your custom validation logic. + +## The Infrastructure Layer + +### Namespaces + +ASP.NET Boilerplate uses the `Abp.*` namespaces while the ABP Framework uses the `Volo.Abp.*` namespaces for the framework and pre-built fundamental modules. + +In addition, there are also some pre-built application modules (like docs and blog modules) those are using the `Volo.*` namespaces (like `Volo.Blogging.*` and `Volo.Docs.*`). We consider these modules as standalone open source products developed by Volosoft rather than add-ons or generic modules completing the ABP Framework and used in the applications. We've developed them as a module to make them re-usable as a part of a bigger solution. + +### Module System + +Both of the ASP.NET Boilerplate and the ABP Framework have the `AbpModule` while they are a bit different. + +ASP.NET Boilerplate's `AbpModule` class has `PreInitialize`, `Initialize` and `PostInitialize` methods you can override and configure the framework and the depended modules. You can also register and resolve dependencies in these methods. + +ABP Framework's `AbpModule` class has the `ConfigureServices` and `OnApplicationInitialization` methods (and their Pre and Post versions). It is similar to ASP.NET Core's Startup class. You configure other services and register dependencies in the `ConfigureServices`. However, you can now resolve dependencies in that point. You can resolve dependencies and configure the ASP.NET Core pipeline in the `OnApplicationInitialization` method while you can not register dependencies here. So, the new module classes separate dependency registration phase from dependency resolution phase since it follows the ASP.NET Core's approach. + +### Dependency Injection + +#### The DI Framework + +ASP.NET Boilerplate is using the [Castle Windsor](http://www.castleproject.org/projects/windsor/) as the dependency injection framework. This is a fundamental dependency of the ASP.NET Boilerplate framework. We've got a lot of feedback to make the ASP.NET Boilerplate DI framework agnostic, but it was not so easy because of the design. + +ABP Framework is dependency injection framework independent since it uses Microsoft's [Dependency Injection Extensions](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection) library as an abstraction. None of the ABP Framework or module packages depends on any specific library. + +However, ABP Framework doesn't use the Microsoft's base DI library because it has some missing features ABP Framework needs to: Property Injection and Interception. All the startup templates and the samples are using the [Autofac](https://autofac.org/) as the DI library and it is the only [officially integrated](Autofac-Integration.md) library to the ABP Framework. We suggest you to use the Autofac with the ABP Framework if you have not a good reason. If you have a good reason, please create an [issue](https://github.com/abpframework/abp/issues/new) on GitHub to request it or just implement it and send a pull request :) + +#### Registering the Dependencies + +Registering the dependencies are similar and mostly handled by the framework conventionally (like repositories, application services, controllers... etc). Implement the same `ITransientDependency`, `ISingletonDependency` and `IScopedDependency` interfaces for the services not registered by conventions. + +When you need to manually register dependencies, use the `context.Services` in the `ConfigureServices` method of your module. Example: + +````csharp +public class BlogModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + //Register an instance as singleton + context.Services.AddSingleton(new TaxCalculator(taxRatio: 0.18)); + + //Register a factory method that resolves from IServiceProvider + context.Services.AddScoped( + sp => sp.GetRequiredService() + ); + } +} +```` + +See the ABP Framework [dependency injection document](https://docs.abp.io/en/abp/latest/Dependency-Injection) for details. + +### Configuration vs Options System + +ASP.NET Boilerplate has its own configuration system to configure the framework and the modules. For example, you could disable the audit logging in the `Initialize` method of your [module](https://aspnetboilerplate.com/Pages/Documents/Module-System): + +````csharp +public override void Initialize() +{ + Configuration.Auditing.IsEnabled = false; +} +```` + +ABP Framework uses [the options pattern](Options.md) to configure the framework and the modules. You typically configure the options in the `ConfigureServices` method of your [module](Module-Development-Basics.md): + +````csharp +public override void ConfigureServices(ServiceConfigurationContext context) +{ + Configure(options => + { + options.IsEnabled = false; + }); +} +```` + +Instead of a central configuration object, there are separated option classes for every module and feature those are defined in the related documents. + +### IAbpSession vs ICurrentUser and ICurrentTenant + +ASP.NET Boilerplate's `IAbpSession` service is used to obtain the current user and tenant information, like ` UserId ` and `TenantId`. + +ABP Framework doesn't have the same service. Instead, use `ICurrentUser` and `ICurrentTenant` services. These services are defined as base properties in some common classes (like `ApplicationService` and `AbpController`), so you generally don't need to manually inject them. They also have much properties compared to the `IAbpSession`. + +### Authorization + +ABP Framework extends the [ASP.NET Core Authorization](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/introduction) by adding **permissions** as auto [policies](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies) and allowing the authorization system to be usable in the [application services](Application-Services.md) too. + +#### AbpAutorize vs Autorize + +Use the standard `[Autorize]` and `[AllowAnonymous]` attributes instead of ASP.NET Boilerplate's custom `[AbpAutorize]` and `[AbpAllowAnonymous]` attributes. + +#### IPermissionChecker vs IAuthorizationService + +Use the standard `IAuthorizationService` to check permissions instead of the ASP.NET Boilerplate's `IPermissionChecker` service. While `IPermissionChecker` also exists in the ABP Framework, it is used to explicitly use the permissions. Using `IAuthorizationService` is the recommended way since it covers other type of policy checks too. + +#### AuthorizationProvider vs PermissionDefinitionProvider + +You inherit from the `AuthorizationProvider` in the ASP.NET Boilerplate to define your permissions. ABP Framework replaces it by the `PermissionDefinitionProvider` base class. So, define your permissions by inheriting from the `PermissionDefinitionProvider` class. + +### Unit of Work + +Unit of work system has been designed to work seamlessly. For most of the cases, you don't need to change anything. + +`UnitOfWork` attribute of the ABP Framework doesn't have the `ScopeOption` (type of `TransactionScopeOption`) property. Instead, use `IUnitOfWorkManager.Begin()` method with `requiresNew = true` to create an independent inner transaction in a transaction scope. + +#### Data Filters + +ASP.NET Boilerplate implements the data filtering system as a part of the unit of work. ABP Framework has a separate `IDataFilter` service. + +See the [data filtering document](Data-Filtering.md) to learn how to enable/disable a filter. + +See [the UOW documentation](Unit-Of-Work.md) for more about the UOW system. + +### Multi-Tenancy + +#### IMustHaveTenant & IMayHaveTenant vs IMultiTenant + +ASP.NET Boilerplate defines `IMustHaveTenant` and `IMayHaveTenant` interfaces to implement them for your entities. In this way, your entities are automatically filtered according to the current tenant. Because of the design, there was a problem: You had to create a "Default" tenant in the database with "1" as the Id if you want to create a non multi-tenant application (this "Default" tenant was used as the single tenant). + +ABP Framework has a single interface for multi-tenant entities: `IMultiTenant` which defines a nullable `TenantId` property of type `Guid`. If your application is not multi-tenant, then your entities will have null TenantId (instead of a default one). + +On the migration, you need to change the TenantId field type and replace these interfaces with the `IMultiTenant` + +#### Switch Between Tenants + +In some cases you might need to switch to a tenant for a code scope and work with the tenant's data in this scope. + +In ASP.NET Boilerplate, it is done using the `IUnitOfWorkManager` service: + +````csharp +public async Task> GetProducts(int tenantId) +{ + using (_unitOfWorkManager.Current.SetTenantId(tenantId)) + { + return await _productRepository.GetAllListAsync(); + } +} +```` + +In the ABP Framework it is done with the `ICurrentTenant` service: + +````csharp +public async Task> GetProducts(Guid tenantId) +{ + using (_currentTenant.Change(tenantId)) + { + return await _productRepository.GetListAsync(); + } +} +```` + +Pass `null` to the `Change` method to switch to the host side. + +### Caching + +ASP.NET Boilerplate has its [own distributed caching abstraction](https://aspnetboilerplate.com/Pages/Documents/Caching) which has in-memory and Redis implementations. You typically inject the `ICacheManager` service and use its `GetCache(...)` method to obtain a cache, then get and set objects in the cache. + +ABP Framework uses and extends ASP.NET Core's [distributed caching abstraction](Caching.md). It defines the `IDistributedCache` services to inject a cache and get/set objects. + +### Logging + +ASP.NET Boilerplate uses Castle Windsor's [logging facility](http://docs.castleproject.org/Windsor.Logging-Facility.ashx) as an abstraction and supports multiple logging providers including Log4Net (the default one comes with the startup projects) and Serilog. You typically property-inject the logger: + +````csharp +using Castle.Core.Logging; //1: Import Logging namespace + +public class TaskAppService : ITaskAppService +{ + //2: Getting a logger using property injection + public ILogger Logger { get; set; } + + public TaskAppService() + { + //3: Do not write logs if no Logger supplied. + Logger = NullLogger.Instance; + } + + public void CreateTask(CreateTaskInput input) + { + //4: Write logs + Logger.Info("Creating a new task with description: " + input.Description); + //... + } +} +```` + +ABP Framework depends on Microsoft's [logging extensions](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging) library which is also an abstraction and there are many providers implement it. Startup templates are using the Serilog as the pre-configured logging libary while it is easy to change in your project. The usage pattern is similar: + +````csharp +//1: Import the Logging namespaces +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +public class TaskAppService : ITaskAppService +{ + //2: Getting a logger using property injection + public ILogger Logger { get; set; } + + public TaskAppService() + { + //3: Do not write logs if no Logger supplied. + Logger = NullLogger.Instance; + } + + public void CreateTask(CreateTaskInput input) + { + //4: Write logs + Logger.Info("Creating a new task with description: " + input.Description); + //... + } +} +```` + +You inject the `ILogger` instead of the `ILogger`. + +### Object to Object Mapping + +#### IObjectMapper Service + +ASP.NET Boilerplate defines an `IObjectMapper` service ([see](https://aspnetboilerplate.com/Pages/Documents/Object-To-Object-Mapping)) and has an integration to the [AutoMapper](https://automapper.org/) library. + +Example usage: Create a `User` object with the given `CreateUserInput` object: + +````csharp +public void CreateUser(CreateUserInput input) +{ + var user = ObjectMapper.Map(input); + ... +} +```` + +Example: Update an existing `User` properties with the given `UpdateUserInput` object: + +````csharp +public async Task UpdateUserAsync(Guid id, UpdateUserInput input) +{ + var user = await _userRepository.GetAsync(id); + ObjectMapper.Map(input, user); +} +```` + +ABP Framework has the same `IObjectMapper` service ([see](Object-To-Object-Mapping.md)) and the AutoMapper integration with a slightly different mapping methods. + +Example usage: Create a `User` object with the given `CreateUserInput` object: + +````csharp +public void CreateUser(CreateUserInput input) +{ + var user = ObjectMapper.Map(input); +} +```` + +This time you need to explicitly declare the source type and target type (while ASP.NET Boilerplate was requiring only the target type). + +Example: Update an existing `User` properties with the given `UpdateUserInput` object: + +````csharp +public async Task UpdateUserAsync(Guid id, UpdateUserInput input) +{ + var user = await _userRepository.GetAsync(id); + ObjectMapper.Map(input, user); +} +```` + +Again, ABP Framework expects to explicitly set the source and target types. + +#### AutoMapper Integration + +##### Auto Mapping Attributes + +ASP.NET Boilerplate has `AutoMapTo`, `AutoMapFrom` and `AutoMap` attributes to automatically create mappings for the declared types. Example: + +````csharp +[AutoMapTo(typeof(User))] +public class CreateUserInput +{ + public string Name { get; set; } + public string Surname { get; set; } + ... +} +```` + +ABP Framework has no such attributes, because AutoMapper as a [similar attribute](https://automapper.readthedocs.io/en/latest/Attribute-mapping.html) now. You need to switch to AutoMapper's attribute. + +##### Mapping Definitions + +ABP Framework follows AutoMapper principles closely. You can define classes derived from the `Profile` class to define your mappings. + +##### Configuration Validation + +Configuration validation is a best practice for the AutoMapper to maintain your mapping configuration in a safe way. + +See [the documentation](Object-To-Object-Mapping.md) for more information related to the object mapping. + +### Setting Management + +#### Defining the Settings + +In an ASP.NET Boilerplate based application, you create a class deriving from the `SettingProvider` class, implement the `GetSettingDefinitions` method and add your class to the `Configuration.Settings.Providers` list. + +In the ABP Framework, you need to derive your class from the `SettingDefinitionProvider` and implement the `Define` method. You don't need to register your class since the ABP Framework automatically discovers it. + +#### Getting the Setting Values + +ASP.NET Boilerplate provides the `ISettingManager` to read the setting values in the server side and `abp.setting.get(...)` method in the JavaScript side. + +ABP Framework has the `ISettingProvider` service to read the setting values in the server side and `abp.setting.get(...)` method in the JavaScript side. + +#### Setting the Setting Values + +For ASP.NET Boilerplate, you use the same `ISettingManager` service to change the setting values. + +ABP Framework separates it and provides the setting management module (pre-added to the startup projects) which has the ` ISettingManager ` to change the setting values. This separation was introduced to support tiered deployment scenarios (where `ISettingProvider` can also work in the client application while `ISettingManager ` can also work in the server (API) side). + +### Clock + +ASP.NET Boilerplate has a static `Clock` service ([see](https://aspnetboilerplate.com/Pages/Documents/Timing)) which is used to abstract the `DateTime` kind, so you can easily switch between Local and UTC times. You don't inject it, but just use the `Clock.Now` static method to obtain the current time. + +ABP Framework has the `IClock` service ([see](Clock.md)) which has a similar goal, but now you need to inject it whenever you need it. + +### Event Bus + +ASP.NET Boilerplate has an in-process event bus system. You typically inject the `IEventBus` (or use the static instance `EventBus.Default`) to trigger an event. It automatically triggers events for entity changes (like `EntityCreatingEventData` and `EntityUpdatedEventData`). You create a class by implementing the `IEventHandler` interface. + +ABP Framework separates the event bus into two services: `ILocalEventBus` and `IDistributedEventBus`. + +The local event bus is similar to the event bus of the ASP.NET Boilerplate while the distributed event bus is new feature introduced in the ABP Framework. + +So, to migrate your code; + +* Use the `ILocalEventBus` instead of the `IEventBus`. +* Implement the `ILocalEventHandler` instead of the `IEventHandler`. + +> Note that ABP Framework has also an `IEventBus` interface, but it does exists to be a common interface for the local and distributed event bus. It is not injected and directly used. + +### Feature Management + +Feature system is used in multi-tenant applications to define features of your application check if given feature is available for the current tenant. + +#### Defining Features + +In the ASP.NET Boilerplate ([see](https://aspnetboilerplate.com/Pages/Documents/Feature-Management)), you create a class inheriting from the `FeatureProvider`, override the `SetFeatures` method and add your class to the `Configuration.Features.Providers` list. + +In the ABP Framework ([see](Features.md)), you derive your class from the `FeatureDefinitionProvider` and override the `Define` method. No need to add your class to the configuration, it is automatically discovered by the framework. + +#### Checking Features + +You can continue to use the `RequiresFeature` attribute and `IFeatureChecker` service to check if a feature is enabled for the current tenant. + +#### Changing the Feature Values + +In the ABP Framework you use the `IFeatureManager` to change a feature value for a tenant. + +### Audit Logging + +The ASP.NET Boilerplate ([see](https://aspnetboilerplate.com/Pages/Documents/Audit-Logging)) and the ABP Framework ([see](Audit-Logging.md)) has similar audit logging systems. ABP Framework requires to add `UseAuditing()` middleware to the ASP.NET Core pipeline, which is already added in the startup templates. So, most of the times it will be work out of the box. + +### Localization + +ASP.NET Boilerplate supports XML and JSON files to define the localization key-values for the UI ([see](https://aspnetboilerplate.com/Pages/Documents/Localization)). ABP Framework only supports the JSON formatter localization files ([see](Localization.md)). So, you need to convert your XML file to JSON. + +The ASP.NET Boilerplate has its own the `ILocalizationManager` service to be injected and used for the localization in the server side. + +The ABP Framework uses [Microsoft localization extension](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization) library, so it is completely integrated to ASP.NET Core. You use the `IStringLocalizer` service to get a localized text. Example: + +````csharp +public class MyService +{ + private readonly IStringLocalizer _localizer; + + public MyService(IStringLocalizer localizer) + { + _localizer = localizer; + } + + public void Foo() + { + var str = _localizer["HelloWorld"]; //Get a localized text + } +} +```` + +So, you need to replace `ILocalizationManager` usage by the `IStringLocalizer`. + +It also provides API used in the client side: + +````js +var testResource = abp.localization.getResource('Test'); +var str = testResource('HelloWorld'); +```` + +It was like `abp.localization.localize(...)` in the ASP.NET Boilerplate. + +### Navigation vs Menu + +In ASP.NET you create a class deriving from the `NavigationProvider` to define your menu elements. Menu items has `requiredPermissionName` attributes to restrict access to a menu element. Menu items were static and your class is executed only one time. + +Int the ABP Framework you need to create a class implements the `IMenuContributor` interface. Your class is executed whenever the menu needs to be rendered. So, you can conditionally add menu items. + +As an example, this is the menu contributor of the tenant management module: + +````csharp +public class AbpTenantManagementWebMainMenuContributor : IMenuContributor +{ + public async Task ConfigureMenuAsync(MenuConfigurationContext context) + { + //Add items only to the main menu + if (context.Menu.Name != StandardMenus.Main) + { + return; + } + + //Get the standard administration menu item + var administrationMenu = context.Menu.GetAdministration(); + + //Resolve some needed services from the DI container + var authorizationService = context.ServiceProvider + .GetRequiredService(); + var l = context.ServiceProvider + .GetRequiredService>(); + + var tenantManagementMenuItem = new ApplicationMenuItem( + TenantManagementMenuNames.GroupName, + l["Menu:TenantManagement"], + icon: "fa fa-users"); + + administrationMenu.AddItem(tenantManagementMenuItem); + + //Conditionally add the "Tenants" menu item based on the permission + if (await authorizationService + .IsGrantedAsync(TenantManagementPermissions.Tenants.Default)) + { + tenantManagementMenuItem.AddItem( + new ApplicationMenuItem( + TenantManagementMenuNames.Tenants, + l["Tenants"], + url: "/TenantManagement/Tenants")); + } + } +} +```` + +So, you need to check permission using the `IAuthorizationService` if you want to show a menu item only when the user has the related permission. + +> Navigation/Menu system is only for ASP.NET Core MVC / Razor Pages applications. Angular applications has a different system implemented in the startup templates. + +## Missing Features + +The following features are not present for the ABP Framework. Here, a list of some major missing features (and the related issue for that feature waiting on the ABP Framework GitHub repository): + +* [Multi-Lingual Entities](https://aspnetboilerplate.com/Pages/Documents/Multi-Lingual-Entities) ([#1754](https://github.com/abpframework/abp/issues/1754)) +* [Real time notification system](https://aspnetboilerplate.com/Pages/Documents/Notification-System) ([#633](https://github.com/abpframework/abp/issues/633)) +* [NHibernate Integration](https://aspnetboilerplate.com/Pages/Documents/NHibernate-Integration) ([#339](https://github.com/abpframework/abp/issues/339)) - We don't intent to work on this, but any community contribution welcome. + +Some of these features will eventually be implemented. However, you can implement them yourself if they are important for you. If you want, you can [contribute](Contribution/Index.md) to the framework, it is appreciated. \ No newline at end of file diff --git a/docs/en/Audit-Logging.md b/docs/en/Audit-Logging.md index 610efc0451..799b3b76c3 100644 --- a/docs/en/Audit-Logging.md +++ b/docs/en/Audit-Logging.md @@ -39,6 +39,7 @@ Here, a list of the options you can configure: * `IsEnabled` (default: `true`): A root switch to enable or disable the auditing system. Other options is not used if this value is `false`. * `HideErrors` (default: `true`): Audit log system hides and write regular [logs](Logging.md) if any error occurs while saving the audit log objects. If saving the audit logs is critical for your system, set this to `false` to throw exception in case of hiding the errors. * `IsEnabledForAnonymousUsers` (default: `true`): If you want to write audit logs only for the authenticated users, set this to `false`. If you save audit logs for anonymous users, you will see `null` for `UserId` values for these users. +* `AlwaysLogOnException` (default: `true`): If you set to true, it always saves the audit log on an exception/error case without checking other options (except `IsEnabled`, which completely disables the audit logging). * `IsEnabledForGetRequests` (default: `false`): HTTP GET requests should not make any change in the database normally and audit log system doesn't save audit log objects for GET request. Set this to `true` to enable it also for the GET requests. * `ApplicationName`: If multiple applications saving audit logs into a single database, set this property to your application name, so you can distinguish the logs of different applications. * `IgnoredTypes`: A list of `Type`s to be ignored for audit logging. If this is an entity type, changes for this type of entities will not be saved. This list is also used while serializing the action parameters. @@ -369,4 +370,4 @@ You can call other services, they may call others, they may change entities and The Audit Logging Module basically implements the `IAuditingStore` to save the audit log objects to a database. It supports multiple database providers. This module is added to the startup templates by default. -See [the Audit Logging Module document](Modules/Audit-Logging.md) for more about it. \ No newline at end of file +See [the Audit Logging Module document](Modules/Audit-Logging.md) for more about it. diff --git a/docs/en/Background-Jobs.md b/docs/en/Background-Jobs.md index 73815bb229..70f06bbadb 100644 --- a/docs/en/Background-Jobs.md +++ b/docs/en/Background-Jobs.md @@ -108,7 +108,7 @@ Enqueue method gets some optional arguments to control the background job: You may want to disable background job execution for your application. This is generally needed if you want to execute background jobs in another process and disable it for the current process. -Use `BackgroundJobOptions` to configure the job execution: +Use `AbpBackgroundJobOptions` to configure the job execution: ````csharp [DependsOn(typeof(AbpBackgroundJobsModule))] @@ -116,7 +116,7 @@ public class MyModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { - Configure(options => + Configure(options => { options.IsJobExecutionEnabled = false; //Disables job execution }); @@ -140,7 +140,7 @@ ABP framework includes a simple `IBackgroundJobManager` implementation that; ### Configuration -Use `BackgroundJobWorkerOptions` in your [module class](Module-Development-Basics.md) to configure the default background job manager. The example below changes the timeout duration for background jobs: +Use `AbpBackgroundJobWorkerOptions` in your [module class](Module-Development-Basics.md) to configure the default background job manager. The example below changes the timeout duration for background jobs: ````csharp [DependsOn(typeof(AbpBackgroundJobsModule))] @@ -148,7 +148,7 @@ public class MyModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { - Configure(options => + Configure(options => { options.DefaultTimeout = 864000; //10 days (as seconds) }); diff --git a/docs/en/Blog-Posts/2019-02-22/Post.md b/docs/en/Blog-Posts/2019-02-22/Post.md index 35f8219014..b27a50ec05 100644 --- a/docs/en/Blog-Posts/2019-02-22/Post.md +++ b/docs/en/Blog-Posts/2019-02-22/Post.md @@ -1,6 +1,6 @@ # Microservice Demo, Projects Status and Road Map -After [the first announcement](https://abp.io/blog/abp/Abp-vNext-Announcement) on the ABP vNext, we have a lot of improvements on the codebase (1100+ commits on the [GitHub repository](https://github.com/abpframework/abp)). We've created features, samples, documentation and much more. In this post, I want to inform you about some news and the status of the project. +After [the first announcement](https://blog.abp.io/Abp-vNext-Announcement) on the ABP vNext, we have a lot of improvements on the codebase (1100+ commits on the [GitHub repository](https://github.com/abpframework/abp)). We've created features, samples, documentation and much more. In this post, I want to inform you about some news and the status of the project. ## Microservice Demo Solution @@ -38,7 +38,7 @@ First release may not include a SPA template. However, we want to prepare a simp ## Chinese Web Site -There is a big ABP community in China. They have created a Chinese version of the abp.io web site: https://cn.abp.io/ They are keeping it up to date. Thanks to the Chinese developers and especially to [Liming Ma](https://github.com/maliming). +There is a big ABP community in China. They have created a Chinese version of the abp.io web site: https://abp.io/ They are keeping it up to date. Thanks to the Chinese developers and especially to [Liming Ma](https://github.com/maliming). ## NDC {London} 2019 diff --git a/docs/en/Caching.md b/docs/en/Caching.md index 8aa9f00657..bb11b2b45a 100644 --- a/docs/en/Caching.md +++ b/docs/en/Caching.md @@ -2,6 +2,32 @@ ABP framework extends ASP.NET Core's distributed caching system. +## Volo.Abp.Caching Package + +> This package is already installed by default with the startup template. So, most of the time, you don't need to install it manually. + +Volo.Abp.Caching is the core package of the caching system. Install it to your project using the package manager console (PMC): + +``` +Install-Package Volo.Abp.Caching +``` + +Then you can add **AbpCachingModule** dependency to your module: + +```c# +using Volo.Abp.Modularity; +using Volo.Abp.Caching; + +namespace MyCompany.MyProject +{ + [DependsOn(typeof(AbpCachingModule))] + public class MyModule : AbpModule + { + //... + } +} +``` + ## `IDistributedCache` Interface ASP.NET Core defines the `IDistributedCache` interface to get/set cache values. But it has some difficulties: diff --git a/docs/en/Clock.md b/docs/en/Clock.md new file mode 100644 index 0000000000..46ef1235e0 --- /dev/null +++ b/docs/en/Clock.md @@ -0,0 +1,3 @@ +# Clock + +TODO \ No newline at end of file diff --git a/docs/en/Features.md b/docs/en/Features.md new file mode 100644 index 0000000000..4b31ca16e9 --- /dev/null +++ b/docs/en/Features.md @@ -0,0 +1,3 @@ +# Features + +TODO \ No newline at end of file diff --git a/docs/en/Logging.md b/docs/en/Logging.md index 9b9c604bed..7fa45c03b9 100644 --- a/docs/en/Logging.md +++ b/docs/en/Logging.md @@ -2,4 +2,5 @@ ABP Framework doesn't implement any logging infrastructure. It uses the [ASP.NET Core's logging system](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging). -> .NET Core's logging system is actually independent from the ASP.NET Core. It is usable in any type of application. \ No newline at end of file +> .NET Core's logging system is actually independent from the ASP.NET Core. It is usable in any type of application. + diff --git a/docs/en/Modules/Audit-Logging.md b/docs/en/Modules/Audit-Logging.md index 922f99284b..039c61d3a2 100644 --- a/docs/en/Modules/Audit-Logging.md +++ b/docs/en/Modules/Audit-Logging.md @@ -1,6 +1,6 @@ # Audit Logging Module -The Audit Logging Module basically implements the `IAuditingStore` to save the audit log objects to a database. +The Audit Logging Module basically implements the `IAuditingStore` to save the audit log objects to a database. > Audit Logging module is already installed and configured for [the startup templates](../Startup-Templates/Index.md). So, most of the times you don't need to manually add this module to your application. diff --git a/docs/en/Modules/Feature-Management.md b/docs/en/Modules/Feature-Management.md new file mode 100644 index 0000000000..5c41277dd8 --- /dev/null +++ b/docs/en/Modules/Feature-Management.md @@ -0,0 +1,3 @@ +# Feature Management Module + +TODO \ No newline at end of file diff --git a/docs/en/Modules/Index.md b/docs/en/Modules/Index.md index 812f22e8dd..2ffb509667 100644 --- a/docs/en/Modules/Index.md +++ b/docs/en/Modules/Index.md @@ -16,6 +16,7 @@ There are some **free and open source** application modules developed and mainta * **Background Jobs**: Persist background jobs when using the default background job manager. * **Blogging**: Used to create fancy blogs. ABP's [own blog](https://blog.abp.io/) already using this module. * [**Docs**](Docs.md): Used to create technical documentation pages. ABP's [own documentation](https://docs.abp.io) already using this module. +* **Feature Management**: Used to persist and manage the [features](../Features.md). * **Identity**: Manages roles, users and their permissions, based on the Microsoft Identity library. * **IdentityServer**: Integrates to IdentityServer4. * **Permission Management**: Used to persist permissions. diff --git a/docs/en/Repositories.md b/docs/en/Repositories.md index e6b55cb3de..6a60c58278 100644 --- a/docs/en/Repositories.md +++ b/docs/en/Repositories.md @@ -52,7 +52,6 @@ Generic Repositories provides some standard CRUD features out of the box: * Provides `Update` and `Delete` methods to update or delete an entity by entity object or it's id. * Provides `Delete` method to delete multiple entities by a filter. * Implements `IQueryable`, so you can use LINQ and extension methods like `FirstOrDefault`, `Where`, `OrderBy`, `ToList` and so on... -* Have **sync** and **async** versions for all methods. ### Basic Repositories diff --git a/docs/en/docs-nav.json b/docs/en/docs-nav.json index 6657ac629a..cbb4c80e72 100644 --- a/docs/en/docs-nav.json +++ b/docs/en/docs-nav.json @@ -49,6 +49,10 @@ } ] }, + { + "text": "ASP.NET Boilerplate Migration Guide", + "path": "AspNet-Boilerplate-Migration-Guide.md" + }, { "text": "CLI", "path": "CLI.md" @@ -104,6 +108,10 @@ "text": "Caching", "path": "Caching.md" }, + { + "text": "Logging", + "path": "Logging.md" + }, { "text": "Audit Logging", "path": "Audit-Logging.md" @@ -111,6 +119,10 @@ { "text": "Settings", "path": "Settings.md" + }, + { + "text": "Data Filtering", + "path": "Data-Filtering.md" } ] }, diff --git a/docs/zh-Hans/Ambient-Context-Pattern.md b/docs/zh-Hans/Ambient-Context-Pattern.md new file mode 100644 index 0000000000..d00a721ce2 --- /dev/null +++ b/docs/zh-Hans/Ambient-Context-Pattern.md @@ -0,0 +1,3 @@ +## Ambient Context Pattern + +TODO \ No newline at end of file diff --git a/docs/zh-Hans/Audit-Logging.md b/docs/zh-Hans/Audit-Logging.md new file mode 100644 index 0000000000..a028e640b2 --- /dev/null +++ b/docs/zh-Hans/Audit-Logging.md @@ -0,0 +1,375 @@ +# 审计日志 + +[维基百科](https://en.wikipedia.org/wiki/Audit_trail): "*审计跟踪(也称为**审计日志**)是一种安全相关的按时间顺序记录,记录集或记录目的和来源. 这种记录提供了在任何特定时间的操作,过程或事件产生影响活动顺序的文件证据* ". + +ABP框架提供一个可扩展的**审计日志系统**,自动化的根据**约定**记录审计日志,并提供**配置**控制审计日志的级别. + +一个**审计日志对象**(参见下面的审计日志对象部分)通常是针对每个web请求创建和保存的.包括; + +* **请求和响应的细节** (如URL,HTTP方法,浏览器信息,HTTP状态代码...等). +* **执行的动作** (控制器操作和应用服务方法调用及其参数). +* **实体的变化** (在Web请求中). +* **异常信息** (如果在执行请求发生操作). +* **请求时长** (测量应用程序的性能). + +> [启动模板](Startup-Templates/Index.md)已经将审计日志系统配置为适用于大多数应用程序. 本文档介绍了对审计日志系统更精细的控制. + +## 数据库提供程序支持 + +* [Entity Framework Core](Entity-Framework-Core.md)提供程序完全支持. +* [MongoDB](MongoDB.md)提供程序不支持实体更改审计记录. 其他功能按预期工作. + +## UseAuditing() + +`UseAuditing()` 中间件应该被添加到ASP.NET Core请求管道,用于创建和保存审计日志. 如果你使用[启动模板](Startup-Templates/Index.md)创建的应用程序,它已经默认添加. + +## AbpAuditingOptions + +`AbpAuditingOptions` 是配置审计日志系统的主要[options对象](Options.md). 你可以在[模块](Module-Development-Basics.md)的 `ConfigureServices` 方法中进行配置: + +````csharp +Configure(options => +{ + options.IsEnabled = false; //Disables the auditing system +}); +```` + +这里是你可以配置的选项列表: + +* `IsEnabled` (默认值: `true`): 启用或禁用审计系统的总开关. 如果值为 `false`,则不使用其他选项. +* `HideErrors` (默认值: `true`): 在保存审计日志对象时如果发生任何错误,审计日志系统会将错误隐藏并写入常规[日志](Logging.md). 如果保存审计日志对系统非常重要那么将其设置为 `false` 以便在隐藏错误时抛出异常. +* `IsEnabledForAnonymousUsers` (默认值: `true`): 如果只想为经过身份验证的用户记录审计日志,请设置为 `false`.如果为匿名用户保存审计日志,你将看到这些用户的 `UserId` 值为 `null`. +* `AlwaysLogOnException`(默认值: `true`): 如果设置为 `true`,将始终在异常/错误情况下保存审计日志,不检查其他选项(`IsEnabled` 除外,它完全禁用了审计日志). +* `IsEnabledForGetRequests` (默认值: `false`): HTTP GET请求通常不应该在数据库进行任何更改,审计日志系统不会为GET请求保存审计日志对象. 将此值设置为 `true` 可为GET请求启用审计日志系统. +* `ApplicationName`: 如果有多个应用程序保存审计日志到单一的数据库,使用此属性设置为你的应用程序名称区分不同的应用程序日志. +* `IgnoredTypes`: 审计日志系统忽略的 `Type` 列表. 如果它是实体类型,则不会保存此类型实体的更改. 在序列化操作参数时也使用此列表. +* `EntityHistorySelectors`:选择器列表,用于确定是否选择了用于保存实体更改的实体类型. 有关详细信息请参阅下面的部分. +* `Contributors`: `AuditLogContributor` 实现的列表. 贡献者是扩展审计日志系统的一种方式. 有关详细信息请参阅下面的"审计日志贡献者"部分. + +### 实体历史选择器 + +保存您的所有实体的所有变化将需要大量的数据库空间. 出于这个原因**审计日志系统不保存为实体的任何改变,除非你明确地对其进行配置**. + +要保存的所有实体的所有更改,只需使用 `AddAllEntities()` 扩展方法. + +````csharp +Configure(options => +{ + options.EntityHistorySelectors.AddAllEntities(); +}); +```` + +`options.EntityHistorySelectors` 实际上是一个类型谓词的列表,你可以写一个lambda表达式定义过滤器. + +下面的示例中与使用 `AddAllEntities()` 扩展方法效果相同: + +````csharp +Configure(options => +{ + options.EntityHistorySelectors.Add( + new NamedTypeSelector( + "MySelectorName", + type => + { + if (typeof(IEntity).IsAssignableFrom(type)) + { + return true; + } + else + { + return false; + } + } + ) + ); +}); +```` + +条件 `typeof(IEntity).IsAssignableFrom(type)` 对于任何实现 `IEntity` 接口的类(从技术上来这些都是你应用程序中的实体) 结果都为 `true` . 你可以根据自己的逻辑编写条件并返回 `true` 或 `false`. + +`options.EntityHistorySelectors` 是一种灵活动态的选择实体进行审计日志记录的方法. 另一种方法是为每个实体使用 `Audited` 和 `DisableAuditing` attribute. + +## 启用/禁用审计日志服务 + +### 启用/禁用 Controllers & Actions + +默认所有的控制器动作都会被记录下来(有关GET请求,请参阅上面的 `IsEnabledForGetRequests` ). + +你可以使用 `[DisableAuditing]` 来禁用特定的控制器: + +````csharp +[DisableAuditing] +public class HomeController : AbpController +{ + //... +} +```` + +使用 `[DisableAuditing]` 在action级别控制: + +````csharp +public class HomeController : AbpController +{ + [DisableAuditing] + public async Task Home() + { + //... + } + + public async Task OtherActionLogged() + { + //... + } +} +```` + +### 启用/禁用 应用服务&方法 + +[应用服务](Application-Services.md)也默认包含在审计日志中. 你可在服务或方法级别使用 `[DisableAuditing]`. + +#### 启用/禁用 其他服务 + +可以为任何类型的类(注册到[依赖注入](Dependency-Injection.md)并从依赖注入解析)启用审计日志,默认情况下仅对控制器和应用程序服务启用. + +对于任何需要被审计记录的类或方法都可以使用 `[Audited]` 和`IAuditingEnabled`.此外,您的类可以(直接或固有的)实现 `IAuditingEnabled` 接口以认启用该类的审计日志记录. + +### 启用/禁用 实体 & 属性 + +以下情况下实体在实体更改审计日志记录中忽略实体; + +* 如果将实体类型添加到 `AbpAuditingOptions.IgnoredTypes`(如前所述),它在审计日志系统中被完全忽略. +* 如果对象不是[实体](Entities.md)(没有直接或固有的实现 `IEntity` - 所有实体默认实现这个接口). +* 如果实体访问级别不是public的. + +你可以使用 `Audited` 来启用实体更改审计日志: + +````csharp +[Audited] +public class MyEntity : Entity +{ + //... +} +```` + +或者禁用实体: + +````csharp +[DisableAuditing] +public class MyEntity : Entity +{ + //... +} +```` + +只有前面提到的 `AbpAuditingOptions.EntityHistorySelector` 选择实体时才有必要禁用审计日志记录. + +你可以仅禁用实体的某些属性的审计,以审计日志记录进行精细控制: + +````csharp +[Audited] +public class MyUser : Entity +{ + public string Name { get; set; } + + public string Email { get; set; } + + [DisableAuditing] //Ignore the Passoword on audit logging + public string Password { get; set; } +} +```` + +审计日志系统保存 `MyUser` 实体的更改,出于安全的目的忽略 `Password` 属性. + +在某些情况下你可能要保存一些属性,但忽略所有其他属性. 为忽略的属性编写 `[DisableAuditing]` 将很乏味. 这种情况下将 `[Audited]` 用于所需的属性,使用 `[DisableAuditing]` 属性标记该实体: + +````csharp +[DisableAuditing] +public class MyUser : Entity +{ + [Audited] //Only log the Name change + public string Name { get; set; } + + public string Email { get; set; } + + public string Password { get; set; } +} +```` + +## IAuditingStore + +`IAuditingStore` 是一个接口,用于保存ABP框架的审计日志对象(下面说明). 如果需要将审计日志对象保存到自定义数据存储中,可以在自己的应用程序中实现 `IAuditingStore` 并在[依赖注入系统](Dependency-Injection.md)替换. + +如果没有注册审计存储,则使用 `SimpleLogAuditingStore`. 它只是将审计对象写入标准[日志系统](Logging.md). + +[审计日志模块](Modules/Audit-Logging.md)已在[启动模板](Startup-Templates/Index.md)中配置,它将审计日志对象保存到数据库中(支持多个数据库提供程序). 所以大多数时候你并不需要关心 `IAuditingStore` 是如何实现和使用的. + +## 审计日志对象 + +默认为每个**web请求**创建一个**审计日志对象**,审计日志对象可以由以下关系图表示: + +![**auditlog-object-diagram**](images/auditlog-object-diagram.png) + +* **AuditLogInfo**: 具有以下属性: + * `ApplicationName`: 当你保存不同的应用审计日志到同一个数据库,这个属性用来区分应用程序. + * `UserId`:当前用户的Id,用户未登录为 `null`. + * `UserName`:当前用户的用户名,如果用户已经登录(这里的值不依赖于标识模块/系统进行查找). + * `TenantId`: 当前租户的Id,对于多租户应用. + * `TenantName`: 当前租户的名称,对于多租户应用. + * `ExecutionTime`: 审计日志对象创建的时间. + * `ExecutionDuration`: 请求的总执行时间,以毫秒为单位. 可以用来观察应用程序的性能. + * `ClientId`: 当前客户端的Id,如果客户端已经通过认证.客户端通常是使用HTTP API的第三方应用程序. + * `ClientName`: 当前客户端的名称,如果有的话. + * `ClientIpAddress`: 客户端/用户设备的IP地址. + * `CorrelationId`: 当前[相关Id](CorrelationId.md). 相关Id用于在单个逻辑操作中关联由不同应用程序(或微服务)写入的审计日志. + * `BrowserInfo`: 当前用户的浏览器名称/版本信息,如果有的话. + * `HttpMethod`: 当前HTTP请求的方法(GET,POST,PUT,DELETE ...等). + * `HttpStatusCode`: HTTP响应状态码. + * `Url`: 请求的URL. +* **AuditLogActionInfo**: 一个 审计日志动作通常是web请求期间控制器动作或[应用服务](Application-Services.md)方法调用. 一个审计日志可以包含多个动作. 动作对象具有以下属性: + * `ServiceName`:执行的控制器/服务的名称. + * `MethodName`:控制器/服务执行的方法的名称. + * `Parameters`:传递给方法的参数的JSON格文本. + * `ExecutionTime`: 执行的时间. + * `ExecutionDuration`: 方法执行时长,以毫秒为单位. 可以用来观察方法的性能. +* **EntityChangeInfo**: 表示一个实体在Web请求中的变更. 审计日志可以包含0个或多个实体的变更. 实体变更具有以下属性: + * `ChangeTime`: 当实体被改变的时间. + * `ChangeType`:具有以下字段的枚举: `Created`(0), `Updated`(1)和 `Deleted`(2). + * `EntityId`: 更改实体的Id. + * `EntityTenantId`:实体所属的租户Id. + * `EntityTypeFullName`: 实体的类型(类)的完整命名空间名称(例如Book实体的*Acme.BookStore.Book*. +* **EntityPropertyChangeInfo**: 表示一个实体的属性的更改.一个实体的更改信息(上面已说明)可含有具有以下属性的一个或多个属性的更改: + * `NewValue`: 属性的新值. 如果实体已被删除为 `null`. + * `OriginalValue`:变更前旧/初始值. 如果实体是新创建为 `null`. + * `PropertyName`: 实体类的属性名称. + * `PropertyTypeFullName`:属性类型的完整命名空间名称. +* **Exception**: 审计日志对象可能包含零个或多个异常. 可以得到失败请求的异常信息. +* **Comment**:用于将自定义消息添加到审计日志条目的任意字符串值. 审计日志对象可能包含零个或多个注释. + +除了上面说明的标准属性之外,`AuditLogInfo`, `AuditLogActionInfo` 和 `EntityChangeInfo` 对象还实现了`IHasExtraProperties` 接口,你可以向这些对象添加自定义属性. + +## 审计日志贡献者 + +你可以创建类继承 `AuditLogContributor`类 来扩展审计系统,该类定义了 `PreContribute` 和 `PostContribute` 方法. + +唯一预构建的贡献者是 `AspNetCoreAuditLogContributor` 类,它设置HTTP请求的相关属性. + +贡献者可以设置 `AuditLogInfo` 类的属性和集合来添加更多信息. + +例: + +````csharp +public class MyAuditLogContributor : AuditLogContributor +{ + public override void PreContribute(AuditLogContributionContext context) + { + var currentUser = context.ServiceProvider.GetRequiredService(); + context.AuditInfo.SetProperty( + "MyCustomClaimValue", + currentUser.FindClaimValue("MyCustomClaim") + ); + } + + public override void PostContribute(AuditLogContributionContext context) + { + context.AuditInfo.Comments.Add("Some comment..."); + } +} +```` + +* `context.ServiceProvider` 可以从[依赖注入系统](Dependency-Injection.md)中解析服务. +* `context.AuditInfo` 可以用来访问当前审计日志的对象并进行操作. + +创建贡献者后,需要将其添加到 `AbpAuditingOptions.Contributors` 列表中: + +````csharp +Configure(options => +{ + options.Contributors.Add(new MyAuditLogContributor()); +}); +```` + +## IAuditLogScope & IAuditingManager + +本节介绍用于高级用例的 `IAuditLogScope` 和 `IAuditingManager` 服务. + +**审计日志范围**是**构建**和**保存**审计日志对象的[环境范围](Ambient-Context-Pattern.md)(前面解释过). 默认审计日志中间件会为Web请求创建审计日志范围(请参阅上面的 `UseAuditing()` 部分). + +### 获取当前审计日志范围 + +上面提到,审计日志贡献者是操作审计日志对象的全局方法. 你可从服务中获得值. + +如果需要在应用程序的任意位置上操作审计日志对象,可以访问当前审计日志范围并获取当前审计日志对象(与范围的管理方式无关). +例: + +````csharp +public class MyService : ITransientDependency +{ + private readonly IAuditingManager _auditingManager; + + public MyService(IAuditingManager auditingManager) + { + _auditingManager = auditingManager; + } + + public async Task DoItAsync() + { + var currentAuditLogScope = _auditingManager.Current; + if (currentAuditLogScope != null) + { + currentAuditLogScope.Log.Comments.Add( + "Executed the MyService.DoItAsync method :)" + ); + + currentAuditLogScope.Log.SetProperty("MyCustomProperty", 42); + } + } +} +```` + +总是检查 `_auditingManager.Current` 是否为空,因为它是在外部范围中控制的,在调用方法之前你不知道是否创建了审计日志范围. + +### 手动创建审计日志范围 + +你很少需要手动创建审计日志的范围,但如果你需要,可以使用 `IAuditingManager` 创建审计日志的范围. +例: + +````csharp +public class MyService : ITransientDependency +{ + private readonly IAuditingManager _auditingManager; + + public MyService(IAuditingManager auditingManager) + { + _auditingManager = auditingManager; + } + + public async Task DoItAsync() + { + using (var auditingScope = _auditingManager.BeginScope()) + { + try + { + //Call other services... + } + catch (Exception ex) + { + //Add exceptions + _auditingManager.Current.Log.Exceptions.Add(ex); + } + finally + { + //Always save the log + await auditingScope.SaveAsync(); + } + } + } +} +```` + +您可以调用其他服务,它们可能调用其他服务,它们可能更改实体,等等. 所有这些交互都保存为finally块中的一个审计日志对象. + +## 审计日志模块 + +审计日志模块基本上实现了 `IAuditingStore`, 将审计日志对象保存到数据库中并支持多个数据库提供程序. 默认此模块已添加到启动模板中. + +参见[审计日志模块文档](Modules/Audit-Logging.md)了解更多. \ No newline at end of file diff --git a/docs/zh-Hans/Background-Jobs-Hangfire.md b/docs/zh-Hans/Background-Jobs-Hangfire.md index 5ef9aad32d..d35d8482ca 100644 --- a/docs/zh-Hans/Background-Jobs-Hangfire.md +++ b/docs/zh-Hans/Background-Jobs-Hangfire.md @@ -1,3 +1,43 @@ -# Hangfire Background Job Manager +# Hangfire后台作业管理 -待添加 \ No newline at end of file +[Hangfire](https://www.hangfire.io/)是一个高级的后台作业管理. 你可以用ABP框架集成Hangfire代替[默认后台作业管理](Background-Jobs.md). 通过这种方式你可以使用相同的后台作业API,将你的代码独立于Hangfire. 如果你喜欢也可以直接使用Hangfire的API. + +> 参阅[后台作业文档](Background-Jobs.md),学习如何使用后台作业系统. 本文只介绍了如何安装和配置Hangfire集成. + +## 安装 + +建议使用[ABP CLI](CLI.md)安装包. + +### 使用ABP CLI + +在项目的文件夹(.csproj文件)中打开命令行窗口输入以下命令: + +````bash +abp add-package Volo.Abp.BackgroundJobs.HangFire +```` + +### 手动安装 + +如果你想手动安装; + +1. 添加 [Volo.Abp.BackgroundJobs.HangFire](https://www.nuget.org/packages/Volo.Abp.BackgroundJobs.HangFire) NuGet包添加到你的项目: + + ```` + Install-Package Volo.Abp.BackgroundJobs.HangFire + ```` + +2. 添加 `AbpBackgroundJobsHangfireModule` 到你的模块的依赖列表: + +````csharp +[DependsOn( + //...other dependencies + typeof(AbpBackgroundJobsHangfireModule) //Add the new module dependency + )] +public class YourModule : AbpModule +{ +} +```` + +## 配置 + +TODO... \ No newline at end of file diff --git a/docs/zh-Hans/Background-Jobs.md b/docs/zh-Hans/Background-Jobs.md index 30b6f0f1ad..7c2a694005 100644 --- a/docs/zh-Hans/Background-Jobs.md +++ b/docs/zh-Hans/Background-Jobs.md @@ -110,7 +110,7 @@ Enqueue方法接收一些可选参数用于控制后台作业: 你可能希望在你的应用程序中禁用后台作业执行. 如果你希望在另一个进程中执行后台作业并在当前进程中禁用它,通常可以使用以下命令. -使用 `BackgroundJobOptions` 配置作业执行: +使用 `AbpBackgroundJobOptions` 配置作业执行: ````csharp [DependsOn(typeof(AbpBackgroundJobsModule))] @@ -118,7 +118,7 @@ public class MyModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { - Configure(options => + Configure(options => { options.IsJobExecutionEnabled = false; //禁用作业执行 }); @@ -142,7 +142,7 @@ ABP framework 包含一个简单的 `IBackgroundJobManager` 实现; ### 配置 -在你的[模块类](Module-Development-Basics.md)中使用 `BackgroundJobWorkerOptions` 配置默认作业管理器. +在你的[模块类](Module-Development-Basics.md)中使用 `AbpBackgroundJobWorkerOptions` 配置默认作业管理器. 示例中更改后台作业的的超时时间: ````csharp @@ -151,7 +151,7 @@ public class MyModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { - Configure(options => + Configure(options => { options.DefaultTimeout = 864000; //10 days (as seconds) }); diff --git a/docs/zh-Hans/Blog-Posts/2019-02-22/Post.md b/docs/zh-Hans/Blog-Posts/2019-02-22/Post.md index 69a8603baf..30a5d691e9 100644 --- a/docs/zh-Hans/Blog-Posts/2019-02-22/Post.md +++ b/docs/zh-Hans/Blog-Posts/2019-02-22/Post.md @@ -1,12 +1,12 @@ # 微服务演示,项目状态和路线图 -在ABP vNext上的[第一个公告](https://cn.abp.io/blog/abp/Abp-vNext-Announcement)之后,我们对代码库进行了很多改进([GitHub存储库](https://github.com/abpframework/abp)上的1100多次提交).我们已经创建了功能,示例,文档等等.在这篇文章中,我想告诉你一些新闻和项目的状态. +在ABP vNext上的[第一个公告](https://abp.io/blog/abp/Abp-vNext-Announcement)之后,我们对代码库进行了很多改进([GitHub存储库](https://github.com/abpframework/abp)上的1100多次提交).我们已经创建了功能,示例,文档等等.在这篇文章中,我想告诉你一些新闻和项目的状态. ## 微服务演示解决方案 -ABP框架的主要目标之一是提供[创建微服务解决方案的便利基础设施](https://cn.abp.io/documents/abp/latest/Microservice-Architecture). +ABP框架的主要目标之一是提供[创建微服务解决方案的便利基础设施](https://abp.io/documents/abp/latest/Microservice-Architecture). -我们一直在努力开发微服务解决方案演示.初始版本已完成并[文档化](https://cn.abp.io/documents/abp/latest/Samples/Microservice-Demo).该示例解决方案旨在演示一个简单而完整的微服务解决方案; +我们一直在努力开发微服务解决方案演示.初始版本已完成并[文档化](https://abp.io/documents/abp/latest/Samples/Microservice-Demo).该示例解决方案旨在演示一个简单而完整的微服务解决方案; - 具有多个独立的,可自我部署的**微服务**. - 多个**Web应用程序**,每个都使用不同的API网关. @@ -20,7 +20,7 @@ ABP框架的主要目标之一是提供[创建微服务解决方案的便利基 - 使用[Docker](https://www.docker.com/)和[Kubernates](https://kubernetes.io/)**部署**并运行所有服务和应用程序. - 使用[Elasticsearch](https://www.elastic.co/products/elasticsearch)和[Kibana](https://www.elastic.co/products/kibana)存储和可视化日志(使用[Serilog](https://serilog.net/)编写). -有关解决方案的详细说明,请参阅[其文档](https://cn.abp.io/documents/abp/latest/Samples/Microservice-Demo). +有关解决方案的详细说明,请参阅[其文档](https://abp.io/documents/abp/latest/Samples/Microservice-Demo). ## 改进/功能 @@ -32,13 +32,13 @@ ABP框架的主要目标之一是提供[创建微服务解决方案的便利基 根据我们的估计,我们计划在2019年第二季度(可能在五月或六月)发布v1.0.所以,不用等待太长时间了.我们也对第一个稳定版本感到非常兴奋. -我们还将完善[文档](https://cn.abp.io/documents/abp/latest),因为它现在还远未完成. +我们还将完善[文档](https://abp.io/documents/abp/latest),因为它现在还远未完成. 第一个版本可能不包含SPA模板.但是,如果可能的话,我们想要准备一个简单些的.SPA框架还没有确定下来.备选有:**Angular,React和Blazor**.请将您的想法写为对此帖的评论. ## 中文网 -中国有一个大型的ABP社区.他们创建了一个中文版的abp.io网站:https://cn.abp.io/. 他们一直在保持更新.感谢中国的开发人员,特别是[Liming Ma](https://github.com/maliming). +中国有一个大型的ABP社区.他们创建了一个中文版的abp.io网站:https://abp.io/. 他们一直在保持更新.感谢中国的开发人员,特别是[Liming Ma](https://github.com/maliming). ## NDC {London} 2019 diff --git a/docs/zh-Hans/Caching.md b/docs/zh-Hans/Caching.md index 7379104f51..0557ddcb4d 100644 --- a/docs/zh-Hans/Caching.md +++ b/docs/zh-Hans/Caching.md @@ -2,6 +2,32 @@ ABP框架扩展了ASP.NET Core的分布式缓存系统. +## Volo.Abp.Caching Package + +> 默认情况下启动模板已经安装了这个包,所以大部分情况下你不需要手动安装. + +Volo.Abp.Caching是缓存系统的核心包.使用包管理控制台(PMC)安装到项目: + +``` +Install-Package Volo.Abp.Caching +``` + +然后将 **AbpCachingModule** 依赖添加到你的模块: + +```c# +using Volo.Abp.Modularity; +using Volo.Abp.Caching; + +namespace MyCompany.MyProject +{ + [DependsOn(typeof(AbpCachingModule))] + public class MyModule : AbpModule + { + //... + } +} +``` + ## `IDistributedCache` 接口 ASP.NET Core 定义了 `IDistributedCache` 接口用于 get/set 缓存值 . 但是会有以下问题: diff --git a/docs/zh-Hans/Connection-Strings.md b/docs/zh-Hans/Connection-Strings.md index 2df4137b2b..562ae700ce 100644 --- a/docs/zh-Hans/Connection-Strings.md +++ b/docs/zh-Hans/Connection-Strings.md @@ -35,6 +35,22 @@ ABP框架的设计是[模块化](Module-Development-Basics.md), [微服务兼容 [预构建的应用程序模块](Modules/Index.md) 为连接字符串名称定义常量. 例如IdentityServer模块在 `AbpIdentityServerDbProperties` 类(位于 `Volo.Abp.IdentityServer` 命名空间)定义了 `ConnectionStringName` 常量 . 其他的模块类似的定义常量,你可以查看连接字符串的名称. +### AbpDbConnectionOptions + +ABP实际上使用 `AbpDbConnectionOptions` 获取连接字符串. 如果如上所述设置了连接字符串, `AbpDbConnectionOptions` 会被自动填充. 但是你也可以使用[选项模式](Options.md)设置或覆盖连接字符串. 你可以在[模块](Module-Development-Basics.md)的 `ConfigureServices` 方法配置`AbpDbConnectionOptions`). +如下所示: + +````csharp +public override void ConfigureServices(ServiceConfigurationContext context) +{ + Configure(options => + { + options.ConnectionStrings.Default = "..."; + options.ConnectionStrings["AbpPermissionManagement"] = "..."; + }); +} +```` + ## 设置连接字符串名称 模块通常使用 `ConnectionStringName` attribute 为 `DbContext` 类关联一个唯一的连接字符串名称. 示例: diff --git a/docs/zh-Hans/Contribution/Localization-Text-Files.md b/docs/zh-Hans/Contribution/Localization-Text-Files.md index 36bae2890a..8055d9cae2 100644 --- a/docs/zh-Hans/Contribution/Localization-Text-Files.md +++ b/docs/zh-Hans/Contribution/Localization-Text-Files.md @@ -3,7 +3,7 @@ 这是一个来自框架的本地化文本文件列表, 任何人都可以做出贡献. 我们会将此列表保持最新: * https://github.com/abpframework/abp/tree/master/framework/src/Volo.Abp.AspNetCore.Mvc.UI.MultiTenancy/Volo/Abp/AspNetCore/Mvc/UI/MultiTenancy/Localization/en.json -* https://github.com/abpframework/abp/tree/master/framework/src/Volo.Abp.Localization/Volo/Abp/Localization/Resources/AbpValidation/en.json +* https://github.com/abpframework/abp/blob/master/framework/src/Volo.Abp.Validation/Volo/Abp/Validation/Localization/en.json * https://github.com/abpframework/abp/tree/master/framework/src/Volo.Abp.UI.Navigation/Volo/Abp/Ui/Navigation/Localization/Resource/en.json * https://github.com/abpframework/abp/tree/master/framework/src/Volo.Abp.UI/Localization/Resources/AbpUi/en.json * https://github.com/abpframework/abp/tree/master/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Localization/Resource/en.json @@ -12,29 +12,20 @@ * https://github.com/abpframework/abp/tree/master/framework/test/Volo.Abp.Localization.Tests/Volo/Abp/Localization/TestResources/Base/Validation/en.json * https://github.com/abpframework/abp/tree/master/framework/test/Volo.Abp.Localization.Tests/Volo/Abp/Localization/TestResources/Source/en.json * https://github.com/abpframework/abp/tree/master/framework/test/Volo.Abp.Localization.Tests/Volo/Abp/Localization/TestResources/SourceExt/en.json -* https://github.com/abpframework/abp/tree/master/modules/account/src/Volo.Abp.Account.Web/Localization/Resources/AbpAccount/Web/en.json +* https://github.com/abpframework/abp/blob/master/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/en.json * https://github.com/abpframework/abp/tree/master/modules/blogging/src/Volo.Blogging.Application.Contracts/Volo/Blogging/Localization/Resources/Blogging/ApplicationContracts/en.json -* https://github.com/abpframework/abp/tree/master/modules/blogging/src/Volo.Blogging.Web/Localization/Resources/Blogging/Web/en.json +* https://github.com/abpframework/abp/tree/master/modules/blogging/src/Volo.Blogging.Domain.Shared/Volo/Blogging/Localization/Resources/en.json * https://github.com/abpframework/abp/tree/master/modules/docs/app/VoloDocs.Web/Localization/Resources/VoloDocs/Web/en.json * https://github.com/abpframework/abp/tree/master/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/en.json -* https://github.com/abpframework/abp/tree/master/modules/docs/src/Volo.Docs.Admin.Web/Localization/Resources/Docs/Web/en.json * https://github.com/abpframework/abp/tree/master/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/en.json -* https://github.com/abpframework/abp/tree/master/modules/feature-management/src/Volo.Abp.FeatureManagement.Application.Contracts/Volo/Abp/FeatureManagement/Localization/ApplicationContracts/en.json -* https://github.com/abpframework/abp/tree/master/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain/Volo/Abp/FeatureManagement/Localization/Domain/en.json -* https://github.com/abpframework/abp/tree/master/modules/feature-management/src/Volo.Abp.FeatureManagement.Web/Localization/Resources/FeatureManagement/en.json -* https://github.com/abpframework/abp/tree/master/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/Localization/ApplicationContracts/en.json -* https://github.com/abpframework/abp/tree/master/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/Localization/Domain/en.json -* https://github.com/abpframework/abp/tree/master/modules/identity/src/Volo.Abp.Identity.Web/Localization/Resources/AbpIdentity/en.json -* https://github.com/abpframework/abp/tree/master/modules/permission-management/src/Volo.Abp.PermissionManagement.Web/Localization/Resources/AbpPermissionManagement/en.json -* https://github.com/abpframework/abp/tree/master/modules/setting-management/src/Volo.Abp.SettingManagement.Web/Localization/Resources/AbpSettingManagement/en.json -* https://github.com/abpframework/abp/tree/master/modules/tenant-management/src/Volo.Abp.TenantManagement.Application.Contracts/Volo/Abp/TenantManagement/Localization/ApplicationContracts/en.json -* https://github.com/abpframework/abp/tree/master/modules/tenant-management/src/Volo.Abp.TenantManagement.Web/Localization/Resources/AbpTenantManagement/Web/en.json +* https://github.com/abpframework/abp/tree/master/modules/feature-management/src/Volo.Abp.FeatureManagement.Domain.Shared/Volo/Abp/FeatureManagement/Localization/Domain/en.json +* https://github.com/abpframework/abp/tree/master/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/Localization/en.json +* https://github.com/abpframework/abp/tree/master/modules/permission-management/src/Volo.Abp.PermissionManagement.Domain.Shared/Volo/Abp/PermissionManagement/Localization/Domain/en.json +* https://github.com/abpframework/abp/tree/master/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/en.json +* https://github.com/abpframework/abp/tree/master/modules/tenant-management/src/Volo.Abp.TenantManagement.Domain.Shared/Volo/Abp/TenantManagement/Localization/Resources/en.json * https://github.com/abpframework/abp/tree/master/samples/BookStore/src/Acme.BookStore.Domain.Shared/Localization/BookStore/en.json -* https://github.com/abpframework/abp/tree/master/samples/DashboardDemo/src/DashboardDemo.Domain/Localization/DashboardDemo/en.json +* https://github.com/abpframework/abp/tree/master/samples/DashboardDemo/src/DashboardDemo.Domain.Shared/Localization/DashboardDemo/en.json * https://github.com/abpframework/abp/tree/master/samples/MicroserviceDemo/modules/product/src/ProductManagement.Application.Contracts/ProductManagement/Localization/ApplicationContracts/en.json * https://github.com/abpframework/abp/tree/master/samples/MicroserviceDemo/modules/product/src/ProductManagement.Domain/ProductManagement/Localization/Domain/en.json * https://github.com/abpframework/abp/tree/master/samples/MicroserviceDemo/modules/product/src/ProductManagement.Web/Localization/Resources/ProductManagement/en.json -* https://github.com/abpframework/abp/tree/master/templates/mvc-module/src/MyCompanyName.MyProjectName.Application.Contracts/Localization/MyProjectName/ApplicationContracts/en.json -* https://github.com/abpframework/abp/tree/master/templates/mvc-module/src/MyCompanyName.MyProjectName.Domain.Shared/Localization/MyProjectName/DomainShared/en.json -* https://github.com/abpframework/abp/tree/master/templates/mvc-module/src/MyCompanyName.MyProjectName.Web/Localization/MyProjectName/Web/en.json -* https://github.com/abpframework/abp/tree/master/templates/mvc/src/MyCompanyName.MyProjectName.Domain.Shared/Localization/MyProjectName/en.json +* https://github.com/abpframework/abp/tree/master/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Domain.Shared/Localization/MyProjectName/en.json \ No newline at end of file diff --git a/docs/zh-Hans/Dependency-Injection.md b/docs/zh-Hans/Dependency-Injection.md index 381b77ec35..2264a12930 100644 --- a/docs/zh-Hans/Dependency-Injection.md +++ b/docs/zh-Hans/Dependency-Injection.md @@ -319,4 +319,4 @@ public class AppModule : AbpModule ### 请参阅 -* [ASP.NET Core依赖注入最佳实践,提示和技巧](https://cn.abp.io/blog/Abp/asp-net-core-dependency-injection-best-practices-tips-tricks) +* [ASP.NET Core依赖注入最佳实践,提示和技巧](https://blog.abp.io/asp-net-core-dependency-injection-best-practices-tips-tricks) diff --git a/docs/zh-Hans/Entity-Framework-Core.md b/docs/zh-Hans/Entity-Framework-Core.md index 328a4b74cc..b70630e38f 100644 --- a/docs/zh-Hans/Entity-Framework-Core.md +++ b/docs/zh-Hans/Entity-Framework-Core.md @@ -181,7 +181,7 @@ public interface IBookRepository : IRepository } ```` -你通常希望从IRepository派生以继承标准存储库方法. 然而,你没有必要这样做. 仓储接口在分层应用程序的领域层中定义,它在数据访问/基础设施层([启动模板](https://cn.abp.io/Templates)中的`EntityFrameworkCore`项目)中实现 +你通常希望从IRepository派生以继承标准存储库方法. 然而,你没有必要这样做. 仓储接口在分层应用程序的领域层中定义,它在数据访问/基础设施层([启动模板](https://abp.io/Templates)中的`EntityFrameworkCore`项目)中实现 IBookRepository接口的实现示例: diff --git a/docs/zh-Hans/Getting-Started-AspNetCore-MVC-Template.md b/docs/zh-Hans/Getting-Started-AspNetCore-MVC-Template.md index 4d6695c79b..d65573d9db 100644 --- a/docs/zh-Hans/Getting-Started-AspNetCore-MVC-Template.md +++ b/docs/zh-Hans/Getting-Started-AspNetCore-MVC-Template.md @@ -2,7 +2,7 @@ ### 创建新项目 -本教程使用 **ABP CLI** 创建一个新项目. 更多选项, 请参阅[入门](https://cn.abp.io/get-started)页面. +本教程使用 **ABP CLI** 创建一个新项目. 更多选项, 请参阅[入门](https://abp.io/get-started)页面. 如果你之前未安装,请使用命令行安装ABP CLI: diff --git a/docs/zh-Hans/Modules/Audit-Logging.md b/docs/zh-Hans/Modules/Audit-Logging.md new file mode 100644 index 0000000000..0748b27160 --- /dev/null +++ b/docs/zh-Hans/Modules/Audit-Logging.md @@ -0,0 +1,7 @@ +# 审计日志模块 + +审计日志模块实现了 `IAuditingStore` 将审计日志对象保存到数据库中. + +> [启动模板](../Startup-Templates/Index.md)已经安装并配置了审计日志模块,所以你不需要手动安装到你的应用程序. + +参阅[审计日志系统](../Audit-Logging.md)文档了解更多关于审计日志的内容. \ No newline at end of file diff --git a/docs/zh-Hans/Modules/Docs.md b/docs/zh-Hans/Modules/Docs.md index cfe287082b..3bd71d554f 100644 --- a/docs/zh-Hans/Modules/Docs.md +++ b/docs/zh-Hans/Modules/Docs.md @@ -14,21 +14,19 @@ ### 版本 -当你使用GitHub存储文档时,文档模块支持多版本. 如果你的文档具有多个版本, UI上有一个组合框,用于切换版本. 如果你选择使用文件系统存储文档, 那么它不支持多版本. +当你使用GitHub存储文档时,文档模块支持多版本. 如果你的文档具有多个版本, UI上有一个组合框,用于切换版本. 如果你选择使用文件系统存储文档, 那么它不支持多版本. -ABP框架的[文档](https://abp.io/documents/)也是使用的此模块. +ABP框架的[文档](docs.abp.io)也是使用的此模块. > 文档模块遵循 [模块化架构最佳实践](../Best-Practices/Module-Architecture.md) 指南. - - ## 安装 ### 1- 下载 -如果你没有现有的ABP项目, 这个步骤向你展示如何在[abp.io](https://cn.abp.io)创建一个新项目并添加文档模块. 如果你本地已经有了一个ABP项目, 那么你可以跳过这一步. +如果你没有现有的ABP项目, 这个步骤向你展示如何在[abp.io](https://abp.io)创建一个新项目并添加文档模块. 如果你本地已经有了一个ABP项目, 那么你可以跳过这一步. -打开 https://cn.abp.io/Templates. 输入项目名称为 `Acme.MyProject`, 选择 `ASP.NET Core Mvc Application` 和选择 `Entity Framework Core` 做为数据库提供者. +打开 https://abp.io/Templates. 输入项目名称为 `Acme.MyProject`, 选择 `ASP.NET Core Mvc Application` 和选择 `Entity Framework Core` 做为数据库提供者. 请注意,本文档包含了 `Entity Framework Core` 提供者 不过你也可以选择 `MongoDB` 做为数据库提供者. @@ -36,7 +34,7 @@ ABP框架的[文档](https://abp.io/documents/)也是使用的此模块. ### 2- 运行这个空项目 -下载项目后, 解压压缩文档并且打开 `Acme.MyProject.sln`. 你可以看到这个解决方案包含了 `Application`, `Domain `, `EntityFrameworkCore` 和 `Web` 项目. 右键选择 `Acme.MyProject.Web` 项目**设置为启动项目**. +下载项目后, 解压压缩文档并且打开 `Acme.MyProject.sln`. 你可以看到这个解决方案包含了 `Application`, `Domain`, `EntityFrameworkCore` 和 `Web` 项目. 右键选择 `Acme.MyProject.Web` 项目**设置为启动项目**. ![创建新项目](../images/docs-module_solution-explorer.png) @@ -67,31 +65,32 @@ ABP框架的[文档](https://abp.io/documents/)也是使用的此模块. ```csharp ``` + * [Volo.Docs.EntityFrameworkCore](https://www.nuget.org/packages/Volo.Docs.EntityFrameworkCore/) 需要安装到 `Acme.MyProject.EntityFrameworkCore` 项目. - - 修改 `Acme.MyProject.EntityFrameworkCore.csproj`文件并且添加以下行. 需要注意它要设置(v0.9.0)为Latest版本. + * 修改 `Acme.MyProject.EntityFrameworkCore.csproj` 文件并且添加以下行. 需要注意它要设置(v0.9.0)为Latest版本. ```csharp ``` + * [Volo.Docs.Application](https://www.nuget.org/packages/Volo.Docs.Application/) 需要安装到 `Acme.MyProject.Application` 项目. - * 修改 `Acme.MyProject.Application.csproj`文件并且添加以下行. 需要注意它要设置(v0.9.0)为Latest版本. + * 修改 `Acme.MyProject.Application.csproj` 文件并且添加以下行. 需要注意它要设置(v0.9.0)为Latest版本. ```csharp ``` -* [Volo.Docs.Web ](https://www.nuget.org/packages/Volo.Docs.Web/) 需要安装到 `Acme.MyProject.Web` 项目. - - 修改 `Acme.MyProject.Web.csproj`文件并且添加以下行. 需要注意它要设置(v0.9.0)为Latest版本. +* [Volo.Docs.Web](https://www.nuget.org/packages/Volo.Docs.Web/) 需要安装到 `Acme.MyProject.Web` 项目. + + * 修改 `Acme.MyProject.Web.csproj` 文件并且添加以下行. 需要注意它要设置(v0.9.0)为Latest版本. ```csharp ``` - - -### 3- 添加模块添加 +### 3- 添加模块依赖 一个ABP模块必须声明 `[DependsOn]` attribute 如果它依赖于另一个模块. 每个模块都必须在相关的项目的`[DependsOn]`Attribute 中添加. @@ -155,7 +154,6 @@ ABP框架的[文档](https://abp.io/documents/)也是使用的此模块. } ``` - * 打开 `MyProjectWebModule.cs`并且添加 `typeof(DocsWebModule)` 如下所示; ```csharp @@ -174,15 +172,13 @@ ABP框架的[文档](https://abp.io/documents/)也是使用的此模块. } ``` - - ### 4- 数据库集成 #### 4.1- Entity Framework 集成 如果你选择了Entity Framework 做为数据库供应者,你需要在DbContext中配置文档模块. 做以下操作; -- 打开 `MyProjectDbContext.cs` 并且添加 `modelBuilder.ConfigureDocs()` 到 `OnModelCreating()` 方法中 +* 打开 `MyProjectDbContext.cs` 并且添加 `modelBuilder.ConfigureDocs()` 到 `OnModelCreating()` 方法中 ```csharp [ConnectionStringName("Default")] @@ -195,7 +191,7 @@ ABP框架的[文档](https://abp.io/documents/)也是使用的此模块. } protected override void OnModelCreating(ModelBuilder modelBuilder) - { + { //... modelBuilder.ConfigureDocs(); } @@ -218,7 +214,6 @@ ABP框架的[文档](https://abp.io/documents/)也是使用的此模块. 最后你可以查看数据库中创建的新表,例如你可以看到 `DocsProjects` 表已经添加到数据库中. - ### 5- 链接文档模块 文档模块的默认路由是; @@ -262,7 +257,7 @@ ABP框架的[文档](https://abp.io/documents/)也是使用的此模块. "texts": { "Menu:Home": "首页", "Welcome": "欢迎", - "LongWelcomeMessage": "欢迎来到该应用程序. 这是一个基于ABP框架的启动项目. 有关更多信息, 请访问 cn.abp.io.", + "LongWelcomeMessage": "欢迎来到该应用程序. 这是一个基于ABP框架的启动项目. 有关更多信息, 请访问 abp.io.", "Menu:Docs": "文档" } } @@ -352,10 +347,10 @@ INSERT [dbo].[DocsProjects] ([Id], [Name], [ShortName], [Format], [DefaultDocume - ExtraProperties: ```json - {"Path":"C:\\Github\\abp\\docs\\zh-Hans"} + {"Path":"C:\\Github\\abp\\docs"} ``` - 请注意 `Path` 必须使用本地docs目录替换. 你可以从https://github.com/abpframework/abp/tree/master/docs/zh-hans获取ABP Framework的文档并且复制到该目录 `C:\\Github\\abp\\docs\\zh-Hans` 使其正常工作. + 请注意 `Path` 必须使用本地docs目录替换. 你可以从https://github.com/abpframework/abp/tree/master/docs获取ABP Framework的文档并且复制到该目录 `C:\\Github\\abp\\docs` 使其正常工作. - MainWebsiteUrl: `/` @@ -364,7 +359,7 @@ INSERT [dbo].[DocsProjects] ([Id], [Name], [ShortName], [Format], [DefaultDocume 对于 `SQL` 数据库,你可以使用下面的 `T-SQL` 命令将指定的示例插入到 `DocsProjects` 表中: ```mssql -INSERT [dbo].[DocsProjects] ([Id], [Name], [ShortName], [Format], [DefaultDocumentName], [NavigationDocumentName], [MinimumVersion], [DocumentStoreType], [ExtraProperties], [MainWebsiteUrl], [LatestVersionBranchName]) VALUES (N'12f21123-e08e-4f15-bedb-ae0b2d939659', N'ABP framework (FileSystem)', N'abp', N'md', N'Index', N'docs-nav.json', NULL, N'FileSystem', N'{"Path":"C:\\Github\\abp\\docs\\zh-Hans"}', N'/', NULL) +INSERT [dbo].[DocsProjects] ([Id], [Name], [ShortName], [Format], [DefaultDocumentName], [NavigationDocumentName], [MinimumVersion], [DocumentStoreType], [ExtraProperties], [MainWebsiteUrl], [LatestVersionBranchName]) VALUES (N'12f21123-e08e-4f15-bedb-ae0b2d939659', N'ABP framework (FileSystem)', N'abp', N'md', N'Index', N'docs-nav.json', NULL, N'FileSystem', N'{"Path":"C:\\Github\\abp\\docs"}', N'/', NULL) ``` 添加上面的一个示例项目后运行该应用程序. 在菜单中你会看到`文档` 链接,点击菜单链接打开文档页面. @@ -408,6 +403,101 @@ public class Person [https://github.com/abpframework/abp/blob/master/docs/zh-Hans/](https://github.com/abpframework/abp/blob/master/docs/zh-Hans/) +#### 有条件的部分功能(使用Scriban) + +文档模块使用[Scriban]()有条件的显示或隐藏文档的某些部分. 使用该功能你需要为每一种语言创建一个JSON文件做为**参数文档**. 它包含所有键值以及它们的显示名称. + +例如 [en/docs-params.json](https://github.com/abpio/abp-commercial-docs/blob/master/en/docs-params.json): + +```json +{ + "parameters": [{ + "name": "UI", + "displayName": "UI", + "values": { + "MVC": "MVC / Razor Pages", + "NG": "Angular" + } + }, + { + "name": "DB", + "displayName": "Database", + "values": { + "EF": "Entity Framework Core", + "Mongo": "MongoDB" + } + }, + { + "name": "Tiered", + "displayName": "Tiered", + "values": { + "No": "Not Tiered", + "Yes": "Tiered" + } + }] +} +``` + +因为并不是项目中的每个文档都有章节或者不需要所有的参数,你必须声明哪些参数将用于对文档进行分段,在文档的任何地方都可以使用JSON块. + +例如 [Getting-Started.md](https://github.com/abpio/abp-commercial-docs/blob/master/en/getting-started.md): + +``` +..... + +​````json +//[doc-params] +{ + "UI": ["MVC","NG"], + "DB": ["EF", "Mongo"], + "Tiered": ["Yes", "No"] +} +​```` + +........ +``` + +这个部分会在渲染时自动删除.前提是这些键值必须与**参数文档**中的键值匹配. + +![Interface](../images/docs-section-ui.png) + +现在你可以使用 **Scriban** 语法在文档中创建章节. + +示例 : + +```` +{{ if UI == "NG" }} + +* `-u` argument specifies the UI framework, `angular` in this case. + +{{ end }} + +{{ if DB == "Mongo" }} + +* `-d` argument specifies the database provider, `mongodb` in this case. + +{{ end }} + +{{ if Tiered == "Yes" }} + +* `--tiered` argument is used to create N-tiered solution where authentication server, UI and API layers are physically separated. + +{{ end }} + +```` + +还可以在文本中使用变量,在其键中添加 **_Value** 后缀: + +```` +This document assumes that you prefer to use **{{ UI_Value }}** as the UI framework and **{{ DB_Value }}** as the database provider. +```` + +如果你想要得到的当前文档的语言或版本,可以使用预定义的 **Document_Language_Code** 和 **DOCUMENT_VERSION** 键(这对于创建重定向到另一个地区中另一个文档系统的链接很有用). + +------ + +**重要提示**: Scriban 的语法是 "{{" and "}}". 如果要在文档(如Angular文档)中使用转义,则必须使用转义块. 参阅 [Scriban文档]( ) 了解更多信息. + ### 8- 创建文档导航 导航文档是文档页面的主菜单. 它位于页面的左侧,是一个`JSON` 文件. 请查看以下示例导航文档以了解结构. @@ -464,4 +554,8 @@ public class Person ![Navigation menu](../images/docs-module_download-sample-navigation-menu.png) -最后,为您的项目添加了一个新的Docs模块, 该模块由GitHub提供. \ No newline at end of file +最后,为您的项目添加了一个新的Docs模块, 该模块由GitHub提供. + +## 下一步 + +文档模块也可以做为独立的应用程序. 查看 [VoloDocs](../Apps/VoloDocs). \ No newline at end of file diff --git a/docs/zh-Hans/Modules/Index.md b/docs/zh-Hans/Modules/Index.md index 8e5edf35b6..9b44967c53 100644 --- a/docs/zh-Hans/Modules/Index.md +++ b/docs/zh-Hans/Modules/Index.md @@ -11,16 +11,20 @@ ABP是一个 **模块化的应用程序框架** 由十多个 **nuget packages** 有一些由ABP社区开发和维护的 **开源免费** 的应用程序模块: -* **Account**: 用于用户登录/注册应用程序. -* **Audit Logging**: 用于将审计日志持久化到数据库. +* **Account**: 提供账户管理UI,并允许用户登录/注册应用程序. +* [**Audit Logging**](Audit-Logging.md): 用于将审计日志持久化到数据库. * **Background Jobs**: 用于在使用默认后台作业管理器时保存后台作业. -* **Blogging**: 用于创建精美的博客. ABP的[博客](https://abp.io/blog/abp/) 就使用了此模块. +* **Blogging**: 用于创建精美的博客. ABP的[博客](https://blog.abp.io/) 就使用了此模块. * [**Docs**](Docs.md): 用于创建技术文档页面. ABP的[文档](https://abp.io/documents/) 就使用了此模块. -* **Identity**: 用于管理角色,用户和他们的权限. +* **Identity**: 基于Microsoft Identity管理角色,用户和他们的权限. * **Identity Server**: 集成了IdentityServer4. * **Permission Management**: 用于保存权限. * **Setting Management**: 用于保存设置. -* **Tenant Management**: 用于管理[多租户](../Multi-Tenancy.md)应用程序的租户. -* **Users**: 用于抽象用户, 因此其他模块可以依赖此模块而不是Identity模块. +* **Tenant Management**: 管理[多租户](../Multi-Tenancy.md)应用程序的租户. +* **Users**: 抽象用户, 因此其他模块可以依赖此模块而不是Identity模块. -模块化文档正在编写中. 请参阅[这个仓库](https://github.com/abpframework/abp/tree/master/modules)获取所有模块的源代码. \ No newline at end of file +模块化文档正在编写中. 请参阅[这个仓库](https://github.com/abpframework/abp/tree/master/modules)获取所有模块的源代码. + +## 商业应用模块 + +[ABP商业](https://commercial.abp.io/)许可证在ABP框架上提供了额外的预构建应用程序模块. 参见ABP商业版提供的[模块列表](https://commercial.abp.io/module). \ No newline at end of file diff --git a/docs/zh-Hans/Modules/Setting-Management.md b/docs/zh-Hans/Modules/Setting-Management.md index 31ea2505ea..fd87dd734c 100644 --- a/docs/zh-Hans/Modules/Setting-Management.md +++ b/docs/zh-Hans/Modules/Setting-Management.md @@ -67,6 +67,8 @@ namespace Demo 你可以从不同的设置值提供程序中(默认,全局,用户,租户...等)中获取或设定设置值. +> 如果只需要读取设置值,建议使用 `ISettingProvider` 而不是`ISettingManager`,因为它实现了缓存并支持所有部署场景. 如果要创建设置管理UI,可以使用ISettingManager. + ### Setting Cache 设置值缓存在 [分布式缓存](../Caching.md) 系统中. 建议始终使用 `ISettingManager` 更改设置值. diff --git a/docs/zh-Hans/Tutorials/AspNetCore-Mvc/Part-I.md b/docs/zh-Hans/Tutorials/AspNetCore-Mvc/Part-I.md index f9314e5030..5394890f8d 100644 --- a/docs/zh-Hans/Tutorials/AspNetCore-Mvc/Part-I.md +++ b/docs/zh-Hans/Tutorials/AspNetCore-Mvc/Part-I.md @@ -50,6 +50,18 @@ namespace Acme.BookStore public DateTime PublishDate { get; set; } public float Price { get; set; } + + protected Book() + { + } + public Book(Guid id, string name, BookType type, DateTime publishDate, float price) + :base(id) + { + Name = name; + Type = type; + PublishDate = publishDate; + Price = price; + } } } ```` @@ -349,7 +361,7 @@ successfully created the book with id: f3f03580-c1aa-d6a9-072d-39e75c69f5c7 ```` * 此代码更改了Razor View Page Model的默认继承,因此它从`BookStorePage`类(而不是`PageModel`)继承.启动模板附带的`BookStorePage`类,提供所有页面使用的一些共享属性/方法. -* 确保`IndexModel`(Index.cshtml.cs)具有`Acme.BookStore.Pages.Books`命名空间,或者在`Index.cshtml`中更新它. +* 确保`IndexModel`(Index.cshtml.cs)具有`Acme.BookStore.Web.Pages.Books`命名空间,或者在`Index.cshtml`中更新它. #### 将Books页面添加到主菜单 @@ -426,7 +438,7 @@ context.Menu.AddItem( ```` * `abp-script` [tag helper](https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro)用于将外部的 **脚本** 添加到页面中.它比标准的`script`标签多了很多额外的功能.它可以处理 **最小化**和 **版本**.查看[捆绑 & 压缩文档](../../AspNetCore/Bundling-Minification.md)获取更多信息. -* `abp-card` 和 `abp-table` 是为Twitter Bootstrap的[card component](http://getbootstrap.com/docs/4.1/components/card/)封装的 **tag helpers**.ABP中有很多tag helpers,可以很方便的使用大多数[bootstrap](https://getbootstrap.com/)组件.你也可以使用原生的HTML标签代替tag helpers.使用tag helper可以通过智能提示和编译时类型检查减少HTML代码并防止错误.查看[tag helpers 文档](../../AspNetCore/Tag-Helpers.md). +* `abp-card` 和 `abp-table` 是为Twitter Bootstrap的[card component](http://getbootstrap.com/docs/4.1/components/card/)封装的 **tag helpers**.ABP中有很多tag helpers,可以很方便的使用大多数[bootstrap](https://getbootstrap.com/)组件.你也可以使用原生的HTML标签代替tag helpers.使用tag helper可以通过智能提示和编译时类型检查减少HTML代码并防止错误.查看[tag helpers 文档](../../AspNetCore/Tag-Helpers/Index.md). * 你可以像上面本地化菜单一样 **本地化** 列名. #### 添加脚本文件 diff --git a/docs/zh-Hans/Tutorials/AspNetCore-Mvc/Part-III.md b/docs/zh-Hans/Tutorials/AspNetCore-Mvc/Part-III.md index 5bbe0e3424..e48cf6b710 100644 --- a/docs/zh-Hans/Tutorials/AspNetCore-Mvc/Part-III.md +++ b/docs/zh-Hans/Tutorials/AspNetCore-Mvc/Part-III.md @@ -56,26 +56,12 @@ namespace Acme.BookStore public async Task SeedAsync(DataSeedContext context) { await _bookRepository.InsertAsync( - new Book - { - Id = _guidGenerator.Create(), - Name = "Test book 1", - Type = BookType.Fantastic, - PublishDate = new DateTime(2015, 05, 24), - Price = 21 - } - ); + new Book(_guidGenerator.Create(), "Test book 1", + BookType.Fantastic, new DateTime(2015, 05, 24), 21)); await _bookRepository.InsertAsync( - new Book - { - Id = _guidGenerator.Create(), - Name = "Test book 2", - Type = BookType.Science, - PublishDate = new DateTime(2014, 02, 11), - Price = 15 - } - ); + new Book(_guidGenerator.Create(), "Test book 2", + BookType.Science, new DateTime(2014, 02, 11), 15)); } } } diff --git a/docs/zh-Hans/docs-nav.json b/docs/zh-Hans/docs-nav.json index 44856b34ed..ad811cc5b3 100644 --- a/docs/zh-Hans/docs-nav.json +++ b/docs/zh-Hans/docs-nav.json @@ -97,8 +97,13 @@ "path": "Caching.md" }, { - "text": "审计" - }, + "text": "日志", + "path": "Logging.md" + }, + { + "text": "审计日志", + "path": "Audit-Logging.md" + }, { "text": "设置管理", "path": "Settings.md" diff --git a/docs/zh-Hans/images/auditlog-object-diagram.png b/docs/zh-Hans/images/auditlog-object-diagram.png new file mode 100644 index 0000000000..a7e86a2bb2 Binary files /dev/null and b/docs/zh-Hans/images/auditlog-object-diagram.png differ diff --git a/docs/zh-Hans/images/docs-section-ui.png b/docs/zh-Hans/images/docs-section-ui.png new file mode 100644 index 0000000000..7856454e5d Binary files /dev/null and b/docs/zh-Hans/images/docs-section-ui.png differ diff --git a/framework/src/Volo.Abp.AspNetCore/Volo/Abp/AspNetCore/Auditing/AbpAuditingMiddleware.cs b/framework/src/Volo.Abp.AspNetCore/Volo/Abp/AspNetCore/Auditing/AbpAuditingMiddleware.cs index 78ae28e63f..f59c5b6b3a 100644 --- a/framework/src/Volo.Abp.AspNetCore/Volo/Abp/AspNetCore/Auditing/AbpAuditingMiddleware.cs +++ b/framework/src/Volo.Abp.AspNetCore/Volo/Abp/AspNetCore/Auditing/AbpAuditingMiddleware.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; @@ -28,38 +29,50 @@ namespace Volo.Abp.AspNetCore.Auditing public async Task InvokeAsync(HttpContext context, RequestDelegate next) { - if (!ShouldWriteAuditLog(context)) - { - await next(context); - return; - } - + bool hasError = false; using (var scope = _auditingManager.BeginScope()) { try { await next(context); + if (_auditingManager.Current.Log.Exceptions.Any()) + { + hasError = true; + } + } + catch (Exception) + { + hasError = true; + throw; } finally { - await scope.SaveAsync(); + if (ShouldWriteAuditLog(context, hasError)) + { + await scope.SaveAsync(); + } } } } - private bool ShouldWriteAuditLog(HttpContext httpContext) + private bool ShouldWriteAuditLog(HttpContext httpContext, bool hasError = false) { if (!Options.IsEnabled) { return false; } + if (Options.AlwaysLogOnException && hasError) + { + return true; + } + if (!Options.IsEnabledForAnonymousUsers && !CurrentUser.IsAuthenticated) { return false; } - if (!Options.IsEnabledForGetRequests && + if (!Options.IsEnabledForGetRequests && string.Equals(httpContext.Request.Method, HttpMethods.Get, StringComparison.OrdinalIgnoreCase)) { return false; diff --git a/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AbpAuditingOptions.cs b/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AbpAuditingOptions.cs index da406fa490..58a0713014 100644 --- a/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AbpAuditingOptions.cs +++ b/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AbpAuditingOptions.cs @@ -31,6 +31,12 @@ namespace Volo.Abp.Auditing /// public bool IsEnabledForAnonymousUsers { get; set; } + /// + /// Audit log on exceptions. + /// Default: true. + /// + public bool AlwaysLogOnException { get; set; } + public List Contributors { get; } public List IgnoredTypes { get; } @@ -48,6 +54,7 @@ namespace Volo.Abp.Auditing IsEnabled = true; IsEnabledForAnonymousUsers = true; HideErrors = true; + AlwaysLogOnException = true; Contributors = new List(); diff --git a/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditingManager.cs b/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditingManager.cs index 070684f48a..2a9dd8bf5a 100644 --- a/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditingManager.cs +++ b/framework/src/Volo.Abp.Auditing/Volo/Abp/Auditing/AuditingManager.cs @@ -23,8 +23,8 @@ namespace Volo.Abp.Auditing private readonly IAuditingStore _auditingStore; public AuditingManager( - IAmbientScopeProvider ambientScopeProvider, - IAuditingHelper auditingHelper, + IAmbientScopeProvider ambientScopeProvider, + IAuditingHelper auditingHelper, IAuditingStore auditingStore, IServiceProvider serviceProvider, IOptions options) @@ -84,7 +84,7 @@ namespace Volo.Abp.Auditing { var changeGroups = auditLog.EntityChanges .Where(e => e.ChangeType == EntityChangeType.Updated) - .GroupBy(e => new {e.EntityTypeFullName, e.EntityId}) + .GroupBy(e => new { e.EntityTypeFullName, e.EntityId }) .ToList(); foreach (var changeGroup in changeGroups) @@ -141,7 +141,7 @@ namespace Volo.Abp.Auditing public DisposableSaveHandle( AuditingManager auditingManager, IDisposable scope, - AuditLogInfo auditLog, + AuditLogInfo auditLog, Stopwatch stopWatch) { _auditingManager = auditingManager; diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginCommand.cs index fe9ed2d98f..32bc6671bf 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/LoginCommand.cs @@ -33,15 +33,19 @@ namespace Volo.Abp.Cli.Commands ); } - Console.Write("Password: "); - var password = ConsoleHelper.ReadSecret(); - if (password.IsNullOrWhiteSpace()) + var password = commandLineArgs.Options.GetOrNull(Options.Password.Short, Options.Password.Long); + if (password == null) { - throw new CliUsageException( - "Password is missing!" + - Environment.NewLine + Environment.NewLine + - GetUsageInfo() - ); + Console.Write("Password: "); + password = ConsoleHelper.ReadSecret(); + if (password.IsNullOrWhiteSpace()) + { + throw new CliUsageException( + "Password is missing!" + + Environment.NewLine + Environment.NewLine + + GetUsageInfo() + ); + } } await AuthService.LoginAsync( @@ -60,10 +64,12 @@ namespace Volo.Abp.Cli.Commands sb.AppendLine(""); sb.AppendLine("Usage:"); sb.AppendLine(" abp login "); + sb.AppendLine(" abp login -p "); sb.AppendLine(""); sb.AppendLine("Example:"); sb.AppendLine(""); sb.AppendLine(" abp login john"); + sb.AppendLine(" abp login john -p 1234"); sb.AppendLine(""); sb.AppendLine("See the documentation for more info: https://docs.abp.io/en/abp/latest/CLI"); @@ -82,6 +88,12 @@ namespace Volo.Abp.Cli.Commands public const string Short = "o"; public const string Long = "organization"; } + + public static class Password + { + public const string Short = "p"; + public const string Long = "password"; + } } } } \ No newline at end of file diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SuiteCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SuiteCommand.cs index a47a865617..a13621ea22 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SuiteCommand.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/SuiteCommand.cs @@ -54,7 +54,7 @@ namespace Volo.Abp.Cli.Commands private async Task InstallSuiteAsync() { var nugetIndexUrl = await GetNuGetIndexUrlAsync(); - + if (nugetIndexUrl == null) { return; @@ -108,13 +108,21 @@ namespace Volo.Abp.Cli.Commands { var apiKeyResult = await _apiKeyService.GetApiKeyOrNullAsync(); - if (apiKeyResult == null || string.IsNullOrEmpty(apiKeyResult.ApiKey)) + if (apiKeyResult == null) + { + Logger.LogWarning("You are not signed in! Use the CLI command \"abp login \" to sign in, then try again."); + return null; + } + + if (!string.IsNullOrWhiteSpace(apiKeyResult.ErrorMessage)) { - Logger.LogError("Couldn't retrieve your NuGet API key!"); - Logger.LogWarning(File.Exists(CliPaths.AccessToken) - ? "Make sure you have an active session and license on commercial.abp.io. To re-sign in you can use the CLI command \"abp login \"." - : "You are not signed in to commercial.abp.io. Use the CLI command \"abp login \" to sign in."); + Logger.LogWarning(apiKeyResult.ErrorMessage); + return null; + } + if (string.IsNullOrEmpty(apiKeyResult.ApiKey)) + { + Logger.LogError("Couldn't retrieve your NuGet API key! You can re-sign in with the CLI command \"abp login \"."); return null; } diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Licensing/DeveloperApiKeyResult.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Licensing/DeveloperApiKeyResult.cs index fb3622f6eb..eb781c27b1 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Licensing/DeveloperApiKeyResult.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Licensing/DeveloperApiKeyResult.cs @@ -10,5 +10,15 @@ namespace Volo.Abp.Cli.Licensing public DateTime? LicenseEndTime { get; set; } public bool CanDownloadSourceCode { get; set; } public string LicenseCode { get; set; } + public string ErrorMessage { get; set; } + public LicenseErrorType? ErrorType { get; set; } + + public enum LicenseErrorType + { + NotAuthenticated = 1, + NotMemberOfAnOrganization = 2, + NoActiveLicense = 3, + NotDeveloperOfTheOrganization = 4 + } } } \ No newline at end of file diff --git a/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/EntityHelper.cs b/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/EntityHelper.cs index 92ebdd4568..a33c5f56ec 100644 --- a/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/EntityHelper.cs +++ b/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Entities/EntityHelper.cs @@ -3,6 +3,8 @@ using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; +using Volo.Abp.MultiTenancy; +using Volo.Abp.Reflection; namespace Volo.Abp.Domain.Entities { @@ -11,6 +13,7 @@ namespace Volo.Abp.Domain.Entities /// public static class EntityHelper { + public static bool IsEntity([NotNull] Type type) { return typeof(IEntity).IsAssignableFrom(type); @@ -82,10 +85,10 @@ namespace Volo.Abp.Domain.Entities var lambdaBody = Expression.Equal(leftExpression, rightExpression); return Expression.Lambda>(lambdaBody, lambdaParam); } - + public static void TrySetId( - IEntity entity, - Func idFactory, + IEntity entity, + Func idFactory, bool checkForDisableGuidGenerationAttribute = false) { //TODO: Can be optimized (by caching per entity type)? diff --git a/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/RepositoryBase.cs b/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/RepositoryBase.cs index 29814f4de6..3ade403017 100644 --- a/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/RepositoryBase.cs +++ b/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/RepositoryBase.cs @@ -8,16 +8,19 @@ using System.Threading.Tasks; using Volo.Abp.Data; using Volo.Abp.Domain.Entities; using Volo.Abp.MultiTenancy; +using Volo.Abp.Uow; namespace Volo.Abp.Domain.Repositories { - public abstract class RepositoryBase : BasicRepositoryBase, IRepository + public abstract class RepositoryBase : BasicRepositoryBase, IRepository, IUnitOfWorkManagerAccessor where TEntity : class, IEntity { public IDataFilter DataFilter { get; set; } public ICurrentTenant CurrentTenant { get; set; } + public IUnitOfWorkManager UnitOfWorkManager { get; set; } + public virtual Type ElementType => GetQueryable().ElementType; public virtual Expression Expression => GetQueryable().Expression; diff --git a/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/RepositoryExtensions.cs b/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/RepositoryExtensions.cs index 40ebca015e..ef44d6830d 100644 --- a/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/RepositoryExtensions.cs +++ b/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/RepositoryExtensions.cs @@ -5,6 +5,7 @@ using System.Threading; using System.Threading.Tasks; using Volo.Abp.Domain.Entities; using Volo.Abp.DynamicProxy; +using Volo.Abp.Uow; namespace Volo.Abp.Domain.Repositories { @@ -41,5 +42,56 @@ namespace Volo.Abp.Domain.Repositories await repo.EnsurePropertyLoadedAsync(entity, propertyExpression, cancellationToken); } } + + public static async Task HardDeleteAsync( + this IBasicRepository repository, + TEntity entity, + bool autoSave = false, + CancellationToken cancellationToken = default + ) + where TEntity : class, IEntity, ISoftDelete + { + if (!(ProxyHelper.UnProxy(repository) is IUnitOfWorkManagerAccessor unitOfWorkManagerAccessor)) + { + throw new AbpException($"The given repository (of type {repository.GetType().AssemblyQualifiedName}) should implement the {typeof(IUnitOfWorkManagerAccessor).AssemblyQualifiedName} interface in order to invoke the {nameof(HardDeleteAsync)} method!"); + } + + var uowManager = unitOfWorkManagerAccessor.UnitOfWorkManager; + if (uowManager == null) + { + throw new AbpException($"{nameof(unitOfWorkManagerAccessor.UnitOfWorkManager)} property of the given {nameof(repository)} object is null!"); + } + + if (uowManager.Current == null) + { + using (var uow = uowManager.Begin()) + { + await HardDeleteWithUnitOfWorkAsync(repository, entity, autoSave, cancellationToken, uowManager.Current); + await uow.CompleteAsync(cancellationToken); + } + } + else + { + await HardDeleteWithUnitOfWorkAsync(repository, entity, autoSave, cancellationToken, uowManager.Current); + } + } + + private static async Task HardDeleteWithUnitOfWorkAsync( + IBasicRepository repository, + TEntity entity, + bool autoSave, + CancellationToken cancellationToken, IUnitOfWork currentUow + ) + where TEntity : class, IEntity, ISoftDelete + { + var hardDeleteEntities = (HashSet) currentUow.Items.GetOrAdd( + UnitOfWorkItemNames.HardDeletedEntities, + () => new HashSet() + ); + + hardDeleteEntities.Add(entity); + + await repository.DeleteAsync(entity, autoSave, cancellationToken); + } } } diff --git a/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/UnitOfWorkItemNames.cs b/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/UnitOfWorkItemNames.cs new file mode 100644 index 0000000000..4ec067ceec --- /dev/null +++ b/framework/src/Volo.Abp.Ddd.Domain/Volo/Abp/Domain/Repositories/UnitOfWorkItemNames.cs @@ -0,0 +1,7 @@ +namespace Volo.Abp.Domain.Repositories +{ + public static class UnitOfWorkItemNames + { + public const string HardDeletedEntities = "AbpHardDeletedEntities"; + } +} diff --git a/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EntityFrameworkCore/EfCoreRepository.cs b/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EntityFrameworkCore/EfCoreRepository.cs index 6c3eb689d8..106e00f77a 100644 --- a/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EntityFrameworkCore/EfCoreRepository.cs +++ b/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EntityFrameworkCore/EfCoreRepository.cs @@ -80,7 +80,7 @@ namespace Volo.Abp.Domain.Repositories.EntityFrameworkCore { return includeDetails ? await WithDetails().ToListAsync(GetCancellationToken(cancellationToken)) - : await DbSet.ToListAsync(GetCancellationToken(cancellationToken)); + : await DbSet.ToListAsync(GetCancellationToken(cancellationToken)); } public override async Task GetCountAsync(CancellationToken cancellationToken = default) @@ -208,7 +208,7 @@ namespace Volo.Abp.Domain.Repositories.EntityFrameworkCore { return includeDetails ? await WithDetails().FirstOrDefaultAsync(e => e.Id.Equals(id), GetCancellationToken(cancellationToken)) - : await DbSet.FindAsync(new object[] { id }, GetCancellationToken(cancellationToken)); + : await DbSet.FindAsync(new object[] {id}, GetCancellationToken(cancellationToken)); } public virtual async Task DeleteAsync(TKey id, bool autoSave = false, CancellationToken cancellationToken = default) diff --git a/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpDbContext.cs b/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpDbContext.cs index 16c5c38389..ba9cee70ee 100644 --- a/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpDbContext.cs +++ b/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpDbContext.cs @@ -16,6 +16,7 @@ using Volo.Abp.Data; using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Entities; using Volo.Abp.Domain.Entities.Events; +using Volo.Abp.Domain.Repositories; using Volo.Abp.EntityFrameworkCore.EntityHistory; using Volo.Abp.EntityFrameworkCore.Modeling; using Volo.Abp.EntityFrameworkCore.ValueConverters; @@ -23,6 +24,7 @@ using Volo.Abp.Guids; using Volo.Abp.MultiTenancy; using Volo.Abp.Reflection; using Volo.Abp.Timing; +using Volo.Abp.Uow; namespace Volo.Abp.EntityFrameworkCore { @@ -49,6 +51,8 @@ namespace Volo.Abp.EntityFrameworkCore public IAuditingManager AuditingManager { get; set; } + public IUnitOfWorkManager UnitOfWorkManager { get; set; } + public IClock Clock { get; set; } public ILogger> Logger { get; set; } @@ -102,7 +106,7 @@ namespace Volo.Abp.EntityFrameworkCore .Invoke(this, new object[] { modelBuilder, entityType }); } } - + public override async Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default) { try @@ -196,12 +200,26 @@ namespace Volo.Abp.EntityFrameworkCore protected virtual void ApplyAbpConceptsForDeletedEntity(EntityEntry entry, EntityChangeReport changeReport) { - CancelDeletionForSoftDelete(entry); - UpdateConcurrencyStamp(entry); - SetDeletionAuditProperties(entry); + if (TryCancelDeletionForSoftDelete(entry)) + { + UpdateConcurrencyStamp(entry); + SetDeletionAuditProperties(entry); + } + changeReport.ChangedEntities.Add(new EntityChangeEntry(entry.Entity, EntityChangeType.Deleted)); } + protected virtual bool IsHardDeleted(EntityEntry entry) + { + var hardDeletedEntities = UnitOfWorkManager?.Current?.Items.GetOrDefault(UnitOfWorkItemNames.HardDeletedEntities) as HashSet; + if (hardDeletedEntities == null) + { + return false; + } + + return hardDeletedEntities.Contains(entry.Entity); + } + protected virtual void AddDomainEvents(EntityChangeReport changeReport, object entityAsObj) { var generatesDomainEventsEntity = entityAsObj as IGeneratesDomainEvents; @@ -253,16 +271,22 @@ namespace Volo.Abp.EntityFrameworkCore entity.ConcurrencyStamp = Guid.NewGuid().ToString("N"); } - protected virtual void CancelDeletionForSoftDelete(EntityEntry entry) + protected virtual bool TryCancelDeletionForSoftDelete(EntityEntry entry) { if (!(entry.Entity is ISoftDelete)) { - return; + return false; + } + + if (IsHardDeleted(entry)) + { + return false; } entry.Reload(); entry.State = EntityState.Modified; entry.Entity.As().IsDeleted = true; + return true; } protected virtual void CheckAndSetId(EntityEntry entry) @@ -382,7 +406,7 @@ namespace Volo.Abp.EntityFrameworkCore return; } - var idPropertyBuilder = modelBuilder.Entity().Property(x => ((IEntity) x).Id); + var idPropertyBuilder = modelBuilder.Entity().Property(x => ((IEntity)x).Id); if (idPropertyBuilder.Metadata.PropertyInfo.IsDefined(typeof(DatabaseGeneratedAttribute), true)) { return; diff --git a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Local/ILocalEventHandler.cs b/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Local/ILocalEventHandler.cs index e3501294be..006097825c 100644 --- a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Local/ILocalEventHandler.cs +++ b/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Local/ILocalEventHandler.cs @@ -2,6 +2,7 @@ using System.Threading.Tasks; namespace Volo.Abp.EventBus { + //TODO: Move to the right namespace in v3.0 public interface ILocalEventHandler : IEventHandler { /// diff --git a/framework/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDB/MongoDbRepository.cs b/framework/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDB/MongoDbRepository.cs index 4e8ccaa82e..3333f1d505 100644 --- a/framework/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDB/MongoDbRepository.cs +++ b/framework/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDB/MongoDbRepository.cs @@ -111,7 +111,7 @@ namespace Volo.Abp.Domain.Repositories.MongoDB await ApplyAbpConceptsForDeletedEntityAsync(entity); var oldConcurrencyStamp = SetNewConcurrencyStamp(entity); - if (entity is ISoftDelete softDeleteEntity) + if (entity is ISoftDelete softDeleteEntity && !IsHardDeleted(entity)) { softDeleteEntity.IsDeleted = true; var result = await Collection.ReplaceOneAsync( @@ -175,11 +175,21 @@ namespace Volo.Abp.Domain.Repositories.MongoDB Collection.AsQueryable() ); } + protected virtual bool IsHardDeleted(TEntity entity) + { + var hardDeletedEntities = UnitOfWorkManager?.Current?.Items.GetOrDefault(UnitOfWorkItemNames.HardDeletedEntities) as HashSet; + if (hardDeletedEntities == null) + { + return false; + } + + return hardDeletedEntities.Contains(entity); + } protected virtual FilterDefinition CreateEntityFilter(TEntity entity, bool withConcurrencyStamp = false, string concurrencyStamp = null) { throw new NotImplementedException( - $"{nameof(CreateEntityFilter)} is not implemented for MongoDB by default. It should be overrided and implemented by the deriving class!" + $"{nameof(CreateEntityFilter)} is not implemented for MongoDB by default. It should be overriden and implemented by the deriving class!" ); } diff --git a/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/ChildUnitOfWork.cs b/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/ChildUnitOfWork.cs index d1d90b6f6f..882c8d6a70 100644 --- a/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/ChildUnitOfWork.cs +++ b/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/ChildUnitOfWork.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; @@ -26,6 +27,8 @@ namespace Volo.Abp.Uow public IServiceProvider ServiceProvider => _parent.ServiceProvider; + public Dictionary Items => _parent.Items; + private readonly IUnitOfWork _parent; public ChildUnitOfWork([NotNull] IUnitOfWork parent) diff --git a/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/IUnitOfWork.cs b/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/IUnitOfWork.cs index 32ef781133..ee5baa58bc 100644 --- a/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/IUnitOfWork.cs +++ b/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/IUnitOfWork.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; @@ -9,6 +10,8 @@ namespace Volo.Abp.Uow { Guid Id { get; } + Dictionary Items { get; } + //TODO: Switch to OnFailed (sync) and OnDisposed (sync) methods to be compatible with OnCompleted event EventHandler Failed; diff --git a/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/IUnitOfWorkManagerAccessor.cs b/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/IUnitOfWorkManagerAccessor.cs new file mode 100644 index 0000000000..a12b77855e --- /dev/null +++ b/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/IUnitOfWorkManagerAccessor.cs @@ -0,0 +1,7 @@ +namespace Volo.Abp.Uow +{ + public interface IUnitOfWorkManagerAccessor + { + IUnitOfWorkManager UnitOfWorkManager { get; } + } +} diff --git a/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/UnitOfWork.cs b/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/UnitOfWork.cs index e7e86774b5..05f49df180 100644 --- a/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/UnitOfWork.cs +++ b/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/UnitOfWork.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; +using JetBrains.Annotations; using Microsoft.Extensions.Options; using Volo.Abp.DependencyInjection; @@ -31,6 +32,9 @@ namespace Volo.Abp.Uow public IServiceProvider ServiceProvider { get; } + [NotNull] + public Dictionary Items { get; } + private readonly Dictionary _databaseApis; private readonly Dictionary _transactionApis; private readonly AbpUnitOfWorkDefaultOptions _defaultOptions; @@ -46,6 +50,8 @@ namespace Volo.Abp.Uow _databaseApis = new Dictionary(); _transactionApis = new Dictionary(); + + Items = new Dictionary(); } public virtual void Initialize(AbpUnitOfWorkOptions options) diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/AuditTestController.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/AuditTestController.cs new file mode 100644 index 0000000000..3c8d5dc4db --- /dev/null +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/AuditTestController.cs @@ -0,0 +1,35 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; +using Volo.Abp.Auditing; + +namespace Volo.Abp.AspNetCore.Mvc.Auditing +{ + [Route("api/audit-test")] + [Audited] + public class AuditTestController : AbpController + { + private readonly AbpAuditingOptions _options; + + public AuditTestController(IOptions options) + { + _options = options.Value; + } + + [Route("audit-success")] + public IActionResult AuditSuccessForGetRequests() + { + return Ok(); + } + + [Route("audit-fail")] + public IActionResult AuditFailForGetRequests() + { + throw new UserFriendlyException("Exception occurred!"); + } + [Route("audit-fail-object")] + public object AuditFailForGetRequestsReturningObject() + { + throw new UserFriendlyException("Exception occurred!"); + } + } +} diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/AuditTestController_Tests.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/AuditTestController_Tests.cs new file mode 100644 index 0000000000..49bc689e14 --- /dev/null +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Auditing/AuditTestController_Tests.cs @@ -0,0 +1,65 @@ +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using NSubstitute; +using System.Threading.Tasks; +using Volo.Abp.Auditing; +using Xunit; + +namespace Volo.Abp.AspNetCore.Mvc.Auditing +{ + public class AuditTestController_Tests : AspNetCoreMvcTestBase + { + private readonly AbpAuditingOptions _options; + private IAuditingStore _auditingStore; + + public AuditTestController_Tests() + { + _options = ServiceProvider.GetRequiredService>().Value; + _auditingStore = ServiceProvider.GetRequiredService(); + } + + protected override void ConfigureServices(HostBuilderContext context, IServiceCollection services) + { + _auditingStore = Substitute.For(); + services.Replace(ServiceDescriptor.Singleton(_auditingStore)); + base.ConfigureServices(context, services); + } + + [Fact] + public async Task Should_Trigger_Middleware_And_AuditLog_Success_For_GetRequests() + { + _options.IsEnabledForGetRequests = true; + _options.AlwaysLogOnException = false; + await GetResponseAsync("api/audit-test/audit-success"); + await _auditingStore.Received().SaveAsync(Arg.Any()); + } + + [Fact] + public async Task Should_Trigger_Middleware_And_AuditLog_Exception_Always() + { + _options.IsEnabled = true; + _options.AlwaysLogOnException = true; + + try + { + await GetResponseAsync("api/audit-test/audit-fail", System.Net.HttpStatusCode.Forbidden); + } + catch { } + + await _auditingStore.Received().SaveAsync(Arg.Any()); + } + [Fact] + public async Task Should_Trigger_Middleware_And_AuditLog_Exception_When_Returns_Object() + { + _options.IsEnabled = true; + _options.AlwaysLogOnException = true; + + await GetResponseAsync("api/audit-test/audit-fail-object", System.Net.HttpStatusCode.Forbidden); + + await _auditingStore.Received().SaveAsync(Arg.Any()); + } + } +} diff --git a/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/HardDelete_Tests.cs b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/HardDelete_Tests.cs new file mode 100644 index 0000000000..df3fd98b62 --- /dev/null +++ b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/HardDelete_Tests.cs @@ -0,0 +1,8 @@ +using Volo.Abp.TestApp.Testing; + +namespace Volo.Abp.EntityFrameworkCore.DataFiltering +{ + public class HardDelete_Tests : HardDelete_Tests + { + } +} diff --git a/framework/test/Volo.Abp.MongoDB.Tests/Volo/Abp/MongoDB/DataFiltering/HardDelete_Tests.cs b/framework/test/Volo.Abp.MongoDB.Tests/Volo/Abp/MongoDB/DataFiltering/HardDelete_Tests.cs new file mode 100644 index 0000000000..66c6e58b5c --- /dev/null +++ b/framework/test/Volo.Abp.MongoDB.Tests/Volo/Abp/MongoDB/DataFiltering/HardDelete_Tests.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Volo.Abp.TestApp.Testing; + +namespace Volo.Abp.MongoDB.DataFiltering +{ + public class HardDelete_Tests : HardDelete_Tests + { + } +} diff --git a/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Domain/Phone.cs b/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Domain/Phone.cs index 20292e3de8..c5522cf53a 100644 --- a/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Domain/Phone.cs +++ b/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Domain/Phone.cs @@ -7,7 +7,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.TestApp.Domain { [Table("AppPhones")] - public class Phone : Entity + public class Phone : Entity { public virtual Guid PersonId { get; set; } @@ -17,11 +17,12 @@ namespace Volo.Abp.TestApp.Domain private Phone() { - + } public Phone(Guid personId, string number, PhoneType type = PhoneType.Mobile) { + Id = Guid.NewGuid(); PersonId = personId; Number = number; Type = type; @@ -29,7 +30,7 @@ namespace Volo.Abp.TestApp.Domain public override object[] GetKeys() { - return new object[] {PersonId, Number}; + return new object[] { PersonId, Number }; } } @@ -45,7 +46,7 @@ namespace Volo.Abp.TestApp.Domain protected Order() { - + } public Order(Guid id, string referenceNo) @@ -104,7 +105,7 @@ namespace Volo.Abp.TestApp.Domain public override object[] GetKeys() { - return new object[] {OrderId, ProductId}; + return new object[] { OrderId, ProductId }; } } } \ No newline at end of file diff --git a/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Testing/HardDelete_Tests.cs b/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Testing/HardDelete_Tests.cs new file mode 100644 index 0000000000..1eac79fd7c --- /dev/null +++ b/framework/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Testing/HardDelete_Tests.cs @@ -0,0 +1,69 @@ +using Shouldly; +using System; +using System.Threading.Tasks; +using Volo.Abp.Data; +using Volo.Abp.Domain.Repositories; +using Volo.Abp.Modularity; +using Volo.Abp.TestApp.Domain; +using Volo.Abp.Uow; +using Xunit; + +namespace Volo.Abp.TestApp.Testing +{ + public abstract class HardDelete_Tests : TestAppTestBase + where TStartupModule : IAbpModule + { + protected readonly IRepository PersonRepository; + protected readonly IDataFilter DataFilter; + protected readonly IUnitOfWorkManager UnitOfWorkManager; + + protected HardDelete_Tests() + { + PersonRepository = GetRequiredService>(); + DataFilter = GetRequiredService(); + UnitOfWorkManager = GetRequiredService(); + } + + [Fact] + public async Task Should_HardDelete_Entities() + { + var douglas = await PersonRepository.GetAsync(TestDataBuilder.UserDouglasId); + await PersonRepository.HardDeleteAsync(douglas); + + douglas = await PersonRepository.FindAsync(TestDataBuilder.UserDouglasId); + douglas.ShouldBeNull(); + } + + [Fact] + public async Task Should_HardDelete_Soft_Deleted_Entities() + { + var douglas = await PersonRepository.GetAsync(TestDataBuilder.UserDouglasId); + await PersonRepository.DeleteAsync(douglas); + + douglas = await PersonRepository.FindAsync(TestDataBuilder.UserDouglasId); + douglas.ShouldBeNull(); + + using (DataFilter.Disable()) + { + douglas = await PersonRepository.FindAsync(TestDataBuilder.UserDouglasId); + douglas.ShouldNotBeNull(); + douglas.IsDeleted.ShouldBeTrue(); + douglas.DeletionTime.ShouldNotBeNull(); + } + + using (var uow = UnitOfWorkManager.Begin()) + { + using (DataFilter.Disable()) + { + douglas = await PersonRepository.GetAsync(TestDataBuilder.UserDouglasId); + } + + await PersonRepository.HardDeleteAsync(douglas); + await uow.CompleteAsync(); + } + + douglas = await PersonRepository.FindAsync(TestDataBuilder.UserDouglasId); + douglas.ShouldBeNull(); + } + } +} diff --git a/modules/docs/Volo.Docs.sln b/modules/docs/Volo.Docs.sln index 74e748ac9b..1c32767baa 100644 --- a/modules/docs/Volo.Docs.sln +++ b/modules/docs/Volo.Docs.sln @@ -57,9 +57,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VoloDocs.Web", "app\VoloDoc EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VoloDocs.Migrator", "app\VoloDocs.Migrator\VoloDocs.Migrator.csproj", "{8A5E5001-C017-44A8-ADDA-DC66C102556E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Docs.MongoDB", "src\Volo.Docs.MongoDB\Volo.Docs.MongoDB.csproj", "{DBE846CD-1BED-4F2C-ABF2-94F6240BCB9B}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Docs.MongoDB", "src\Volo.Docs.MongoDB\Volo.Docs.MongoDB.csproj", "{DBE846CD-1BED-4F2C-ABF2-94F6240BCB9B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Docs.MongoDB.Tests", "test\Volo.Docs.MongoDB.Tests\Volo.Docs.MongoDB.Tests.csproj", "{C5E2A2A3-D54D-4C2E-97BA-EA50A49ED7AD}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Volo.Docs.MongoDB.Tests", "test\Volo.Docs.MongoDB.Tests\Volo.Docs.MongoDB.Tests.csproj", "{C5E2A2A3-D54D-4C2E-97BA-EA50A49ED7AD}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/20181225134002_Initial20181225.Designer.cs b/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/20181225134002_Initial20181225.Designer.cs deleted file mode 100644 index ab8c782832..0000000000 --- a/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/20181225134002_Initial20181225.Designer.cs +++ /dev/null @@ -1,465 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using VoloDocs.EntityFrameworkCore; - -namespace VoloDocs.EntityFrameworkCore.Migrations -{ - [DbContext(typeof(VoloDocsDbContext))] - [Migration("20181225134002_Initial20181225")] - partial class Initial20181225 - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "2.1.1-rtm-30846") - .HasAnnotation("Relational:MaxIdentifierLength", 128) - .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); - - modelBuilder.Entity("Volo.Abp.Identity.IdentityClaimType", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .IsRequired() - .HasColumnName("ConcurrencyStamp") - .HasMaxLength(256); - - b.Property("Description") - .HasMaxLength(256); - - b.Property("ExtraProperties") - .HasColumnName("ExtraProperties"); - - b.Property("IsStatic"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(256); - - b.Property("Regex") - .HasMaxLength(512); - - b.Property("RegexDescription") - .HasMaxLength(128); - - b.Property("Required"); - - b.Property("ValueType"); - - b.HasKey("Id"); - - b.ToTable("AbpClaimTypes"); - }); - - modelBuilder.Entity("Volo.Abp.Identity.IdentityRole", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .IsRequired() - .HasColumnName("ConcurrencyStamp") - .HasMaxLength(256); - - b.Property("ExtraProperties") - .HasColumnName("ExtraProperties"); - - b.Property("IsDefault") - .HasColumnName("IsDefault"); - - b.Property("IsPublic") - .HasColumnName("IsPublic"); - - b.Property("IsStatic") - .HasColumnName("IsStatic"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(256); - - b.Property("NormalizedName") - .IsRequired() - .HasMaxLength(256); - - b.Property("TenantId"); - - b.HasKey("Id"); - - b.HasIndex("NormalizedName"); - - b.ToTable("AbpRoles"); - }); - - modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClaimType") - .IsRequired() - .HasMaxLength(256); - - b.Property("ClaimValue") - .HasMaxLength(1024); - - b.Property("RoleId"); - - b.Property("TenantId"); - - b.HasKey("Id"); - - b.HasIndex("RoleId"); - - b.ToTable("AbpRoleClaims"); - }); - - modelBuilder.Entity("Volo.Abp.Identity.IdentityUser", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("AccessFailedCount") - .ValueGeneratedOnAdd() - .HasColumnName("AccessFailedCount") - .HasDefaultValue(0); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnName("ConcurrencyStamp"); - - b.Property("CreationTime") - .HasColumnName("CreationTime"); - - b.Property("CreatorId") - .HasColumnName("CreatorId"); - - b.Property("DeleterId") - .HasColumnName("DeleterId"); - - b.Property("DeletionTime") - .HasColumnName("DeletionTime"); - - b.Property("Email") - .HasColumnName("Email") - .HasMaxLength(256); - - b.Property("EmailConfirmed") - .ValueGeneratedOnAdd() - .HasColumnName("EmailConfirmed") - .HasDefaultValue(false); - - b.Property("ExtraProperties") - .HasColumnName("ExtraProperties"); - - b.Property("IsDeleted") - .ValueGeneratedOnAdd() - .HasColumnName("IsDeleted") - .HasDefaultValue(false); - - b.Property("LastModificationTime") - .HasColumnName("LastModificationTime"); - - b.Property("LastModifierId") - .HasColumnName("LastModifierId"); - - b.Property("LockoutEnabled") - .ValueGeneratedOnAdd() - .HasColumnName("LockoutEnabled") - .HasDefaultValue(false); - - b.Property("LockoutEnd"); - - b.Property("Name") - .HasColumnName("Name") - .HasMaxLength(64); - - b.Property("NormalizedEmail") - .HasColumnName("NormalizedEmail") - .HasMaxLength(256); - - b.Property("NormalizedUserName") - .IsRequired() - .HasColumnName("NormalizedUserName") - .HasMaxLength(256); - - b.Property("PasswordHash") - .HasColumnName("PasswordHash") - .HasMaxLength(256); - - b.Property("PhoneNumber") - .HasColumnName("PhoneNumber") - .HasMaxLength(16); - - b.Property("PhoneNumberConfirmed") - .ValueGeneratedOnAdd() - .HasColumnName("PhoneNumberConfirmed") - .HasDefaultValue(false); - - b.Property("SecurityStamp") - .IsRequired() - .HasColumnName("SecurityStamp") - .HasMaxLength(256); - - b.Property("Surname") - .HasColumnName("Surname") - .HasMaxLength(64); - - b.Property("TenantId") - .HasColumnName("TenantId"); - - b.Property("TwoFactorEnabled") - .ValueGeneratedOnAdd() - .HasColumnName("TwoFactorEnabled") - .HasDefaultValue(false); - - b.Property("UserName") - .IsRequired() - .HasColumnName("UserName") - .HasMaxLength(256); - - b.HasKey("Id"); - - b.HasIndex("Email"); - - b.HasIndex("NormalizedEmail"); - - b.HasIndex("NormalizedUserName"); - - b.HasIndex("UserName"); - - b.ToTable("AbpUsers"); - }); - - modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ClaimType") - .IsRequired() - .HasMaxLength(256); - - b.Property("ClaimValue") - .HasMaxLength(1024); - - b.Property("TenantId"); - - b.Property("UserId"); - - b.HasKey("Id"); - - b.HasIndex("UserId"); - - b.ToTable("AbpUserClaims"); - }); - - modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => - { - b.Property("UserId"); - - b.Property("LoginProvider") - .HasMaxLength(64); - - b.Property("ProviderDisplayName") - .HasMaxLength(128); - - b.Property("ProviderKey") - .IsRequired() - .HasMaxLength(196); - - b.Property("TenantId"); - - b.HasKey("UserId", "LoginProvider"); - - b.HasIndex("LoginProvider", "ProviderKey"); - - b.ToTable("AbpUserLogins"); - }); - - modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => - { - b.Property("UserId"); - - b.Property("RoleId"); - - b.Property("TenantId"); - - b.HasKey("UserId", "RoleId"); - - b.HasIndex("RoleId", "UserId"); - - b.ToTable("AbpUserRoles"); - }); - - modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => - { - b.Property("UserId"); - - b.Property("LoginProvider") - .HasMaxLength(64); - - b.Property("Name") - .HasMaxLength(128); - - b.Property("TenantId"); - - b.Property("Value"); - - b.HasKey("UserId", "LoginProvider", "Name"); - - b.ToTable("AbpUserTokens"); - }); - - modelBuilder.Entity("Volo.Abp.PermissionManagement.PermissionGrant", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("Name") - .IsRequired() - .HasMaxLength(128); - - b.Property("ProviderKey") - .IsRequired() - .HasMaxLength(64); - - b.Property("ProviderName") - .IsRequired() - .HasMaxLength(64); - - b.Property("TenantId"); - - b.HasKey("Id"); - - b.HasIndex("Name", "ProviderName", "ProviderKey"); - - b.ToTable("AbpPermissionGrants"); - }); - - modelBuilder.Entity("Volo.Abp.SettingManagement.Setting", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("Name") - .IsRequired() - .HasMaxLength(128); - - b.Property("ProviderKey") - .HasMaxLength(64); - - b.Property("ProviderName") - .HasMaxLength(64); - - b.Property("Value") - .IsRequired() - .HasMaxLength(2048); - - b.HasKey("Id"); - - b.HasIndex("Name", "ProviderName", "ProviderKey"); - - b.ToTable("AbpSettings"); - }); - - modelBuilder.Entity("Volo.Docs.Projects.Project", b => - { - b.Property("Id") - .ValueGeneratedOnAdd(); - - b.Property("ConcurrencyStamp") - .IsConcurrencyToken() - .HasColumnName("ConcurrencyStamp"); - - b.Property("DefaultDocumentName") - .IsRequired() - .HasMaxLength(128); - - b.Property("DocumentStoreType"); - - b.Property("ExtraProperties") - .HasColumnName("ExtraProperties"); - - b.Property("Format"); - - b.Property("LatestVersionBranchName") - .HasMaxLength(128); - - b.Property("MainWebsiteUrl"); - - b.Property("MinimumVersion"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(128); - - b.Property("NavigationDocumentName") - .IsRequired() - .HasMaxLength(128); - - b.Property("ShortName") - .IsRequired() - .HasMaxLength(32); - - b.HasKey("Id"); - - b.ToTable("DocsProjects"); - }); - - modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => - { - b.HasOne("Volo.Abp.Identity.IdentityRole") - .WithMany("Claims") - .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => - { - b.HasOne("Volo.Abp.Identity.IdentityUser") - .WithMany("Claims") - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => - { - b.HasOne("Volo.Abp.Identity.IdentityUser") - .WithMany("Logins") - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => - { - b.HasOne("Volo.Abp.Identity.IdentityRole") - .WithMany() - .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade); - - b.HasOne("Volo.Abp.Identity.IdentityUser") - .WithMany("Roles") - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); - }); - - modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => - { - b.HasOne("Volo.Abp.Identity.IdentityUser") - .WithMany("Tokens") - .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/20200218014727_init.Designer.cs b/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/20200218014727_init.Designer.cs new file mode 100644 index 0000000000..522b3e3ba5 --- /dev/null +++ b/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/20200218014727_init.Designer.cs @@ -0,0 +1,670 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using VoloDocs.EntityFrameworkCore; + +namespace VoloDocs.EntityFrameworkCore.Migrations +{ + [DbContext(typeof(VoloDocsDbContext))] + [Migration("20200218014727_init")] + partial class init + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "3.1.1") + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("Volo.Abp.Identity.IdentityClaimType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .IsRequired() + .HasColumnName("ConcurrencyStamp") + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.Property("Description") + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.Property("ExtraProperties") + .HasColumnName("ExtraProperties") + .HasColumnType("nvarchar(max)"); + + b.Property("IsStatic") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.Property("Regex") + .HasColumnType("nvarchar(512)") + .HasMaxLength(512); + + b.Property("RegexDescription") + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("Required") + .HasColumnType("bit"); + + b.Property("ValueType") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("AbpClaimTypes"); + }); + + modelBuilder.Entity("Volo.Abp.Identity.IdentityRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .IsRequired() + .HasColumnName("ConcurrencyStamp") + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.Property("ExtraProperties") + .HasColumnName("ExtraProperties") + .HasColumnType("nvarchar(max)"); + + b.Property("IsDefault") + .HasColumnName("IsDefault") + .HasColumnType("bit"); + + b.Property("IsPublic") + .HasColumnName("IsPublic") + .HasColumnType("bit"); + + b.Property("IsStatic") + .HasColumnName("IsStatic") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.Property("NormalizedName") + .IsRequired() + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName"); + + b.ToTable("AbpRoles"); + }); + + modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("ClaimType") + .IsRequired() + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(1024)") + .HasMaxLength(1024); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AbpRoleClaims"); + }); + + modelBuilder.Entity("Volo.Abp.Identity.IdentityUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AccessFailedCount") + .ValueGeneratedOnAdd() + .HasColumnName("AccessFailedCount") + .HasColumnType("int") + .HasDefaultValue(0); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnName("ConcurrencyStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("CreationTime") + .HasColumnName("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreatorId") + .HasColumnName("CreatorId") + .HasColumnType("uniqueidentifier"); + + b.Property("DeleterId") + .HasColumnName("DeleterId") + .HasColumnType("uniqueidentifier"); + + b.Property("DeletionTime") + .HasColumnName("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("Email") + .IsRequired() + .HasColumnName("Email") + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.Property("EmailConfirmed") + .ValueGeneratedOnAdd() + .HasColumnName("EmailConfirmed") + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("ExtraProperties") + .HasColumnName("ExtraProperties") + .HasColumnType("nvarchar(max)"); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnName("IsDeleted") + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("LastModificationTime") + .HasColumnName("LastModificationTime") + .HasColumnType("datetime2"); + + b.Property("LastModifierId") + .HasColumnName("LastModifierId") + .HasColumnType("uniqueidentifier"); + + b.Property("LockoutEnabled") + .ValueGeneratedOnAdd() + .HasColumnName("LockoutEnabled") + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .HasColumnName("Name") + .HasColumnType("nvarchar(64)") + .HasMaxLength(64); + + b.Property("NormalizedEmail") + .IsRequired() + .HasColumnName("NormalizedEmail") + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.Property("NormalizedUserName") + .IsRequired() + .HasColumnName("NormalizedUserName") + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.Property("PasswordHash") + .HasColumnName("PasswordHash") + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.Property("PhoneNumber") + .HasColumnName("PhoneNumber") + .HasColumnType("nvarchar(16)") + .HasMaxLength(16); + + b.Property("PhoneNumberConfirmed") + .ValueGeneratedOnAdd() + .HasColumnName("PhoneNumberConfirmed") + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("SecurityStamp") + .IsRequired() + .HasColumnName("SecurityStamp") + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.Property("Surname") + .HasColumnName("Surname") + .HasColumnType("nvarchar(64)") + .HasMaxLength(64); + + b.Property("TenantId") + .HasColumnName("TenantId") + .HasColumnType("uniqueidentifier"); + + b.Property("TwoFactorEnabled") + .ValueGeneratedOnAdd() + .HasColumnName("TwoFactorEnabled") + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("UserName") + .IsRequired() + .HasColumnName("UserName") + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.HasKey("Id"); + + b.HasIndex("Email"); + + b.HasIndex("NormalizedEmail"); + + b.HasIndex("NormalizedUserName"); + + b.HasIndex("UserName"); + + b.ToTable("AbpUsers"); + }); + + modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("ClaimType") + .IsRequired() + .HasColumnType("nvarchar(256)") + .HasMaxLength(256); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(1024)") + .HasMaxLength(1024); + + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); + + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AbpUserClaims"); + }); + + modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => + { + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(64)") + .HasMaxLength(64); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("ProviderKey") + .IsRequired() + .HasColumnType("nvarchar(196)") + .HasMaxLength(196); + + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("UserId", "LoginProvider"); + + b.HasIndex("LoginProvider", "ProviderKey"); + + b.ToTable("AbpUserLogins"); + }); + + modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId", "UserId"); + + b.ToTable("AbpUserRoles"); + }); + + modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(64)") + .HasMaxLength(64); + + b.Property("Name") + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AbpUserTokens"); + }); + + modelBuilder.Entity("Volo.Abp.PermissionManagement.PermissionGrant", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("ProviderKey") + .IsRequired() + .HasColumnType("nvarchar(64)") + .HasMaxLength(64); + + b.Property("ProviderName") + .IsRequired() + .HasColumnType("nvarchar(64)") + .HasMaxLength(64); + + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("Name", "ProviderName", "ProviderKey"); + + b.ToTable("AbpPermissionGrants"); + }); + + modelBuilder.Entity("Volo.Abp.SettingManagement.Setting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(64)") + .HasMaxLength(64); + + b.Property("ProviderName") + .HasColumnType("nvarchar(64)") + .HasMaxLength(64); + + b.Property("Value") + .IsRequired() + .HasColumnType("nvarchar(2048)") + .HasMaxLength(2048); + + b.HasKey("Id"); + + b.HasIndex("Name", "ProviderName", "ProviderKey"); + + b.ToTable("AbpSettings"); + }); + + modelBuilder.Entity("Volo.Docs.Documents.Document", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnName("ConcurrencyStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("EditLink") + .HasColumnType("nvarchar(2048)") + .HasMaxLength(2048); + + b.Property("ExtraProperties") + .HasColumnName("ExtraProperties") + .HasColumnType("nvarchar(max)"); + + b.Property("FileName") + .IsRequired() + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("Format") + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("LanguageCode") + .IsRequired() + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("LastCachedTime") + .HasColumnType("datetime2"); + + b.Property("LastUpdatedTime") + .HasColumnType("datetime2"); + + b.Property("LocalDirectory") + .HasColumnType("nvarchar(512)") + .HasMaxLength(512); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(255)") + .HasMaxLength(255); + + b.Property("ProjectId") + .HasColumnType("uniqueidentifier"); + + b.Property("RawRootUrl") + .HasColumnType("nvarchar(2048)") + .HasMaxLength(2048); + + b.Property("RootUrl") + .HasColumnType("nvarchar(2048)") + .HasMaxLength(2048); + + b.Property("Version") + .IsRequired() + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.HasKey("Id"); + + b.ToTable("DocsDocuments"); + }); + + modelBuilder.Entity("Volo.Docs.Documents.DocumentContributor", b => + { + b.Property("DocumentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Username") + .HasColumnType("nvarchar(450)"); + + b.Property("AvatarUrl") + .HasColumnType("nvarchar(max)"); + + b.Property("UserProfileUrl") + .HasColumnType("nvarchar(max)"); + + b.HasKey("DocumentId", "Username"); + + b.ToTable("DocsDocumentContributors"); + }); + + modelBuilder.Entity("Volo.Docs.Projects.Project", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnName("ConcurrencyStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("DefaultDocumentName") + .IsRequired() + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("DocumentStoreType") + .HasColumnType("nvarchar(max)"); + + b.Property("ExtraProperties") + .HasColumnName("ExtraProperties") + .HasColumnType("nvarchar(max)"); + + b.Property("Format") + .HasColumnType("nvarchar(max)"); + + b.Property("LatestVersionBranchName") + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("MainWebsiteUrl") + .HasColumnType("nvarchar(max)"); + + b.Property("MinimumVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("NavigationDocumentName") + .IsRequired() + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("ParametersDocumentName") + .IsRequired() + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("ShortName") + .IsRequired() + .HasColumnType("nvarchar(32)") + .HasMaxLength(32); + + b.HasKey("Id"); + + b.ToTable("DocsProjects"); + }); + + modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => + { + b.HasOne("Volo.Abp.Identity.IdentityRole", null) + .WithMany("Claims") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => + { + b.HasOne("Volo.Abp.Identity.IdentityUser", null) + .WithMany("Claims") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => + { + b.HasOne("Volo.Abp.Identity.IdentityUser", null) + .WithMany("Logins") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => + { + b.HasOne("Volo.Abp.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Volo.Abp.Identity.IdentityUser", null) + .WithMany("Roles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => + { + b.HasOne("Volo.Abp.Identity.IdentityUser", null) + .WithMany("Tokens") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Volo.Docs.Documents.DocumentContributor", b => + { + b.HasOne("Volo.Docs.Documents.Document", null) + .WithMany("Contributors") + .HasForeignKey("DocumentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/20181225134002_Initial20181225.cs b/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/20200218014727_init.cs similarity index 83% rename from modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/20181225134002_Initial20181225.cs rename to modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/20200218014727_init.cs index abae1bbc04..7e85e1bbc1 100644 --- a/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/20181225134002_Initial20181225.cs +++ b/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/20200218014727_init.cs @@ -3,7 +3,7 @@ using Microsoft.EntityFrameworkCore.Migrations; namespace VoloDocs.EntityFrameworkCore.Migrations { - public partial class Initial20181225 : Migration + public partial class init : Migration { protected override void Up(MigrationBuilder migrationBuilder) { @@ -95,8 +95,8 @@ namespace VoloDocs.EntityFrameworkCore.Migrations NormalizedUserName = table.Column(maxLength: 256, nullable: false), Name = table.Column(maxLength: 64, nullable: true), Surname = table.Column(maxLength: 64, nullable: true), - Email = table.Column(maxLength: 256, nullable: true), - NormalizedEmail = table.Column(maxLength: 256, nullable: true), + Email = table.Column(maxLength: 256, nullable: false), + NormalizedEmail = table.Column(maxLength: 256, nullable: false), EmailConfirmed = table.Column(nullable: false, defaultValue: false), PasswordHash = table.Column(maxLength: 256, nullable: true), SecurityStamp = table.Column(maxLength: 256, nullable: false), @@ -112,6 +112,33 @@ namespace VoloDocs.EntityFrameworkCore.Migrations table.PrimaryKey("PK_AbpUsers", x => x.Id); }); + migrationBuilder.CreateTable( + name: "DocsDocuments", + columns: table => new + { + Id = table.Column(nullable: false), + ExtraProperties = table.Column(nullable: true), + ConcurrencyStamp = table.Column(nullable: true), + ProjectId = table.Column(nullable: false), + Name = table.Column(maxLength: 255, nullable: false), + Version = table.Column(maxLength: 128, nullable: false), + LanguageCode = table.Column(maxLength: 128, nullable: false), + FileName = table.Column(maxLength: 128, nullable: false), + Content = table.Column(nullable: false), + Format = table.Column(maxLength: 128, nullable: true), + EditLink = table.Column(maxLength: 2048, nullable: true), + RootUrl = table.Column(maxLength: 2048, nullable: true), + RawRootUrl = table.Column(maxLength: 2048, nullable: true), + LocalDirectory = table.Column(maxLength: 512, nullable: true), + CreationTime = table.Column(nullable: false), + LastUpdatedTime = table.Column(nullable: false), + LastCachedTime = table.Column(nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_DocsDocuments", x => x.Id); + }); + migrationBuilder.CreateTable( name: "DocsProjects", columns: table => new @@ -124,6 +151,7 @@ namespace VoloDocs.EntityFrameworkCore.Migrations Format = table.Column(nullable: true), DefaultDocumentName = table.Column(maxLength: 128, nullable: false), NavigationDocumentName = table.Column(maxLength: 128, nullable: false), + ParametersDocumentName = table.Column(maxLength: 128, nullable: false), MinimumVersion = table.Column(nullable: true), DocumentStoreType = table.Column(nullable: true), MainWebsiteUrl = table.Column(nullable: true), @@ -180,9 +208,9 @@ namespace VoloDocs.EntityFrameworkCore.Migrations name: "AbpUserLogins", columns: table => new { - TenantId = table.Column(nullable: true), UserId = table.Column(nullable: false), LoginProvider = table.Column(maxLength: 64, nullable: false), + TenantId = table.Column(nullable: true), ProviderKey = table.Column(maxLength: 196, nullable: false), ProviderDisplayName = table.Column(maxLength: 128, nullable: true) }, @@ -201,9 +229,9 @@ namespace VoloDocs.EntityFrameworkCore.Migrations name: "AbpUserRoles", columns: table => new { - TenantId = table.Column(nullable: true), UserId = table.Column(nullable: false), - RoleId = table.Column(nullable: false) + RoleId = table.Column(nullable: false), + TenantId = table.Column(nullable: true) }, constraints: table => { @@ -226,10 +254,10 @@ namespace VoloDocs.EntityFrameworkCore.Migrations name: "AbpUserTokens", columns: table => new { - TenantId = table.Column(nullable: true), UserId = table.Column(nullable: false), LoginProvider = table.Column(maxLength: 64, nullable: false), Name = table.Column(maxLength: 128, nullable: false), + TenantId = table.Column(nullable: true), Value = table.Column(nullable: true) }, constraints: table => @@ -243,6 +271,26 @@ namespace VoloDocs.EntityFrameworkCore.Migrations onDelete: ReferentialAction.Cascade); }); + migrationBuilder.CreateTable( + name: "DocsDocumentContributors", + columns: table => new + { + DocumentId = table.Column(nullable: false), + Username = table.Column(nullable: false), + UserProfileUrl = table.Column(nullable: true), + AvatarUrl = table.Column(nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_DocsDocumentContributors", x => new { x.DocumentId, x.Username }); + table.ForeignKey( + name: "FK_DocsDocumentContributors_DocsDocuments_DocumentId", + column: x => x.DocumentId, + principalTable: "DocsDocuments", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + migrationBuilder.CreateIndex( name: "IX_AbpPermissionGrants_Name_ProviderName_ProviderKey", table: "AbpPermissionGrants", @@ -325,6 +373,9 @@ namespace VoloDocs.EntityFrameworkCore.Migrations migrationBuilder.DropTable( name: "AbpUserTokens"); + migrationBuilder.DropTable( + name: "DocsDocumentContributors"); + migrationBuilder.DropTable( name: "DocsProjects"); @@ -333,6 +384,9 @@ namespace VoloDocs.EntityFrameworkCore.Migrations migrationBuilder.DropTable( name: "AbpUsers"); + + migrationBuilder.DropTable( + name: "DocsDocuments"); } } } diff --git a/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/VoloDocsDbContextModelSnapshot.cs b/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/VoloDocsDbContextModelSnapshot.cs index 0a93515c64..0780f28624 100644 --- a/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/VoloDocsDbContextModelSnapshot.cs +++ b/modules/docs/app/VoloDocs.EntityFrameworkCore/Migrations/VoloDocsDbContextModelSnapshot.cs @@ -15,42 +15,52 @@ namespace VoloDocs.EntityFrameworkCore.Migrations { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "2.1.1-rtm-30846") + .HasAnnotation("ProductVersion", "3.1.1") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Volo.Abp.Identity.IdentityClaimType", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); b.Property("ConcurrencyStamp") .IsConcurrencyToken() .IsRequired() .HasColumnName("ConcurrencyStamp") + .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property("Description") + .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property("ExtraProperties") - .HasColumnName("ExtraProperties"); + .HasColumnName("ExtraProperties") + .HasColumnType("nvarchar(max)"); - b.Property("IsStatic"); + b.Property("IsStatic") + .HasColumnType("bit"); b.Property("Name") .IsRequired() + .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property("Regex") + .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property("RegexDescription") + .HasColumnType("nvarchar(128)") .HasMaxLength(128); - b.Property("Required"); + b.Property("Required") + .HasColumnType("bit"); - b.Property("ValueType"); + b.Property("ValueType") + .HasColumnType("int"); b.HasKey("Id"); @@ -60,35 +70,44 @@ namespace VoloDocs.EntityFrameworkCore.Migrations modelBuilder.Entity("Volo.Abp.Identity.IdentityRole", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); b.Property("ConcurrencyStamp") .IsConcurrencyToken() .IsRequired() .HasColumnName("ConcurrencyStamp") + .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property("ExtraProperties") - .HasColumnName("ExtraProperties"); + .HasColumnName("ExtraProperties") + .HasColumnType("nvarchar(max)"); b.Property("IsDefault") - .HasColumnName("IsDefault"); + .HasColumnName("IsDefault") + .HasColumnType("bit"); b.Property("IsPublic") - .HasColumnName("IsPublic"); + .HasColumnName("IsPublic") + .HasColumnType("bit"); b.Property("IsStatic") - .HasColumnName("IsStatic"); + .HasColumnName("IsStatic") + .HasColumnType("bit"); b.Property("Name") .IsRequired() + .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property("NormalizedName") .IsRequired() + .HasColumnType("nvarchar(256)") .HasMaxLength(256); - b.Property("TenantId"); + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); b.HasKey("Id"); @@ -100,18 +119,22 @@ namespace VoloDocs.EntityFrameworkCore.Migrations modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .HasColumnType("uniqueidentifier"); b.Property("ClaimType") .IsRequired() + .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property("ClaimValue") + .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); - b.Property("RoleId"); + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); - b.Property("TenantId"); + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); b.HasKey("Id"); @@ -123,105 +146,133 @@ namespace VoloDocs.EntityFrameworkCore.Migrations modelBuilder.Entity("Volo.Abp.Identity.IdentityUser", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); b.Property("AccessFailedCount") .ValueGeneratedOnAdd() .HasColumnName("AccessFailedCount") + .HasColumnType("int") .HasDefaultValue(0); b.Property("ConcurrencyStamp") .IsConcurrencyToken() - .HasColumnName("ConcurrencyStamp"); + .HasColumnName("ConcurrencyStamp") + .HasColumnType("nvarchar(max)"); b.Property("CreationTime") - .HasColumnName("CreationTime"); + .HasColumnName("CreationTime") + .HasColumnType("datetime2"); b.Property("CreatorId") - .HasColumnName("CreatorId"); + .HasColumnName("CreatorId") + .HasColumnType("uniqueidentifier"); b.Property("DeleterId") - .HasColumnName("DeleterId"); + .HasColumnName("DeleterId") + .HasColumnType("uniqueidentifier"); b.Property("DeletionTime") - .HasColumnName("DeletionTime"); + .HasColumnName("DeletionTime") + .HasColumnType("datetime2"); b.Property("Email") + .IsRequired() .HasColumnName("Email") + .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property("EmailConfirmed") .ValueGeneratedOnAdd() .HasColumnName("EmailConfirmed") + .HasColumnType("bit") .HasDefaultValue(false); b.Property("ExtraProperties") - .HasColumnName("ExtraProperties"); + .HasColumnName("ExtraProperties") + .HasColumnType("nvarchar(max)"); b.Property("IsDeleted") .ValueGeneratedOnAdd() .HasColumnName("IsDeleted") + .HasColumnType("bit") .HasDefaultValue(false); b.Property("LastModificationTime") - .HasColumnName("LastModificationTime"); + .HasColumnName("LastModificationTime") + .HasColumnType("datetime2"); b.Property("LastModifierId") - .HasColumnName("LastModifierId"); + .HasColumnName("LastModifierId") + .HasColumnType("uniqueidentifier"); b.Property("LockoutEnabled") .ValueGeneratedOnAdd() .HasColumnName("LockoutEnabled") + .HasColumnType("bit") .HasDefaultValue(false); - b.Property("LockoutEnd"); + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); b.Property("Name") .HasColumnName("Name") + .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property("NormalizedEmail") + .IsRequired() .HasColumnName("NormalizedEmail") + .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property("NormalizedUserName") .IsRequired() .HasColumnName("NormalizedUserName") + .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property("PasswordHash") .HasColumnName("PasswordHash") + .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property("PhoneNumber") .HasColumnName("PhoneNumber") + .HasColumnType("nvarchar(16)") .HasMaxLength(16); b.Property("PhoneNumberConfirmed") .ValueGeneratedOnAdd() .HasColumnName("PhoneNumberConfirmed") + .HasColumnType("bit") .HasDefaultValue(false); b.Property("SecurityStamp") .IsRequired() .HasColumnName("SecurityStamp") + .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property("Surname") .HasColumnName("Surname") + .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property("TenantId") - .HasColumnName("TenantId"); + .HasColumnName("TenantId") + .HasColumnType("uniqueidentifier"); b.Property("TwoFactorEnabled") .ValueGeneratedOnAdd() .HasColumnName("TwoFactorEnabled") + .HasColumnType("bit") .HasDefaultValue(false); b.Property("UserName") .IsRequired() .HasColumnName("UserName") + .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); @@ -240,18 +291,22 @@ namespace VoloDocs.EntityFrameworkCore.Migrations modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .HasColumnType("uniqueidentifier"); b.Property("ClaimType") .IsRequired() + .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property("ClaimValue") + .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); - b.Property("TenantId"); + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); - b.Property("UserId"); + b.Property("UserId") + .HasColumnType("uniqueidentifier"); b.HasKey("Id"); @@ -262,19 +317,24 @@ namespace VoloDocs.EntityFrameworkCore.Migrations modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => { - b.Property("UserId"); + b.Property("UserId") + .HasColumnType("uniqueidentifier"); b.Property("LoginProvider") + .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property("ProviderKey") .IsRequired() + .HasColumnType("nvarchar(196)") .HasMaxLength(196); - b.Property("TenantId"); + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); b.HasKey("UserId", "LoginProvider"); @@ -285,11 +345,14 @@ namespace VoloDocs.EntityFrameworkCore.Migrations modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => { - b.Property("UserId"); + b.Property("UserId") + .HasColumnType("uniqueidentifier"); - b.Property("RoleId"); + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); - b.Property("TenantId"); + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); b.HasKey("UserId", "RoleId"); @@ -300,17 +363,22 @@ namespace VoloDocs.EntityFrameworkCore.Migrations modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => { - b.Property("UserId"); + b.Property("UserId") + .HasColumnType("uniqueidentifier"); b.Property("LoginProvider") + .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property("Name") + .HasColumnType("nvarchar(128)") .HasMaxLength(128); - b.Property("TenantId"); + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); - b.Property("Value"); + b.Property("Value") + .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); @@ -320,21 +388,26 @@ namespace VoloDocs.EntityFrameworkCore.Migrations modelBuilder.Entity("Volo.Abp.PermissionManagement.PermissionGrant", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); b.Property("Name") .IsRequired() + .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property("ProviderKey") .IsRequired() + .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property("ProviderName") .IsRequired() + .HasColumnType("nvarchar(64)") .HasMaxLength(64); - b.Property("TenantId"); + b.Property("TenantId") + .HasColumnType("uniqueidentifier"); b.HasKey("Id"); @@ -346,20 +419,25 @@ namespace VoloDocs.EntityFrameworkCore.Migrations modelBuilder.Entity("Volo.Abp.SettingManagement.Setting", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); b.Property("Name") .IsRequired() + .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property("ProviderKey") + .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property("ProviderName") + .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property("Value") .IsRequired() + .HasColumnType("nvarchar(2048)") .HasMaxLength(2048); b.HasKey("Id"); @@ -369,43 +447,155 @@ namespace VoloDocs.EntityFrameworkCore.Migrations b.ToTable("AbpSettings"); }); + modelBuilder.Entity("Volo.Docs.Documents.Document", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnName("ConcurrencyStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("EditLink") + .HasColumnType("nvarchar(2048)") + .HasMaxLength(2048); + + b.Property("ExtraProperties") + .HasColumnName("ExtraProperties") + .HasColumnType("nvarchar(max)"); + + b.Property("FileName") + .IsRequired() + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("Format") + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("LanguageCode") + .IsRequired() + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("LastCachedTime") + .HasColumnType("datetime2"); + + b.Property("LastUpdatedTime") + .HasColumnType("datetime2"); + + b.Property("LocalDirectory") + .HasColumnType("nvarchar(512)") + .HasMaxLength(512); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(255)") + .HasMaxLength(255); + + b.Property("ProjectId") + .HasColumnType("uniqueidentifier"); + + b.Property("RawRootUrl") + .HasColumnType("nvarchar(2048)") + .HasMaxLength(2048); + + b.Property("RootUrl") + .HasColumnType("nvarchar(2048)") + .HasMaxLength(2048); + + b.Property("Version") + .IsRequired() + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.HasKey("Id"); + + b.ToTable("DocsDocuments"); + }); + + modelBuilder.Entity("Volo.Docs.Documents.DocumentContributor", b => + { + b.Property("DocumentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Username") + .HasColumnType("nvarchar(450)"); + + b.Property("AvatarUrl") + .HasColumnType("nvarchar(max)"); + + b.Property("UserProfileUrl") + .HasColumnType("nvarchar(max)"); + + b.HasKey("DocumentId", "Username"); + + b.ToTable("DocsDocumentContributors"); + }); + modelBuilder.Entity("Volo.Docs.Projects.Project", b => { b.Property("Id") - .ValueGeneratedOnAdd(); + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); b.Property("ConcurrencyStamp") .IsConcurrencyToken() - .HasColumnName("ConcurrencyStamp"); + .HasColumnName("ConcurrencyStamp") + .HasColumnType("nvarchar(max)"); b.Property("DefaultDocumentName") .IsRequired() + .HasColumnType("nvarchar(128)") .HasMaxLength(128); - b.Property("DocumentStoreType"); + b.Property("DocumentStoreType") + .HasColumnType("nvarchar(max)"); b.Property("ExtraProperties") - .HasColumnName("ExtraProperties"); + .HasColumnName("ExtraProperties") + .HasColumnType("nvarchar(max)"); - b.Property("Format"); + b.Property("Format") + .HasColumnType("nvarchar(max)"); b.Property("LatestVersionBranchName") + .HasColumnType("nvarchar(128)") .HasMaxLength(128); - b.Property("MainWebsiteUrl"); + b.Property("MainWebsiteUrl") + .HasColumnType("nvarchar(max)"); - b.Property("MinimumVersion"); + b.Property("MinimumVersion") + .HasColumnType("nvarchar(max)"); b.Property("Name") .IsRequired() + .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property("NavigationDocumentName") .IsRequired() + .HasColumnType("nvarchar(128)") + .HasMaxLength(128); + + b.Property("ParametersDocumentName") + .IsRequired() + .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property("ShortName") .IsRequired() + .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); @@ -415,47 +605,62 @@ namespace VoloDocs.EntityFrameworkCore.Migrations modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => { - b.HasOne("Volo.Abp.Identity.IdentityRole") + b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany("Claims") .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => { - b.HasOne("Volo.Abp.Identity.IdentityUser") + b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Claims") .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => { - b.HasOne("Volo.Abp.Identity.IdentityUser") + b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Logins") .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => { - b.HasOne("Volo.Abp.Identity.IdentityRole") + b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); - b.HasOne("Volo.Abp.Identity.IdentityUser") + b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Roles") .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => { - b.HasOne("Volo.Abp.Identity.IdentityUser") + b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Tokens") .HasForeignKey("UserId") - .OnDelete(DeleteBehavior.Cascade); + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Volo.Docs.Documents.DocumentContributor", b => + { + b.HasOne("Volo.Docs.Documents.Document", null) + .WithMany("Contributors") + .HasForeignKey("DocumentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); }); #pragma warning restore 612, 618 } diff --git a/modules/docs/app/VoloDocs.Web/VoloDocs.Web.csproj b/modules/docs/app/VoloDocs.Web/VoloDocs.Web.csproj index a4243c1701..3cc24371b8 100644 --- a/modules/docs/app/VoloDocs.Web/VoloDocs.Web.csproj +++ b/modules/docs/app/VoloDocs.Web/VoloDocs.Web.csproj @@ -1,4 +1,4 @@ - + @@ -19,6 +19,10 @@ + + all + runtime; build; native; contentfiles; analyzers + @@ -34,6 +38,7 @@ + diff --git a/modules/docs/app/VoloDocs.Web/VoloDocsWebModule.cs b/modules/docs/app/VoloDocs.Web/VoloDocsWebModule.cs index 3e37206f31..d46ae6e021 100644 --- a/modules/docs/app/VoloDocs.Web/VoloDocsWebModule.cs +++ b/modules/docs/app/VoloDocs.Web/VoloDocsWebModule.cs @@ -31,6 +31,7 @@ using VoloDocs.EntityFrameworkCore; using Localization.Resources.AbpUi; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Hosting; +using Volo.Abp.Account; using Volo.Abp.Validation.Localization; namespace VoloDocs.Web @@ -43,6 +44,7 @@ namespace VoloDocs.Web typeof(VoloDocsEntityFrameworkCoreModule), typeof(AbpAutofacModule), typeof(AbpAccountWebModule), + typeof(AbpAccountApplicationModule), typeof(AbpIdentityWebModule), typeof(AbpIdentityApplicationModule), typeof(AbpPermissionManagementDomainIdentityModule), @@ -142,6 +144,12 @@ namespace VoloDocs.Web var env = context.GetEnvironment(); app.UseVirtualFiles(); + app.UseRouting(); + + app.UseAuthentication(); + app.UseAuthorization(); + + app.UseAbpRequestLocalization(); app.UseSwagger(); app.UseSwaggerUI(options => @@ -149,24 +157,11 @@ namespace VoloDocs.Web options.SwaggerEndpoint("/swagger/v1/swagger.json", "Support APP API"); }); - app.UseAuthentication(); - - app.UseAbpRequestLocalization(); - app.UseStatusCodePagesWithReExecute("/error/{0}"); //app.UseMiddleware(); - app.UseMvc(routes => - { - routes.MapRoute( - name: "defaultWithArea", - template: "{area}/{controller=Home}/{action=Index}/{id?}"); - - routes.MapRoute( - name: "default", - template: "{controller=Home}/{action=Index}/{id?}"); - }); + app.UseMvcWithDefaultRouteAndArea(); using (var scope = context.ServiceProvider.CreateScope()) { diff --git a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/DocsAdminPermissionDefinitionProvider.cs b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/DocsAdminPermissionDefinitionProvider.cs index 9ad0411d15..c7bb12e3bb 100644 --- a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/DocsAdminPermissionDefinitionProvider.cs +++ b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/DocsAdminPermissionDefinitionProvider.cs @@ -14,6 +14,9 @@ namespace Volo.Docs.Admin projects.AddChild(DocsAdminPermissions.Projects.Update, L("Permission:Edit")); projects.AddChild(DocsAdminPermissions.Projects.Delete, L("Permission:Delete")); projects.AddChild(DocsAdminPermissions.Projects.Create, L("Permission:Create")); + + group.AddPermission(DocsAdminPermissions.Documents.Default, L("Permission:Documents")); + } private static LocalizableString L(string name) diff --git a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/DocsAdminPermissions.cs b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/DocsAdminPermissions.cs index 341f4c5819..26c1c46254 100644 --- a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/DocsAdminPermissions.cs +++ b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/DocsAdminPermissions.cs @@ -14,6 +14,12 @@ namespace Volo.Docs.Admin public const string Create = Default + ".Create"; } + public static class Documents + { + public const string Default = GroupName + ".Documents"; + } + + public static string[] GetAll() { return ReflectionHelper.GetPublicConstantsRecursively(typeof(DocsAdminPermissions)); diff --git a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Documents/IDocumentAdminAppService.cs b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Documents/IDocumentAdminAppService.cs new file mode 100644 index 0000000000..6adab29c74 --- /dev/null +++ b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Documents/IDocumentAdminAppService.cs @@ -0,0 +1,12 @@ +using System.Threading.Tasks; +using Volo.Abp.Application.Services; + +namespace Volo.Docs.Admin.Documents +{ + public interface IDocumentAdminAppService : IApplicationService + { + Task PullAllAsync(PullAllDocumentInput input); + + Task PullAsync(PullDocumentInput input); + } +} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Documents/PullAllDocumentInput.cs b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Documents/PullAllDocumentInput.cs new file mode 100644 index 0000000000..d796c00e64 --- /dev/null +++ b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Documents/PullAllDocumentInput.cs @@ -0,0 +1,17 @@ +using System; +using System.ComponentModel.DataAnnotations; +using Volo.Docs.Documents; + +namespace Volo.Docs.Admin.Documents +{ + public class PullAllDocumentInput + { + public Guid ProjectId { get; set; } + + [StringLength(DocumentConsts.MaxLanguageCodeNameLength)] + public string LanguageCode { get; set; } + + [StringLength(DocumentConsts.MaxVersionNameLength)] + public string Version { get; set; } + } +} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Documents/PullDocumentInput.cs b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Documents/PullDocumentInput.cs new file mode 100644 index 0000000000..fcc9816b02 --- /dev/null +++ b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Documents/PullDocumentInput.cs @@ -0,0 +1,20 @@ +using System; +using System.ComponentModel.DataAnnotations; +using Volo.Docs.Documents; + +namespace Volo.Docs.Admin.Documents +{ + public class PullDocumentInput + { + public Guid ProjectId { get; set; } + + [StringLength(DocumentConsts.MaxNameLength)] + public string Name { get; set; } + + [StringLength(DocumentConsts.MaxLanguageCodeNameLength)] + public string LanguageCode { get; set; } + + [StringLength(DocumentConsts.MaxVersionNameLength)] + public string Version { get; set; } + } +} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/en.json b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/en.json index 58cff5aa2e..708088b6a6 100644 --- a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/en.json +++ b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/en.json @@ -6,11 +6,13 @@ "Permission:Edit": "Edit", "Permission:Delete": "Delete", "Permission:Create": "Create", + "Permission:Documents": "Documents", "Menu:DocumentManagement": "Documents", "Menu:ProjectManagement": "Projects", "CreateANewProject": "Create new project", "Edit": "Edit", "Create": "Create", + "Pull": "Pull", "Projects": "Projects", "Name": "Name", "ShortName": "ShortName", @@ -27,6 +29,9 @@ "DisplayName:LatestVersionBranchName": "Latest version branch name", "DisplayName:GitHubRootUrl": "GitHub root URL", "DisplayName:GitHubAccessToken": "GitHub access token", - "DisplayName:GitHubUserAgent": "GitHub user agent" + "DisplayName:GitHubUserAgent": "GitHub user agent", + "DisplayName:All": "Pull all", + "DisplayName:LanguageCode": "Language code", + "DisplayName:Version": "Version" } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/tr.json b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/tr.json index 8c31fb1c5a..c40893e538 100644 --- a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/tr.json +++ b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/tr.json @@ -6,11 +6,13 @@ "Permission:Edit": "Düzenle", "Permission:Delete": "Sil", "Permission:Create": "Oluştur", + "Permission:Documents": "Döküman", "Menu:DocumentManagement": "Dökümanlar", "Menu:ProjectManagement": "Projeler", "CreateANewProject": "Yeni proje oluştur", "Edit": "Düzenle", "Create": "Yeni oluştur", + "Pull": "çekme", "Projects": "Projeler", "Name": "İsim", "ShortName": "Kısa isim", @@ -26,6 +28,9 @@ "DisplayName:MainWebsiteUrl": "Ana web site URL", "DisplayName:LatestVersionBranchName": "Son versiyon Branch adı", "DisplayName:GitHubRootUrl": "GitHub kök adresi", - "DisplayName:GitHubAccessToken": "GitHub erişim token" + "DisplayName:GitHubAccessToken": "GitHub erişim token", + "DisplayName:All": "Çekme bütün", + "DisplayName:LanguageCode": "Dil kodu", + "DisplayName:Version": "versiyon" } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/zh-Hans.json b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/zh-Hans.json index 3c540e8154..039be20995 100644 --- a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/zh-Hans.json +++ b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/zh-Hans.json @@ -6,11 +6,13 @@ "Permission:Edit": "编辑", "Permission:Delete": "删除", "Permission:Create": "创建", + "Permission:Documents": "文档", "Menu:DocumentManagement": "文档", "Menu:ProjectManagement": "项目", "CreateANewProject": "创建新项目", "Edit": "编辑", "Create": "创建", + "Pull": "拉取", "Projects": "项目", "Name": "名称", "ShortName": "简称", @@ -27,6 +29,9 @@ "DisplayName:LatestVersionBranchName": "最新版本的分支名称", "DisplayName:GitHubRootUrl": "GitHub根网址", "DisplayName:GitHubAccessToken": "GitHub访问令牌", - "DisplayName:GitHubUserAgent": "GitHub用户代理" + "DisplayName:GitHubUserAgent": "GitHub用户代理", + "DisplayName:All": "拉取所有", + "DisplayName:LanguageCode": "语言代码", + "DisplayName:Version": "版本" } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/zh-Hant.json b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/zh-Hant.json index 0a8415ccad..910194094d 100644 --- a/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/zh-Hant.json +++ b/modules/docs/src/Volo.Docs.Admin.Application.Contracts/Volo/Docs/Admin/Localization/Resources/Docs/ApplicationContracts/zh-Hant.json @@ -6,11 +6,13 @@ "Permission:Edit": "編輯", "Permission:Delete": "刪除", "Permission:Create": "建立", + "Permission:Documents": "文件", "Menu:DocumentManagement": "文件管理", "Menu:ProjectManagement": "專案管理", "CreateANewProject": "建立新專案", "Edit": "編輯", "Create": "建立", + "Pull": "拉取", "Projects": "專案", "Name": "名稱", "ShortName": "簡稱", @@ -27,6 +29,9 @@ "DisplayName:LatestVersionBranchName": "最新版本的分支名稱", "DisplayName:GitHubRootUrl": "GitHub根網址", "DisplayName:GitHubAccessToken": "GitHub 存取Token ", - "DisplayName:GitHubUserAgent": "GitHub 使用者代理" + "DisplayName:GitHubUserAgent": "GitHub 使用者代理", + "DisplayName:All": "拉取所有", + "DisplayName:LanguageCode": "語言代碼", + "DisplayName:Version": "版本" } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Admin.Application/Volo/Docs/Admin/Documents/DocumentAdminAppService.cs b/modules/docs/src/Volo.Docs.Admin.Application/Volo/Docs/Admin/Documents/DocumentAdminAppService.cs new file mode 100644 index 0000000000..255fed246f --- /dev/null +++ b/modules/docs/src/Volo.Docs.Admin.Application/Volo/Docs/Admin/Documents/DocumentAdminAppService.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Newtonsoft.Json; +using Volo.Abp.Application.Services; +using Volo.Abp.Caching; +using Volo.Docs.Documents; +using Volo.Docs.Projects; + +namespace Volo.Docs.Admin.Documents +{ + [Authorize(DocsAdminPermissions.Documents.Default)] + public class DocumentAdminAppService : ApplicationService, IDocumentAdminAppService + { + private readonly IProjectRepository _projectRepository; + private readonly IDocumentRepository _documentRepository; + private readonly IDocumentSourceFactory _documentStoreFactory; + private readonly IDistributedCache _documentUpdateCache; + + public DocumentAdminAppService(IProjectRepository projectRepository, + IDocumentRepository documentRepository, + IDocumentSourceFactory documentStoreFactory, + IDistributedCache documentUpdateCache) + { + _projectRepository = projectRepository; + _documentRepository = documentRepository; + _documentStoreFactory = documentStoreFactory; + _documentUpdateCache = documentUpdateCache; + } + + public async Task PullAllAsync(PullAllDocumentInput input) + { + var project = await _projectRepository.GetAsync(input.ProjectId); + + var navigationFile = await GetDocumentAsync( + project, + project.NavigationDocumentName, + input.LanguageCode, + input.Version + ); + + var nav = JsonConvert.DeserializeObject(navigationFile.Content); + var leafs = nav.Items.GetAllNodes(x => x.Items) + .Where(x => x.IsLeaf && !x.Path.IsNullOrWhiteSpace()) + .ToList(); + + var source = _documentStoreFactory.Create(project.DocumentStoreType); + + var documents = new List(); + foreach (var leaf in leafs) + { + var sourceDocument = + await source.GetDocumentAsync(project, leaf.Path, input.LanguageCode, input.Version); + documents.Add(sourceDocument); + } + + foreach (var document in documents) + { + await _documentRepository.DeleteAsync(document.ProjectId, document.Name, + document.LanguageCode, + document.Version); + + await _documentRepository.InsertAsync(document, true); + await UpdateDocumentUpdateInfoCache(document); + } + } + + public async Task PullAsync(PullDocumentInput input) + { + var project = await _projectRepository.GetAsync(input.ProjectId); + + var source = _documentStoreFactory.Create(project.DocumentStoreType); + var sourceDocument = await source.GetDocumentAsync(project, input.Name, input.LanguageCode, input.Version); + + await _documentRepository.DeleteAsync(sourceDocument.ProjectId, sourceDocument.Name, + sourceDocument.LanguageCode, sourceDocument.Version); + await _documentRepository.InsertAsync(sourceDocument, true); + await UpdateDocumentUpdateInfoCache(sourceDocument); + } + + private async Task UpdateDocumentUpdateInfoCache(Document document) + { + var cacheKey = $"DocumentUpdateInfo{document.ProjectId}#{document.Name}#{document.LanguageCode}#{document.Version}"; + await _documentUpdateCache.SetAsync(cacheKey, new DocumentUpdateInfo + { + Name = document.Name, + CreationTime = document.CreationTime, + LastUpdatedTime = document.LastUpdatedTime + }); + } + + private async Task GetDocumentAsync( + Project project, + string documentName, + string languageCode, + string version) + { + version = string.IsNullOrWhiteSpace(version) ? project.LatestVersionBranchName : version; + var source = _documentStoreFactory.Create(project.DocumentStoreType); + var document = await source.GetDocumentAsync(project, documentName, languageCode, version); + return document; + } + } +} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Admin.HttpApi/Volo/Docs/Admin/DocumentsAdminController.cs b/modules/docs/src/Volo.Docs.Admin.HttpApi/Volo/Docs/Admin/DocumentsAdminController.cs new file mode 100644 index 0000000000..75f610d3e5 --- /dev/null +++ b/modules/docs/src/Volo.Docs.Admin.HttpApi/Volo/Docs/Admin/DocumentsAdminController.cs @@ -0,0 +1,36 @@ +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Volo.Abp; +using Volo.Abp.AspNetCore.Mvc; +using Volo.Docs.Admin.Documents; + +namespace Volo.Docs.Admin +{ + [RemoteService] + [Area("docs")] + [ControllerName("DocumentsAdmin")] + [Route("api/docs/admin/documents")] + public class DocumentsAdminController : AbpController, IDocumentAdminAppService + { + private readonly IDocumentAdminAppService _documentAdminAppService; + + public DocumentsAdminController(IDocumentAdminAppService documentAdminAppService) + { + _documentAdminAppService = documentAdminAppService; + } + + [HttpPost] + [Route("PullAll")] + public Task PullAllAsync(PullAllDocumentInput input) + { + return _documentAdminAppService.PullAllAsync(input); + } + + [HttpPost] + [Route("Pull")] + public Task PullAsync(PullDocumentInput input) + { + return _documentAdminAppService.PullAsync(input); + } + } +} diff --git a/modules/docs/src/Volo.Docs.Admin.Web/DocsAdminWebAutoMapperProfile.cs b/modules/docs/src/Volo.Docs.Admin.Web/DocsAdminWebAutoMapperProfile.cs index 9bf81c2140..ca430cdaad 100644 --- a/modules/docs/src/Volo.Docs.Admin.Web/DocsAdminWebAutoMapperProfile.cs +++ b/modules/docs/src/Volo.Docs.Admin.Web/DocsAdminWebAutoMapperProfile.cs @@ -1,5 +1,6 @@ using AutoMapper; using Volo.Abp.AutoMapper; +using Volo.Docs.Admin.Documents; using Volo.Docs.Admin.Pages.Docs.Admin.Projects; using Volo.Docs.Admin.Projects; @@ -15,6 +16,9 @@ namespace Volo.Docs.Admin CreateMap () .Ignore(x => x.GitHubAccessToken).Ignore(x => x.GitHubRootUrl).Ignore(x => x.GitHubUserAgent); + + CreateMap(); + CreateMap(); } } } diff --git a/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/Index.cshtml b/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/Index.cshtml index a72506d978..e3c0416b6d 100644 --- a/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/Index.cshtml +++ b/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/Index.cshtml @@ -20,6 +20,7 @@ + } diff --git a/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/Pull.cshtml b/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/Pull.cshtml new file mode 100644 index 0000000000..6257971669 --- /dev/null +++ b/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/Pull.cshtml @@ -0,0 +1,22 @@ +@page +@using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Modal +@using Volo.Docs.Admin.Pages.Docs.Admin.Projects +@inherits Volo.Docs.Admin.Pages.Docs.Admin.DocsAdminPage +@model Volo.Docs.Admin.Pages.Docs.Admin.Projects.PullModel +@{ + Layout = null; +} + +@if (Model.PullDocument != null) +{ + + + + + + + + + + +} diff --git a/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/Pull.cshtml.cs b/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/Pull.cshtml.cs new file mode 100644 index 0000000000..dd1b5c2ac9 --- /dev/null +++ b/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/Pull.cshtml.cs @@ -0,0 +1,75 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Volo.Docs.Admin.Documents; +using Volo.Docs.Admin.Projects; +using Volo.Docs.Documents; + +namespace Volo.Docs.Admin.Pages.Docs.Admin.Projects +{ + public class PullModel : DocsAdminPageModel + { + [BindProperty] + public PullDocumentViewModel PullDocument { get; set; } + + private readonly IProjectAdminAppService _projectAppService; + private readonly IDocumentAdminAppService _documentAppService; + + public PullModel(IProjectAdminAppService projectAppService, + IDocumentAdminAppService documentAppService) + { + _projectAppService = projectAppService; + _documentAppService = documentAppService; + } + + public async Task OnGetAsync(Guid id) + { + var project = await _projectAppService.GetAsync(id); + + PullDocument = new PullDocumentViewModel() + { + ProjectId = project.Id, + All = false + }; + + return Page(); + } + + public async Task OnPostAsync() + { + if (PullDocument.All) + { + await _documentAppService.PullAllAsync( + ObjectMapper.Map(PullDocument)); + } + else + { + await _documentAppService.PullAsync( + ObjectMapper.Map(PullDocument)); + } + + return NoContent(); + } + + public class PullDocumentViewModel + { + [HiddenInput] + public Guid ProjectId { get; set; } + + public bool All { get; set; } + + [Required] + [StringLength(DocumentConsts.MaxNameLength)] + public string Name { get; set; } + + [Required] + [StringLength(DocumentConsts.MaxLanguageCodeNameLength)] + public string LanguageCode { get; set; } + + [Required] + [StringLength(DocumentConsts.MaxVersionNameLength)] + public string Version { get; set; } + } + } +} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/Pull.js b/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/Pull.js new file mode 100644 index 0000000000..8c62b5de34 --- /dev/null +++ b/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/Pull.js @@ -0,0 +1,23 @@ +var abp = abp || {}; + +$(function () { + abp.modals.projectPull = function () { + var initModal = function (publicApi, args) { + var $form = publicApi.getForm(); + var fg = $form.find("#PullDocument_Name").parent(); + var nameInput = fg.html(); + + $form.find("input:checkbox").change(function() { + if ($(this).prop("checked")) { + fg.html(""); + } else { + fg.html(nameInput); + } + }); + }; + + return { + initModal: initModal + }; + }; +}); \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/index.js b/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/index.js index d25d04d671..b843202dd9 100644 --- a/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/index.js +++ b/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Projects/index.js @@ -12,6 +12,11 @@ modalClass: 'projectEdit' }); + var _pullModal = new abp.ModalManager({ + viewUrl: abp.appPath + 'Docs/Admin/Projects/Pull', + modalClass: 'projectPull' + }); + var _dataTable = $('#ProjectsTable').DataTable(abp.libs.datatables.normalizeConfiguration({ processing: true, @@ -48,6 +53,15 @@ _dataTable.ajax.reload(); }); } + }, + { + text: l('Pull'), + visible: abp.auth.isGranted('Docs.Admin.Documents'), + action: function (data) { + _pullModal.open({ + Id: data.record.id + }); + } } ] } diff --git a/modules/docs/src/Volo.Docs.Application.Contracts/Volo/Docs/Documents/DocumentWithDetailsDto.cs b/modules/docs/src/Volo.Docs.Application.Contracts/Volo/Docs/Documents/DocumentWithDetailsDto.cs index 44b2ef6861..0364a2e26f 100644 --- a/modules/docs/src/Volo.Docs.Application.Contracts/Volo/Docs/Documents/DocumentWithDetailsDto.cs +++ b/modules/docs/src/Volo.Docs.Application.Contracts/Volo/Docs/Documents/DocumentWithDetailsDto.cs @@ -7,23 +7,31 @@ namespace Volo.Docs.Documents [Serializable] public class DocumentWithDetailsDto { - public string Title { get; set; } + public virtual string Name { get; set; } - public string Content { get; set; } + public virtual string Version { get; set; } - public string Format { get; set; } + public virtual string LanguageCode { get; set; } - public string EditLink { get; set; } + public virtual string FileName { get; set; } - public string RootUrl { get; set; } + public virtual string Content { get; set; } - public string RawRootUrl { get; set; } + public virtual string Format { get; set; } - public string Version { get; set; } + public virtual string EditLink { get; set; } - public string LocalDirectory { get; set; } + public virtual string RootUrl { get; set; } - public string FileName { get; set; } + public virtual string RawRootUrl { get; set; } + + public virtual string LocalDirectory { get; set; } + + public virtual DateTime CreationTime { get; set; } + + public virtual DateTime LastUpdatedTime { get; set; } + + public virtual DateTime LastCachedTime { get; set; } public ProjectDto Project { get; set; } diff --git a/modules/docs/src/Volo.Docs.Application.Contracts/Volo/Docs/Documents/IDocumentAppService.cs b/modules/docs/src/Volo.Docs.Application.Contracts/Volo/Docs/Documents/IDocumentAppService.cs index cfc4840824..b1195e0254 100644 --- a/modules/docs/src/Volo.Docs.Application.Contracts/Volo/Docs/Documents/IDocumentAppService.cs +++ b/modules/docs/src/Volo.Docs.Application.Contracts/Volo/Docs/Documents/IDocumentAppService.cs @@ -9,7 +9,7 @@ namespace Volo.Docs.Documents Task GetDefaultAsync(GetDefaultDocumentInput input); - Task GetNavigationAsync(GetNavigationDocumentInput input); + Task GetNavigationAsync(GetNavigationDocumentInput input); Task GetParametersAsync(GetParametersDocumentInput input); diff --git a/modules/docs/src/Volo.Docs.Application/Volo/Docs/Documents/DocumentAppService.cs b/modules/docs/src/Volo.Docs.Application/Volo/Docs/Documents/DocumentAppService.cs index 839c63860b..7ea04ec0c0 100644 --- a/modules/docs/src/Volo.Docs.Application/Volo/Docs/Documents/DocumentAppService.cs +++ b/modules/docs/src/Volo.Docs.Application/Volo/Docs/Documents/DocumentAppService.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Hosting; @@ -13,24 +14,27 @@ namespace Volo.Docs.Documents public class DocumentAppService : DocsAppServiceBase, IDocumentAppService { private readonly IProjectRepository _projectRepository; - private readonly IDocumentStoreFactory _documentStoreFactory; - protected IDistributedCache DocumentCache { get; } + private readonly IDocumentRepository _documentRepository; + private readonly IDocumentSourceFactory _documentStoreFactory; protected IDistributedCache LanguageCache { get; } protected IDistributedCache ResourceCache { get; } + protected IDistributedCache DocumentUpdateCache { get; } protected IHostEnvironment HostEnvironment { get; } public DocumentAppService( IProjectRepository projectRepository, - IDocumentStoreFactory documentStoreFactory, - IDistributedCache documentCache, + IDocumentRepository documentRepository, + IDocumentSourceFactory documentStoreFactory, IDistributedCache languageCache, IDistributedCache resourceCache, + IDistributedCache documentUpdateCache, IHostEnvironment hostEnvironment) { _projectRepository = projectRepository; + _documentRepository = documentRepository; _documentStoreFactory = documentStoreFactory; - DocumentCache = documentCache; LanguageCache = languageCache; ResourceCache = resourceCache; + DocumentUpdateCache = documentUpdateCache; HostEnvironment = hostEnvironment; } @@ -58,16 +62,35 @@ namespace Volo.Docs.Documents ); } - public virtual async Task GetNavigationAsync(GetNavigationDocumentInput input) + public virtual async Task GetNavigationAsync(GetNavigationDocumentInput input) { var project = await _projectRepository.GetAsync(input.ProjectId); - return await GetDocumentWithDetailsDtoAsync( + var navigationDocument = await GetDocumentWithDetailsDtoAsync( project, project.NavigationDocumentName, input.LanguageCode, input.Version ); + + var navigationNode = JsonConvert.DeserializeObject(navigationDocument.Content); + + var leafs = navigationNode.Items.GetAllNodes(x => x.Items) + .Where(x => !x.Path.IsNullOrWhiteSpace()) + .ToList(); + + foreach (var leaf in leafs) + { + var cacheKey = $"DocumentUpdateInfo{project.Id}#{leaf.Path}#{input.LanguageCode}#{input.Version}"; + var documentUpdateInfo = await DocumentUpdateCache.GetAsync(cacheKey); + if (documentUpdateInfo != null) + { + leaf.CreationTime = documentUpdateInfo.CreationTime; + leaf.LastUpdatedTime = documentUpdateInfo.LastUpdatedTime; + } + } + + return navigationNode; } public async Task GetResourceAsync(GetDocumentResourceInput input) @@ -78,8 +101,8 @@ namespace Volo.Docs.Documents async Task GetResourceAsync() { - var store = _documentStoreFactory.Create(project.DocumentStoreType); - var documentResource = await store.GetResource(project, input.Name, input.LanguageCode, input.Version); + var source = _documentStoreFactory.Create(project.DocumentStoreType); + var documentResource = await source.GetResource(project, input.Name, input.LanguageCode, input.Version); return ObjectMapper.Map(documentResource); } @@ -136,15 +159,27 @@ namespace Volo.Docs.Documents { version = string.IsNullOrWhiteSpace(version) ? project.LatestVersionBranchName : version; - var cacheKey = $"Document@{project.ShortName}#{languageCode}#{documentName}#{version}"; - async Task GetDocumentAsync() { - Logger.LogInformation($"Not found in the cache. Requesting {documentName} from the store..."); - var store = _documentStoreFactory.Create(project.DocumentStoreType); - var document = await store.GetDocumentAsync(project, documentName, languageCode, version); + Logger.LogInformation($"Not found in the cache. Requesting {documentName} from the source..."); + + var source = _documentStoreFactory.Create(project.DocumentStoreType); + var sourceDocument = await source.GetDocumentAsync(project, documentName, languageCode, version); + + await _documentRepository.DeleteAsync(project.Id, sourceDocument.Name, sourceDocument.LanguageCode, sourceDocument.Version); + await _documentRepository.InsertAsync(sourceDocument, true); + Logger.LogInformation($"Document retrieved: {documentName}"); - return CreateDocumentWithDetailsDto(project, document); + + var cacheKey = $"DocumentUpdateInfo{sourceDocument.ProjectId}#{sourceDocument.Name}#{sourceDocument.LanguageCode}#{sourceDocument.Version}"; + await DocumentUpdateCache.SetAsync(cacheKey, new DocumentUpdateInfo + { + Name = sourceDocument.Name, + CreationTime = sourceDocument.CreationTime, + LastUpdatedTime = sourceDocument.LastUpdatedTime + }); + + return CreateDocumentWithDetailsDto(project, sourceDocument); } if (HostEnvironment.IsDevelopment()) @@ -152,16 +187,30 @@ namespace Volo.Docs.Documents return await GetDocumentAsync(); } - return await DocumentCache.GetOrAddAsync( - cacheKey, - GetDocumentAsync, - () => new DistributedCacheEntryOptions - { - //TODO: Configurable? - AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(2), - SlidingExpiration = TimeSpan.FromMinutes(30) - } - ); + var document = await _documentRepository.FindAsync(project.Id, documentName, languageCode, version); + if (document == null) + { + return await GetDocumentAsync(); + } + + //Only the latest version (dev) of the document needs to update the cache. + if (!project.LatestVersionBranchName.IsNullOrWhiteSpace() && + document.Version == project.LatestVersionBranchName && + //TODO: Configurable cache time? + document.LastCachedTime + TimeSpan.FromHours(2) < DateTime.Now) + { + return await GetDocumentAsync(); + } + + var cacheKey = $"DocumentUpdateInfo{document.ProjectId}#{document.Name}#{document.LanguageCode}#{document.Version}"; + await DocumentUpdateCache.SetAsync(cacheKey, new DocumentUpdateInfo + { + Name = document.Name, + CreationTime = document.CreationTime, + LastUpdatedTime = document.LastUpdatedTime, + }); + + return CreateDocumentWithDetailsDto(project, document); } protected virtual DocumentWithDetailsDto CreateDocumentWithDetailsDto(Project project, Document document) @@ -171,6 +220,5 @@ namespace Volo.Docs.Documents documentDto.Contributors = ObjectMapper.Map, List>(document.Contributors); return documentDto; } - } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Application/Volo/Docs/Projects/ProjectAppService.cs b/modules/docs/src/Volo.Docs.Application/Volo/Docs/Projects/ProjectAppService.cs index 13d2ad0ced..c05857f588 100644 --- a/modules/docs/src/Volo.Docs.Application/Volo/Docs/Projects/ProjectAppService.cs +++ b/modules/docs/src/Volo.Docs.Application/Volo/Docs/Projects/ProjectAppService.cs @@ -15,18 +15,18 @@ namespace Volo.Docs.Projects { private readonly IProjectRepository _projectRepository; private readonly IDistributedCache> _versionCache; - private readonly IDocumentStoreFactory _documentStoreFactory; + private readonly IDocumentSourceFactory _documentSource; protected IDistributedCache LanguageCache { get; } public ProjectAppService( IProjectRepository projectRepository, IDistributedCache> versionCache, - IDocumentStoreFactory documentStoreFactory, + IDocumentSourceFactory documentSource, IDistributedCache languageCache) { _projectRepository = projectRepository; _versionCache = versionCache; - _documentStoreFactory = documentStoreFactory; + _documentSource = documentSource; LanguageCache = languageCache; } @@ -68,7 +68,7 @@ namespace Volo.Docs.Projects protected virtual async Task> GetVersionsAsync(Project project) { - var store = _documentStoreFactory.Create(project.DocumentStoreType); + var store = _documentSource.Create(project.DocumentStoreType); var versions = await store.GetVersionsAsync(project); if (!versions.Any()) @@ -108,7 +108,7 @@ namespace Volo.Docs.Projects private async Task GetLanguageListInternalAsync(string shortName, string version) { var project = await _projectRepository.GetByShortNameAsync(shortName); - var store = _documentStoreFactory.Create(project.DocumentStoreType); + var store = _documentSource.Create(project.DocumentStoreType); async Task GetLanguagesAsync() { diff --git a/modules/docs/src/Volo.Docs.Domain.Shared/Volo/Docs/Documents/DocumentConsts.cs b/modules/docs/src/Volo.Docs.Domain.Shared/Volo/Docs/Documents/DocumentConsts.cs index 04371e3dff..f629abd0a4 100644 --- a/modules/docs/src/Volo.Docs.Domain.Shared/Volo/Docs/Documents/DocumentConsts.cs +++ b/modules/docs/src/Volo.Docs.Domain.Shared/Volo/Docs/Documents/DocumentConsts.cs @@ -3,5 +3,13 @@ public static class DocumentConsts { public const int MaxNameLength = 255; + public const int MaxVersionNameLength = 128; + public const int MaxLanguageCodeNameLength = 128; + public const int MaxFileNameNameLength = 128; + public const int MaxFormatNameLength = 128; + public const int MaxEditLinkLength = 2048; + public const int MaxRootUrlLength = 2048; + public const int MaxRawRootUrlLength = 2048; + public const int MaxLocalDirectoryLength = 512; } } diff --git a/modules/docs/src/Volo.Docs.Domain.Shared/Volo/Docs/Documents/DocumentUpdateInfo.cs b/modules/docs/src/Volo.Docs.Domain.Shared/Volo/Docs/Documents/DocumentUpdateInfo.cs new file mode 100644 index 0000000000..fcabe91549 --- /dev/null +++ b/modules/docs/src/Volo.Docs.Domain.Shared/Volo/Docs/Documents/DocumentUpdateInfo.cs @@ -0,0 +1,14 @@ +using System; + +namespace Volo.Docs.Documents +{ + [Serializable] + public class DocumentUpdateInfo + { + public virtual string Name { get; set; } + + public virtual DateTime CreationTime { get; set; } + + public virtual DateTime LastUpdatedTime { get; set; } + } +} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Web/Models/NavigationNode.cs b/modules/docs/src/Volo.Docs.Domain.Shared/Volo/Docs/Documents/NavigationNode.cs similarity index 62% rename from modules/docs/src/Volo.Docs.Web/Models/NavigationNode.cs rename to modules/docs/src/Volo.Docs.Domain.Shared/Volo/Docs/Documents/NavigationNode.cs index c8996a4837..b5c2704eb8 100644 --- a/modules/docs/src/Volo.Docs.Web/Models/NavigationNode.cs +++ b/modules/docs/src/Volo.Docs.Domain.Shared/Volo/Docs/Documents/NavigationNode.cs @@ -22,6 +22,10 @@ namespace Volo.Docs.Documents public bool IsEmpty => Text == null && Path == null; + public virtual DateTime? CreationTime { get; set; } + + public virtual DateTime? LastUpdatedTime { get; set; } + public bool IsSelected(string documentName) { if (documentName == null) @@ -50,4 +54,24 @@ namespace Volo.Docs.Documents return false; } } + + public static class NavigationNodeExtension + { + public static IEnumerable GetAllNodes(this IEnumerable source, Func> selector) + { + if (source == null) + { + yield break; + } + + foreach (var item in source) + { + yield return item; + foreach (var subItem in GetAllNodes(selector(item), selector)) + { + yield return subItem; + } + } + } + } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainModule.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainModule.cs index 91618b950a..81f681403d 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainModule.cs +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/DocsDomainModule.cs @@ -32,10 +32,10 @@ namespace Volo.Docs .AddVirtualJson("/Volo/Docs/Localization/Domain"); }); - Configure(options => + Configure(options => { - options.Stores[GithubDocumentStore.Type] = typeof(GithubDocumentStore); - options.Stores[FileSystemDocumentStore.Type] = typeof(FileSystemDocumentStore); + options.Sources[GithubDocumentSource.Type] = typeof(GithubDocumentSource); + options.Sources[FileSystemDocumentSource.Type] = typeof(FileSystemDocumentSource); }); context.Services.AddHttpClient(GithubRepositoryManager.HttpClientName, client => diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/Document.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/Document.cs index edec595bc0..ecbc3aa617 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/Document.cs +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/Document.cs @@ -1,27 +1,110 @@ +using System; using System.Collections.Generic; +using System.Linq; +using JetBrains.Annotations; +using Volo.Abp; +using Volo.Abp.Domain.Entities; namespace Volo.Docs.Documents { - public class Document + public class Document : AggregateRoot { - public string Title { get; set; } + public virtual Guid ProjectId { get; protected set; } - public string Content { get; set; } + public virtual string Name { get; protected set; } - public string Format { get; set; } + public virtual string Version { get; protected set; } - public string EditLink { get; set; } + public virtual string LanguageCode { get; protected set; } - public string RootUrl { get; set; } + public virtual string FileName { get; set; } - public string RawRootUrl { get; set; } + public virtual string Content { get; set; } - public string Version { get; set; } + public virtual string Format { get; set; } - public string LocalDirectory { get; set; } + public virtual string EditLink { get; set; } - public string FileName { get; set; } + public virtual string RootUrl { get; set; } - public List Contributors { get; set; } + public virtual string RawRootUrl { get; set; } + + public virtual string LocalDirectory { get; set; } + + public virtual DateTime CreationTime { get; set; } + + public virtual DateTime LastUpdatedTime { get; set; } + + public virtual DateTime LastCachedTime { get; set; } + + public virtual List Contributors { get; set; } + + protected Document() + { + Contributors = new List(); + ExtraProperties = new Dictionary(); + } + + public Document( + Guid id, + Guid projectId, + [NotNull] string name, + [NotNull] string version, + [NotNull] string languageCode, + [NotNull] string fileName, + [NotNull] string content, + [NotNull] string format, + [NotNull] string editLink, + [NotNull] string rootUrl, + [NotNull] string rawRootUrl, + [NotNull] string localDirectory, + DateTime creationTime, + DateTime lastUpdatedTime, + DateTime lastCachedTime + ) + { + Id = id; + ProjectId = projectId; + + Name = Check.NotNullOrWhiteSpace(name, nameof(name)); + Version = Check.NotNullOrWhiteSpace(version, nameof(version)); + LanguageCode = Check.NotNullOrWhiteSpace(languageCode, nameof(languageCode)); + FileName = Check.NotNullOrWhiteSpace(fileName, nameof(fileName)); + Content = Check.NotNullOrWhiteSpace(content, nameof(content)); + Format = Check.NotNullOrWhiteSpace(format, nameof(format)); + EditLink = Check.NotNullOrWhiteSpace(editLink, nameof(editLink)); + RootUrl = Check.NotNullOrWhiteSpace(rootUrl, nameof(rootUrl)); + RawRootUrl = Check.NotNullOrWhiteSpace(rawRootUrl, nameof(rawRootUrl)); + LocalDirectory = Check.NotNull(localDirectory, nameof(localDirectory)); + + CreationTime = creationTime; + LastUpdatedTime = lastUpdatedTime; + LastCachedTime = lastCachedTime; + + Contributors = new List(); + ExtraProperties = new Dictionary(); + } + + public virtual void AddContributor(string username, string userProfileUrl, string avatarUrl) + { + Contributors.AddIfNotContains(new DocumentContributor(Id, username, userProfileUrl, avatarUrl)); + } + + public virtual void RemoveAllContributors() + { + Contributors.Clear(); + } + + public virtual void RemoveContributor(string username, string userProfileUrl, string avatarUrl) + { + Contributors.RemoveAll(r => + r.Username == username && r.UserProfileUrl == userProfileUrl && r.AvatarUrl == avatarUrl); + } + + public virtual DocumentContributor FindContributor(string username, string userProfileUrl, string avatarUrl) + { + return Contributors.FirstOrDefault(r => + r.Username == username && r.UserProfileUrl == userProfileUrl && r.AvatarUrl == avatarUrl); + } } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentContributor.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentContributor.cs index e405ae767c..1351b0a4ca 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentContributor.cs +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentContributor.cs @@ -1,15 +1,39 @@ using System; -using System.Collections.Generic; -using System.Text; +using Volo.Abp.Domain.Entities; namespace Volo.Docs.Documents { - public class DocumentContributor + public class DocumentContributor : Entity { + public Guid DocumentId { get; set; } + public string Username { get; set; } public string UserProfileUrl { get; set; } public string AvatarUrl { get; set; } + + protected DocumentContributor() + { + + } + + public virtual bool Equals(Guid documentId, string username) + { + return DocumentId == documentId && Username == username; + } + + public DocumentContributor(Guid documentId, string username, string userProfileUrl, string avatarUrl) + { + DocumentId = documentId; + Username = username; + UserProfileUrl = userProfileUrl; + AvatarUrl = avatarUrl; + } + + public override object[] GetKeys() + { + return new object[] { DocumentId, Username }; + } } } diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentStoreFactory.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentSourceFactory.cs similarity index 54% rename from modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentStoreFactory.cs rename to modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentSourceFactory.cs index 9e13dd2fd8..88ec294850 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentStoreFactory.cs +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentSourceFactory.cs @@ -6,28 +6,28 @@ using Volo.Abp.DependencyInjection; namespace Volo.Docs.Documents { - public class DocumentStoreFactory : IDocumentStoreFactory, ITransientDependency + public class DocumentSourceFactory : IDocumentSourceFactory, ITransientDependency { - protected DocumentStoreOptions Options { get; } + protected DocumentSourceOptions Options { get; } protected IServiceProvider ServiceProvider { get; } - public DocumentStoreFactory( + public DocumentSourceFactory( IServiceProvider serviceProvider, - IOptions options) + IOptions options) { Options = options.Value; ServiceProvider = serviceProvider; } - public virtual IDocumentStore Create(string storeType) + public virtual IDocumentSource Create(string sourceType) { - var serviceType = Options.Stores.GetOrDefault(storeType); + var serviceType = Options.Sources.GetOrDefault(sourceType); if (serviceType == null) { - throw new ApplicationException($"Unknown document store: {storeType}"); + throw new ApplicationException($"Unknown document store: {sourceType}"); } - return (IDocumentStore) ServiceProvider.GetRequiredService(serviceType); + return (IDocumentSource) ServiceProvider.GetRequiredService(serviceType); } } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentSourceOptions.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentSourceOptions.cs new file mode 100644 index 0000000000..ccfc36cbfe --- /dev/null +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentSourceOptions.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; + +namespace Volo.Docs.Documents +{ + public class DocumentSourceOptions + { + public Dictionary Sources { get; set; } + + public DocumentSourceOptions() + { + Sources = new Dictionary(); + } + } +} diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentStoreOptions.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentStoreOptions.cs deleted file mode 100644 index fcc5781d98..0000000000 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/DocumentStoreOptions.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Volo.Docs.Documents -{ - public class DocumentStoreOptions - { - public Dictionary Stores { get; set; } - - public DocumentStoreOptions() - { - Stores = new Dictionary(); - } - } -} diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentRepository.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentRepository.cs new file mode 100644 index 0000000000..75e8a22e6d --- /dev/null +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentRepository.cs @@ -0,0 +1,17 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Volo.Abp.Domain.Repositories; + +namespace Volo.Docs.Documents +{ + public interface IDocumentRepository : IBasicRepository + { + Task FindAsync(Guid projectId, string name, string languageCode, string version, + bool includeDetails = true, + CancellationToken cancellationToken = default); + + Task DeleteAsync(Guid projectId, string name, string languageCode, string version, + CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentStore.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentSource.cs similarity index 91% rename from modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentStore.cs rename to modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentSource.cs index 3cbf2c40f2..e9d2779bd3 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentStore.cs +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentSource.cs @@ -6,7 +6,7 @@ using Volo.Docs.Projects; namespace Volo.Docs.Documents { - public interface IDocumentStore : IDomainService + public interface IDocumentSource : IDomainService { Task GetDocumentAsync(Project project, string documentName, string languageCode, string version); diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentSourceFactory.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentSourceFactory.cs new file mode 100644 index 0000000000..41e5481c14 --- /dev/null +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentSourceFactory.cs @@ -0,0 +1,7 @@ +namespace Volo.Docs.Documents +{ + public interface IDocumentSourceFactory + { + IDocumentSource Create(string sourceType); + } +} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentStoreFactory.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentStoreFactory.cs deleted file mode 100644 index 3a997eb26d..0000000000 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Documents/IDocumentStoreFactory.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Volo.Docs.Documents -{ - public interface IDocumentStoreFactory - { - IDocumentStore Create(string storeType); - } -} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/FileSystem/Documents/FileSystemDocumentStore.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/FileSystem/Documents/FileSystemDocumentSource.cs similarity index 76% rename from modules/docs/src/Volo.Docs.Domain/Volo/Docs/FileSystem/Documents/FileSystemDocumentStore.cs rename to modules/docs/src/Volo.Docs.Domain/Volo/Docs/FileSystem/Documents/FileSystemDocumentSource.cs index 085ce9a917..d93b378dcd 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/FileSystem/Documents/FileSystemDocumentStore.cs +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/FileSystem/Documents/FileSystemDocumentSource.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.IO; using System.Security; using System.Threading.Tasks; @@ -11,7 +12,7 @@ using Volo.Docs.Projects; namespace Volo.Docs.FileSystem.Documents { - public class FileSystemDocumentStore : DomainService, IDocumentStore + public class FileSystemDocumentSource : DomainService, IDocumentSource { public const string Type = "FileSystem"; @@ -30,16 +31,21 @@ namespace Volo.Docs.FileSystem.Documents localDirectory = documentName.Substring(0, documentName.LastIndexOf('/')); } - return new Document - { - Content = content, - FileName = Path.GetFileName(path), - Format = project.Format, - LocalDirectory = localDirectory, - Title = documentName, - RawRootUrl = $"/document-resources?projectId={project.Id.ToString()}&version={version}&languageCode={languageCode}&name=", - RootUrl = "/" - }; + return new Document(GuidGenerator.Create(), + project.Id, + documentName, + version, + languageCode, + Path.GetFileName(path), + content, + project.Format, + path, + "/", + $"/document-resources?projectId={project.Id.ToString()}&version={version}&languageCode={languageCode}&name=", + localDirectory, + File.GetCreationTime(path), + File.GetLastWriteTime(path), + DateTime.Now); } public Task> GetVersionsAsync(Project project) diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/FileSystem/Projects/ProjectFileSystemExtensions.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/FileSystem/Projects/ProjectFileSystemExtensions.cs index 904e7b9e29..f0fc44e39e 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/FileSystem/Projects/ProjectFileSystemExtensions.cs +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/FileSystem/Projects/ProjectFileSystemExtensions.cs @@ -24,7 +24,7 @@ namespace Volo.Docs.FileSystem.Projects { Check.NotNull(project, nameof(project)); - if (project.DocumentStoreType != FileSystemDocumentStore.Type) + if (project.DocumentStoreType != FileSystemDocumentSource.Type) { throw new ApplicationException("Given project has not a FileSystem document store!"); } diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubDocumentStore.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubDocumentSource.cs similarity index 78% rename from modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubDocumentStore.cs rename to modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubDocumentSource.cs index c84772ff26..0c837991d1 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubDocumentStore.cs +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubDocumentSource.cs @@ -16,13 +16,13 @@ namespace Volo.Docs.GitHub.Documents { //TODO: Needs more refactoring - public class GithubDocumentStore : DomainService, IDocumentStore + public class GithubDocumentSource : DomainService, IDocumentSource { public const string Type = "GitHub"; private readonly IGithubRepositoryManager _githubRepositoryManager; - public GithubDocumentStore(IGithubRepositoryManager githubRepositoryManager) + public GithubDocumentSource(IGithubRepositoryManager githubRepositoryManager) { _githubRepositoryManager = githubRepositoryManager; } @@ -34,7 +34,6 @@ namespace Volo.Docs.GitHub.Documents var userAgent = project.GetGithubUserAgentOrNull(); var rawRootUrl = CalculateRawRootUrlWithLanguageCode(rootUrl, languageCode); var rawDocumentUrl = rawRootUrl + documentName; - var commitHistoryUrl = project.GetGitHubUrlForCommitHistory() + documentName; var isNavigationDocument = documentName == project.NavigationDocumentName; var isParameterDocument = documentName == project.ParametersDocumentName; var editLink = rootUrl.ReplaceFirst("/tree/", "/blob/") + languageCode + "/" + documentName; @@ -47,20 +46,40 @@ namespace Volo.Docs.GitHub.Documents fileName = documentName.Substring(documentName.LastIndexOf('/') + 1); } - return new Document + var fileCommits = await GetFileCommitsAsync(project, version, $"docs/{languageCode}/{documentName}"); + + var document= new Document(GuidGenerator.Create(), + project.Id, + documentName, + version, + languageCode, + fileName, + await DownloadWebContentAsStringAsync(rawDocumentUrl, token, userAgent), + project.Format, + editLink, + rootUrl, + rawRootUrl, + localDirectory, + fileCommits.LastOrDefault()?.Commit.Author.Date.DateTime ?? DateTime.MinValue, + fileCommits.FirstOrDefault()?.Commit.Author.Date.DateTime ?? DateTime.MinValue, + DateTime.Now); + + var authors = fileCommits + .Where(x => x.Author != null) + .Select(x => x.Author) + .GroupBy(x => x.Id) + .OrderByDescending(x => x.Count()) + .Select(x => x.FirstOrDefault()).ToList(); + + if (!isNavigationDocument && !isParameterDocument) { - Title = documentName, - EditLink = editLink, - RootUrl = rootUrl, - RawRootUrl = rawRootUrl, - Format = project.Format, - LocalDirectory = localDirectory, - FileName = fileName, - Contributors = new List(), - //Contributors = !isNavigationDocument && !isParameterDocument && !isPartialTemplatesDocumentName ? await GetContributors(commitHistoryUrl, token, userAgent): new List(), - Version = version, - Content = await DownloadWebContentAsStringAsync(rawDocumentUrl, token, userAgent) - }; + foreach (var author in authors) + { + document.AddContributor(author.Login, author.HtmlUrl, author.AvatarUrl); + } + } + + return document; } public async Task> GetVersionsAsync(Project project) @@ -124,6 +143,15 @@ namespace Volo.Docs.GitHub.Documents return await _githubRepositoryManager.GetReleasesAsync(ownerName, repositoryName, project.GetGitHubAccessTokenOrNull()); } + private async Task> GetFileCommitsAsync(Project project, string version, string filename) + { + var url = project.GetGitHubUrl(); + var ownerName = GetOwnerNameFromUrl(url); + var repositoryName = GetRepositoryNameFromUrl(url); + return await _githubRepositoryManager.GetFileCommitsAsync(ownerName, repositoryName, + version, filename, project.GetGitHubAccessTokenOrNull()); + } + protected virtual string GetOwnerNameFromUrl(string url) { try @@ -183,39 +211,6 @@ namespace Volo.Docs.GitHub.Documents } } - private async Task> GetContributors(string url, string token, string userAgent) - { - var contributors = new List(); - - try - { - var commitsJsonAsString = await DownloadWebContentAsStringAsync(url, token, userAgent); - - var commits = JArray.Parse(commitsJsonAsString); - - foreach (var commit in commits) - { - var author = commit["author"]; - - contributors.Add(new DocumentContributor - { - Username = (string)author["login"], - UserProfileUrl = (string)author["html_url"], - AvatarUrl = (string)author["avatar_url"] - }); - } - - contributors = contributors.GroupBy(c => c.Username).OrderByDescending(c=>c.Count()) - .Select( c => c.FirstOrDefault()).ToList(); - } - catch (Exception ex) - { - Logger.LogWarning(ex.Message); - } - - return contributors; - } - private static string CalculateRawRootUrlWithLanguageCode(string rootUrl, string languageCode) { return (rootUrl diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubRepositoryManager.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubRepositoryManager.cs index d19f70c2cd..787dcbba48 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubRepositoryManager.cs +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/GithubRepositoryManager.cs @@ -64,5 +64,16 @@ namespace Volo.Docs.GitHub.Documents .Release .GetAll(name, repositoryName)).ToList(); } + + public async Task> GetFileCommitsAsync(string name, string repositoryName, string version, string filename, string token) + { + var client = token.IsNullOrWhiteSpace() + ? new GitHubClient(new ProductHeaderValue(name)) + : new GitHubClient(new ProductHeaderValue(name), new InMemoryCredentialStore(new Credentials(token))); + + var repo = await client.Repository.Get(name, repositoryName); + var request = new CommitRequest { Path = filename, Sha = version }; + return await client.Repository.Commit.GetAll(repo.Id, request); + } } } diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/IGithubRepositoryManager.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/IGithubRepositoryManager.cs index 519b9829d5..fa81ba695b 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/IGithubRepositoryManager.cs +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Documents/IGithubRepositoryManager.cs @@ -15,5 +15,6 @@ namespace Volo.Docs.GitHub.Documents Task> GetReleasesAsync(string name, string repositoryName, string token); + Task> GetFileCommitsAsync(string name, string repositoryName, string version, string filename, string token); } } diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Projects/ProjectGithubExtensions.cs b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Projects/ProjectGithubExtensions.cs index 3d2170a121..d518132950 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Projects/ProjectGithubExtensions.cs +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/GitHub/Projects/ProjectGithubExtensions.cs @@ -21,14 +21,6 @@ namespace Volo.Docs.GitHub.Projects .Replace("{version}", version); } - public static string GetGitHubUrlForCommitHistory([NotNull] this Project project) - { - return project - .GetGitHubUrl() - .Replace("github.com", "api.github.com/repos") - .Replace("tree/{version}/", "commits?path="); - } - public static void SetGitHubUrl([NotNull] this Project project, string value) { CheckGitHubProject(project); @@ -57,7 +49,7 @@ namespace Volo.Docs.GitHub.Projects { Check.NotNull(project, nameof(project)); - if (project.DocumentStoreType != GithubDocumentStore.Type) + if (project.DocumentStoreType != GithubDocumentSource.Type) { throw new ApplicationException("Given project has not a Github document store!"); } diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/en.json b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/en.json index 1750f82e61..92858a87f0 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/en.json +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/en.json @@ -7,6 +7,7 @@ "ShareOn": "Share on", "Version": "Version", "Edit": "Edit", + "LastEditTime": "Last edit", "Delete": "Delete", "InThisDocument": "In this document", "GoToTop": "Go to top", @@ -16,6 +17,10 @@ "NavigationDocumentNotFound": "This version does not have a navigation document!", "DocumentNotFoundInSelectedLanguage": "Document in the language you wanted is not found. Document in the default language is shown.", "FilterTopics": "Filter topics", - "MultipleVersionDocumentInfo": "This document has multiple versions. Select the options best fit for you." + "MultipleVersionDocumentInfo": "This document has multiple versions. Select the options best fit for you.", + "New": "New", + "Upd": "Upd", + "NewExplanation": "Created in the last two weeks.", + "UpdatedExplanation": "Updated in the last two weeks." } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/tr.json b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/tr.json index 440273022f..612274f95d 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/tr.json +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/tr.json @@ -7,6 +7,7 @@ "ShareOn": "Paylaş", "Version": "Versiyon", "Edit": "Düzenle", + "LastEditTime": "Son Düzenleme", "Delete": "Sil", "InThisDocument": "Bu dökümanda", "GoToTop": "En üste çık", @@ -15,6 +16,10 @@ "DocumentNotFound": "Aradığınız döküman bulunamadı!", "NavigationDocumentNotFound": "Bu döküman için menü bulunamadı!", "DocumentNotFoundInSelectedLanguage": "İstediğiniz dilde belge bulunamadı. Varsayılan dilde belge gösterilir.", - "MultipleVersionDocumentInfo": "Bu dökümanın birden çok versiyonu bulunmaktadır. Sizin için en uygun olan seçenekleri seçiniz." + "MultipleVersionDocumentInfo": "Bu dökümanın birden çok versiyonu bulunmaktadır. Sizin için en uygun olan seçenekleri seçiniz.", + "New": "Yeni", + "Upd": "Günc", + "NewExplanation": "Son iki hafta içinde oluşturuldu.", + "UpdatedExplanation": "Son iki hafta içinde güncellendi." } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/zh-Hans.json b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/zh-Hans.json index 410374b4fd..3eec4562bb 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/zh-Hans.json +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/zh-Hans.json @@ -7,6 +7,7 @@ "ShareOn": "分享到", "Version": "版本", "Edit": "编辑", + "LastEditTime": "上次编辑", "Delete": "删除", "InThisDocument": "在本文中", "GoToTop": "到顶部", @@ -15,6 +16,10 @@ "DocumentNotFound": "找不到请求的文档!", "NavigationDocumentNotFound": "这个版本没有导航文件!", "DocumentNotFoundInSelectedLanguage": "本文档不适用于所选语言, 将以默认语言显示文档.", - "FilterTopics": "过滤主题" + "FilterTopics": "过滤主题", + "New": "新文档", + "Upd": "更新", + "NewExplanation": "在最近两周内创建.", + "UpdatedExplanation": "在最近两周内更新." } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/zh-Hant.json b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/zh-Hant.json index 34ded108f1..5c3d723b0a 100644 --- a/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/zh-Hant.json +++ b/modules/docs/src/Volo.Docs.Domain/Volo/Docs/Localization/Domain/zh-Hant.json @@ -7,6 +7,7 @@ "ShareOn": "分享到", "Version": "版本", "Edit": "編輯", + "LastEditTime": "上次編輯", "Delete": "刪除", "InThisDocument": "在此文件中", "GoToTop": "到最上方", @@ -15,6 +16,10 @@ "DocumentNotFound": "找不到要求的文件!", "NavigationDocumentNotFound": "這個版本沒有導覽文件!", "DocumentNotFoundInSelectedLanguage": "本文件不適用於所選語系,將以預設語系顯示.", - "FilterTopics": "過濾主題" + "FilterTopics": "過濾主題", + "New": "新文檔", + "Upd": "更新", + "NewExplanation": "在最近兩周內創建.", + "UpdatedExplanation": "在最近兩周內更新." } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo.Docs.EntityFrameworkCore.csproj b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo.Docs.EntityFrameworkCore.csproj index cd0dbdf97c..d8bf0d7fc6 100644 --- a/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo.Docs.EntityFrameworkCore.csproj +++ b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo.Docs.EntityFrameworkCore.csproj @@ -10,6 +10,12 @@ + + + + + + diff --git a/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/Documents/EFCoreDocumentRepository.cs b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/Documents/EFCoreDocumentRepository.cs new file mode 100644 index 0000000000..7698ef0b39 --- /dev/null +++ b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/Documents/EFCoreDocumentRepository.cs @@ -0,0 +1,36 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Volo.Abp.Domain.Repositories.EntityFrameworkCore; +using Volo.Abp.EntityFrameworkCore; +using Volo.Docs.EntityFrameworkCore; + +namespace Volo.Docs.Documents +{ + public class EFCoreDocumentRepository : EfCoreRepository, IDocumentRepository + { + public EFCoreDocumentRepository(IDbContextProvider dbContextProvider) + : base(dbContextProvider) + { + } + + public async Task FindAsync(Guid projectId, string name, string languageCode, string version, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await DbSet.IncludeDetails(includeDetails) + .FirstOrDefaultAsync(x => + x.ProjectId == projectId && x.Name == name && x.LanguageCode == languageCode && + x.Version == version, + cancellationToken); + } + + public async Task DeleteAsync(Guid projectId, string name, string languageCode, string version, CancellationToken cancellationToken = default) + { + await DeleteAsync(x => + x.ProjectId == projectId && x.Name == name && x.LanguageCode == languageCode && + x.Version == version, cancellationToken: cancellationToken); + } + } +} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsDbContext.cs b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsDbContext.cs index 1f6a43b825..7c1c635617 100644 --- a/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsDbContext.cs +++ b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsDbContext.cs @@ -1,6 +1,7 @@ using Microsoft.EntityFrameworkCore; using Volo.Abp.Data; using Volo.Abp.EntityFrameworkCore; +using Volo.Docs.Documents; using Volo.Docs.Projects; namespace Volo.Docs.EntityFrameworkCore @@ -10,6 +11,10 @@ namespace Volo.Docs.EntityFrameworkCore { public DbSet Projects { get; set; } + public DbSet Documents { get; set; } + + public DbSet DocumentContributors { get; set; } + public DocsDbContext(DbContextOptions options) : base(options) { diff --git a/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsDbContextModelBuilderExtensions.cs b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsDbContextModelBuilderExtensions.cs index f6a17b68d7..64a85db140 100644 --- a/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsDbContextModelBuilderExtensions.cs +++ b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsDbContextModelBuilderExtensions.cs @@ -3,6 +3,7 @@ using JetBrains.Annotations; using Microsoft.EntityFrameworkCore; using Volo.Abp; using Volo.Abp.EntityFrameworkCore.Modeling; +using Volo.Docs.Documents; using Volo.Docs.Projects; namespace Volo.Docs.EntityFrameworkCore @@ -26,8 +27,7 @@ namespace Volo.Docs.EntityFrameworkCore { b.ToTable(options.TablePrefix + "Projects", options.Schema); - b.ConfigureConcurrencyStamp(); - b.ConfigureExtraProperties(); + b.ConfigureByConvention(); b.Property(x => x.Name).IsRequired().HasMaxLength(ProjectConsts.MaxNameLength); b.Property(x => x.ShortName).IsRequired().HasMaxLength(ProjectConsts.MaxShortNameLength); @@ -36,6 +36,35 @@ namespace Volo.Docs.EntityFrameworkCore b.Property(x => x.ParametersDocumentName).IsRequired().HasMaxLength(ProjectConsts.MaxParametersDocumentNameLength); b.Property(x => x.LatestVersionBranchName).HasMaxLength(ProjectConsts.MaxLatestVersionBranchNameLength); }); + + builder.Entity(b => + { + b.ToTable(options.TablePrefix + "Documents", options.Schema); + + b.ConfigureByConvention(); + + b.Property(x => x.Name).IsRequired().HasMaxLength(DocumentConsts.MaxNameLength); + b.Property(x => x.Version).IsRequired().HasMaxLength(DocumentConsts.MaxVersionNameLength); + b.Property(x => x.LanguageCode).IsRequired().HasMaxLength(DocumentConsts.MaxLanguageCodeNameLength); + b.Property(x => x.FileName).IsRequired().HasMaxLength(DocumentConsts.MaxFileNameNameLength); + b.Property(x => x.Content).IsRequired(); + b.Property(x => x.Format).HasMaxLength(DocumentConsts.MaxFormatNameLength); + b.Property(x => x.EditLink).HasMaxLength(DocumentConsts.MaxEditLinkLength); + b.Property(x => x.RootUrl).HasMaxLength(DocumentConsts.MaxRootUrlLength); + b.Property(x => x.RawRootUrl).HasMaxLength(DocumentConsts.MaxRawRootUrlLength); + b.Property(x => x.LocalDirectory).HasMaxLength(DocumentConsts.MaxLocalDirectoryLength); + + b.HasMany(x => x.Contributors).WithOne() + .HasForeignKey(x => new { x.DocumentId }) + .IsRequired(); + }); + + builder.Entity(b => + { + b.ToTable(options.TablePrefix + "DocumentContributors", options.Schema); + + b.HasKey(x => new { x.DocumentId, x.Username }); + }); } } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsEfCoreQueryableExtensions.cs b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsEfCoreQueryableExtensions.cs new file mode 100644 index 0000000000..0bd2e4fff8 --- /dev/null +++ b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsEfCoreQueryableExtensions.cs @@ -0,0 +1,14 @@ +using System.Linq; +using Microsoft.EntityFrameworkCore; +using Volo.Docs.Documents; + +namespace Volo.Docs.EntityFrameworkCore +{ + public static class DocsEfCoreQueryableExtensions + { + public static IQueryable IncludeDetails(this IQueryable queryable, bool include = true) + { + return !include ? queryable : queryable.Include(x => x.Contributors); + } + } +} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsEntityFrameworkCoreModule.cs b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsEntityFrameworkCoreModule.cs index 459a96516b..6e6b780666 100644 --- a/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsEntityFrameworkCoreModule.cs +++ b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/DocsEntityFrameworkCoreModule.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.DependencyInjection; using Volo.Abp.EntityFrameworkCore; using Volo.Abp.Modularity; +using Volo.Docs.Documents; using Volo.Docs.Projects; namespace Volo.Docs.EntityFrameworkCore @@ -15,6 +16,7 @@ namespace Volo.Docs.EntityFrameworkCore context.Services.AddAbpDbContext(options => { options.AddRepository(); + options.AddRepository(); }); } } diff --git a/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/IDocsDbContext.cs b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/IDocsDbContext.cs index 4f11d438e7..6e96604592 100644 --- a/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/IDocsDbContext.cs +++ b/modules/docs/src/Volo.Docs.EntityFrameworkCore/Volo/Docs/EntityFrameworkCore/IDocsDbContext.cs @@ -1,6 +1,7 @@ using Microsoft.EntityFrameworkCore; using Volo.Abp.Data; using Volo.Abp.EntityFrameworkCore; +using Volo.Docs.Documents; using Volo.Docs.Projects; namespace Volo.Docs.EntityFrameworkCore @@ -9,5 +10,9 @@ namespace Volo.Docs.EntityFrameworkCore public interface IDocsDbContext : IEfCoreDbContext { DbSet Projects { get; set; } + + DbSet Documents { get; set; } + + DbSet DocumentContributors { get; set; } } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.HttpApi/Volo/Docs/Documents/DocsDocumentController.cs b/modules/docs/src/Volo.Docs.HttpApi/Volo/Docs/Documents/DocsDocumentController.cs index 9ff91c8b17..a066a92f23 100644 --- a/modules/docs/src/Volo.Docs.HttpApi/Volo/Docs/Documents/DocsDocumentController.cs +++ b/modules/docs/src/Volo.Docs.HttpApi/Volo/Docs/Documents/DocsDocumentController.cs @@ -34,7 +34,7 @@ namespace Volo.Docs.Documents [HttpGet] [Route("navigation")] - public virtual Task GetNavigationAsync(GetNavigationDocumentInput input) + public Task GetNavigationAsync(GetNavigationDocumentInput input) { return DocumentAppService.GetNavigationAsync(input); } diff --git a/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/Documents/MongoDocumentRepository.cs b/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/Documents/MongoDocumentRepository.cs new file mode 100644 index 0000000000..ee72171e0d --- /dev/null +++ b/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/Documents/MongoDocumentRepository.cs @@ -0,0 +1,36 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using MongoDB.Driver.Linq; +using Volo.Abp.Domain.Repositories.MongoDB; +using Volo.Abp.MongoDB; +using Volo.Docs.MongoDB; + +namespace Volo.Docs.Documents +{ + public class MongoDocumentRepository : MongoDbRepository, IDocumentRepository + { + public MongoDocumentRepository(IMongoDbContextProvider dbContextProvider) + : base(dbContextProvider) + { + } + + public async Task FindAsync(Guid projectId, string name, string languageCode, string version, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await GetMongoQueryable().FirstOrDefaultAsync(x => x.ProjectId == projectId && + x.Name == name && + x.LanguageCode == languageCode && + x.Version == version, cancellationToken); + } + + public async Task DeleteAsync(Guid projectId, string name, string languageCode, string version, + CancellationToken cancellationToken = default) + { + await DeleteAsync(x => + x.ProjectId == projectId && x.Name == name && x.LanguageCode == languageCode && + x.Version == version, cancellationToken: cancellationToken); + } + } +} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/BloggingMongoDbModule.cs b/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/BloggingMongoDbModule.cs index 68b7827b08..cc9662a1ad 100644 --- a/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/BloggingMongoDbModule.cs +++ b/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/BloggingMongoDbModule.cs @@ -2,6 +2,7 @@ using Volo.Abp.MongoDB; using Volo.Docs.Projects; using Microsoft.Extensions.DependencyInjection; +using Volo.Docs.Documents; namespace Volo.Docs.MongoDB { @@ -16,6 +17,7 @@ namespace Volo.Docs.MongoDB context.Services.AddMongoDbContext(options => { options.AddRepository(); + options.AddRepository(); }); } } diff --git a/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/DocsMongoDbContext.cs b/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/DocsMongoDbContext.cs index cc65e9ab3e..afc430c945 100644 --- a/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/DocsMongoDbContext.cs +++ b/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/DocsMongoDbContext.cs @@ -2,6 +2,7 @@ using Volo.Abp.Data; using Volo.Docs.Projects; using Volo.Abp.MongoDB; +using Volo.Docs.Documents; namespace Volo.Docs.MongoDB { @@ -9,6 +10,7 @@ namespace Volo.Docs.MongoDB public class DocsMongoDbContext : AbpMongoDbContext, IDocsMongoDbContext { public IMongoCollection Projects => Collection(); + public IMongoCollection Documents => Collection(); protected override void CreateModel(IMongoModelBuilder modelBuilder) { diff --git a/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/DocsMongoDbContextExtensions.cs b/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/DocsMongoDbContextExtensions.cs index 456070a645..c1645885d2 100644 --- a/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/DocsMongoDbContextExtensions.cs +++ b/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/DocsMongoDbContextExtensions.cs @@ -1,6 +1,7 @@ using System; using Volo.Abp; using Volo.Abp.MongoDB; +using Volo.Docs.Documents; using Volo.Docs.Projects; namespace Volo.Docs.MongoDB @@ -23,6 +24,11 @@ namespace Volo.Docs.MongoDB { b.CollectionName = options.CollectionPrefix + "Projects"; }); + + builder.Entity(b => + { + b.CollectionName = options.CollectionPrefix + "DocumentS"; + }); } } } diff --git a/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/IDocsMongoDbContext.cs b/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/IDocsMongoDbContext.cs index 78b3be8484..92c86a7c4f 100644 --- a/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/IDocsMongoDbContext.cs +++ b/modules/docs/src/Volo.Docs.MongoDB/Volo/Docs/MongoDB/IDocsMongoDbContext.cs @@ -1,6 +1,7 @@ using MongoDB.Driver; using Volo.Abp.Data; using Volo.Abp.MongoDB; +using Volo.Docs.Documents; using Volo.Docs.Projects; namespace Volo.Docs.MongoDB @@ -8,8 +9,8 @@ namespace Volo.Docs.MongoDB [ConnectionStringName(DocsDbProperties.ConnectionStringName)] public interface IDocsMongoDbContext : IAbpMongoDbContext { - IMongoCollection Projects { get; } + IMongoCollection Documents { get; } } } \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Web/Areas/Documents/TagHelpers/TreeTagHelper.cs b/modules/docs/src/Volo.Docs.Web/Areas/Documents/TagHelpers/TreeTagHelper.cs index afb61eadd3..1c57191d0a 100644 --- a/modules/docs/src/Volo.Docs.Web/Areas/Documents/TagHelpers/TreeTagHelper.cs +++ b/modules/docs/src/Volo.Docs.Web/Areas/Documents/TagHelpers/TreeTagHelper.cs @@ -2,8 +2,10 @@ using System.Linq; using System.Text; using Microsoft.AspNetCore.Razor.TagHelpers; +using Microsoft.Extensions.Localization; using Microsoft.Extensions.Options; using Volo.Docs.Documents; +using Volo.Docs.Localization; using Volo.Docs.Utils; namespace Volo.Docs.Areas.Documents.TagHelpers @@ -15,6 +17,8 @@ namespace Volo.Docs.Areas.Documents.TagHelpers { private readonly DocsUiOptions _uiOptions; + private readonly IStringLocalizer _localizer; + private const string LiItemTemplateWithLink = @"
  • {2}{3}
  • "; private const string ListItemAnchor = @"{2}"; @@ -41,8 +45,9 @@ namespace Volo.Docs.Areas.Documents.TagHelpers [HtmlAttributeName("language")] public string LanguageCode { get; set; } - public TreeTagHelper(IOptions urlOptions) + public TreeTagHelper(IOptions urlOptions, IStringLocalizer localizer) { + _localizer = localizer; _uiOptions = urlOptions.Value; } @@ -118,7 +123,27 @@ namespace Volo.Docs.Areas.Documents.TagHelpers } else { - listInnerItem = string.Format(ListItemAnchor, NormalizePath(node.Path), textCss, node.Text.IsNullOrEmpty() ? "?" : node.Text); + var badge = ""; + + if (!node.Path.IsNullOrWhiteSpace() && node.CreationTime.HasValue && node.LastUpdatedTime.HasValue) + { + var newBadge = "" + _localizer["New"] + ""; + var updBadge = "" + _localizer["Upd"] + ""; + + if(node.CreationTime + TimeSpan.FromDays(14) > DateTime.Now) + { + badge = newBadge; + } + else if (node.LastUpdatedTime + TimeSpan.FromDays(14) > DateTime.Now) + { + badge = updBadge; + } + } + + listInnerItem = string.Format(ListItemAnchor, NormalizePath(node.Path), textCss, + node.Text.IsNullOrEmpty() + ? "?" + : node.Text + badge); } return string.Format(LiItemTemplateWithLink, diff --git a/modules/docs/src/Volo.Docs.Web/DocsWebAutoMapperProfile.cs b/modules/docs/src/Volo.Docs.Web/DocsWebAutoMapperProfile.cs index 4a25c94370..a4c4c7647e 100644 --- a/modules/docs/src/Volo.Docs.Web/DocsWebAutoMapperProfile.cs +++ b/modules/docs/src/Volo.Docs.Web/DocsWebAutoMapperProfile.cs @@ -8,8 +8,7 @@ namespace Volo.Docs { public DocsWebAutoMapperProfile() { - CreateMap() - .Ignore(x => x.RootNode); + } } } diff --git a/modules/docs/src/Volo.Docs.Web/DocsWebModule.cs b/modules/docs/src/Volo.Docs.Web/DocsWebModule.cs index 13f29184a9..5b7309a310 100644 --- a/modules/docs/src/Volo.Docs.Web/DocsWebModule.cs +++ b/modules/docs/src/Volo.Docs.Web/DocsWebModule.cs @@ -5,7 +5,9 @@ using Microsoft.Extensions.Options; using Volo.Abp.AspNetCore.Mvc.Localization; using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap; using Volo.Abp.AspNetCore.Mvc.UI.Bundling; +using Volo.Abp.AspNetCore.Mvc.UI.Packages; using Volo.Abp.AspNetCore.Mvc.UI.Packages.Prismjs; +using Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared; using Volo.Abp.AutoMapper; using Volo.Abp.Modularity; using Volo.Abp.VirtualFileSystem; @@ -18,7 +20,11 @@ namespace Volo.Docs { [DependsOn( typeof(DocsHttpApiModule), - typeof(AbpAspNetCoreMvcUiBootstrapModule) + typeof(AbpAutoMapperModule), + typeof(AbpAspNetCoreMvcUiBootstrapModule), + typeof(AbpAspNetCoreMvcUiThemeSharedModule), + typeof(AbpAspNetCoreMvcUiPackagesModule), + typeof(AbpAspNetCoreMvcUiBundlingModule) )] public class DocsWebModule : AbpModule { diff --git a/modules/docs/src/Volo.Docs.Web/Models/NavigationWithDetailsDto.cs b/modules/docs/src/Volo.Docs.Web/Models/NavigationWithDetailsDto.cs deleted file mode 100644 index a85c6eeb01..0000000000 --- a/modules/docs/src/Volo.Docs.Web/Models/NavigationWithDetailsDto.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using Newtonsoft.Json; - -namespace Volo.Docs.Documents -{ - public class NavigationWithDetailsDto : DocumentWithDetailsDto - { - [JsonProperty("items")] - public NavigationNode RootNode { get; set; } - - public void ConvertItems() - { - if (Content.IsNullOrEmpty()) - { - RootNode = new NavigationNode(); - return; - } - - try - { - RootNode = JsonConvert.DeserializeObject(Content); - } - catch (JsonException ex) - { - //todo: should log the exception? - RootNode = new NavigationNode(); - } - } - } -} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Web/Pages/Documents/Project/Index.cshtml b/modules/docs/src/Volo.Docs.Web/Pages/Documents/Project/Index.cshtml index bebf083381..7029cc410a 100644 --- a/modules/docs/src/Volo.Docs.Web/Pages/Documents/Project/Index.cshtml +++ b/modules/docs/src/Volo.Docs.Web/Pages/Documents/Project/Index.cshtml @@ -1,10 +1,11 @@ -@page +@page @using Microsoft.AspNetCore.Mvc.Localization @using Volo.Abp.AspNetCore.Mvc.UI.Layout @using Volo.Abp.AspNetCore.Mvc.UI.Packages.Anchor @using Volo.Abp.AspNetCore.Mvc.UI.Packages.Clipboard @using Volo.Abp.AspNetCore.Mvc.UI.Packages.MalihuCustomScrollbar @using Volo.Abp.AspNetCore.Mvc.UI.Packages.Popper +@using Volo.Docs.Pages.Documents.Shared.DocumentNotFoundComponent @using Volo.Abp.AspNetCore.Mvc.UI.Packages.Prismjs @using Volo.Abp.AspNetCore.Mvc.UI.Theming @using Volo.Docs @@ -39,268 +40,284 @@ } -
    -
    -
    -
    +@if (Model.DocumentFound) +{ +
    +
    +
    +
    -
    - -
    - -
    +
    + +
    -
    - @if (Model.VersionSelectItems.Any()) - { -
    -
    -
    -
    -
    - -
    +
    - + @if (Model.ShowProjectsCombobox && Model.ProjectSelectItems.Count > 1) + { +
    +
    +
    +
    +
    + +
    } - @if (Model.LanguageSelectListItems.Count > 1) - { -
    -
    -
    -
    -
    - +
    + @if (Model.VersionSelectItems.Any()) + { +
    +
    +
    +
    +
    + +
    + +
    -
    -
    - } -
    + } -
    -
    -
    -
    - + @if (Model.LanguageSelectListItems.Count > 1) + { +
    +
    +
    +
    +
    + +
    + +
    +
    +
    - - -
    + }
    -
    +
    +
    +
    +
    + +
    - @if (Model.Navigation == null || Model.Navigation.Content.IsNullOrEmpty()) - { -
    - @L["NavigationDocumentNotFound"] + +
    +
    - } - else - { - - } -
    - -
    -
    - @if (Model.Document != null) - { -
    - +
    -
    -
    -
    - @if (Model.Document.Contributors != null && Model.Document.Contributors.Count > 0) + @if (Model.Document != null) + { +
    + -
    +
    -
    +
    -
    @L["InThisDocument"]
    - +
    @L["InThisDocument"]
    + -
    -
    - } - else - { -
    -

    @L["DocumentNotFound"]

    + } + else + { +
    +

    @L["DocumentNotFound"]

    - - - @L["BackToWebsite"] - -
    - } + + + @L["BackToWebsite"] + +
    + } +
    -
    - +} +else +{ + @(await Component.InvokeAsync(new + { + model = new DocumentNotFoundPageModel + { + ProjectName = Model.ProjectName, + DocumentName = Model.DocumentName, + LanguageCode = Model.LanguageCode, + Version = Model.Version, + } + })) +} \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Web/Pages/Documents/Project/Index.cshtml.cs b/modules/docs/src/Volo.Docs.Web/Pages/Documents/Project/Index.cshtml.cs index 82b58ad117..5788743784 100644 --- a/modules/docs/src/Volo.Docs.Web/Pages/Documents/Project/Index.cshtml.cs +++ b/modules/docs/src/Volo.Docs.Web/Pages/Documents/Project/Index.cshtml.cs @@ -33,6 +33,8 @@ namespace Volo.Docs.Pages.Documents.Project [BindProperty(SupportsGet = true)] public string LanguageCode { get; set; } + public bool DocumentFound { get; set; } = true; + public string DefaultLanguageCode { get; set; } public ProjectDto Project { get; set; } @@ -49,7 +51,7 @@ namespace Volo.Docs.Pages.Documents.Project public List ProjectSelectItems { get; private set; } - public NavigationWithDetailsDto Navigation { get; private set; } + public NavigationNode Navigation { get; private set; } public VersionInfoViewModel LatestVersionInfo { get; private set; } @@ -86,6 +88,21 @@ namespace Volo.Docs.Pages.Documents.Project } public async Task OnGetAsync() + { + try + { + return await SetPageAsync(); + } + catch (DocumentNotFoundException exception) + { + Logger.LogWarning(exception.Message); + + DocumentFound = false; + return Page(); + } + } + + private async Task SetPageAsync() { DocumentsUrlPrefix = _uiOptions.RoutePrefix; ShowProjectsCombobox = _uiOptions.ShowProjectsCombobox; @@ -271,7 +288,7 @@ namespace Volo.Docs.Pages.Documents.Project { try { - var document = await _documentAppService.GetNavigationAsync( + Navigation = await _documentAppService.GetNavigationAsync( new GetNavigationDocumentInput { ProjectId = Project.Id, @@ -279,15 +296,11 @@ namespace Volo.Docs.Pages.Documents.Project Version = Version } ); - - Navigation = ObjectMapper.Map(document); } catch (DocumentNotFoundException) //TODO: What if called on a remote service which may return 404 { return; } - - Navigation.ConvertItems(); } public string CreateVersionLink(VersionInfoViewModel latestVersion, string version, string documentName = null) diff --git a/modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/DocumentNotFoundComponent/Default.cshtml b/modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/DocumentNotFoundComponent/Default.cshtml new file mode 100644 index 0000000000..604ff05da7 --- /dev/null +++ b/modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/DocumentNotFoundComponent/Default.cshtml @@ -0,0 +1,53 @@ +@using Volo.Docs.Pages.Documents.Shared.DocumentNotFoundComponent +@model DocumentNotFoundPageModel +@{ +} +
    +
    + 404 +

    + "@Model.DocumentName" not found in @Model.ProjectName documents, with @Model.Version version and @Model.LanguageCode language. +

    +
    + + Go Back + +
    +
    + + + \ No newline at end of file diff --git a/modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/DocumentNotFoundComponent/DocumentNotFoundPageModel.cs b/modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/DocumentNotFoundComponent/DocumentNotFoundPageModel.cs new file mode 100644 index 0000000000..72b2b97584 --- /dev/null +++ b/modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/DocumentNotFoundComponent/DocumentNotFoundPageModel.cs @@ -0,0 +1,15 @@ +namespace Volo.Docs.Pages.Documents.Shared.DocumentNotFoundComponent +{ + public class DocumentNotFoundPageModel + { + public string ProjectName { get; set; } + + public string LanguageCode { get; set; } + + public string Version { get; set; } + + public string DocumentName { get; set; } + + public string DocumentsUrlPrefix { get; set; } + } +} diff --git a/modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/DocumentNotFoundComponent/DocumentNotFoundViewComponent.cs b/modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/DocumentNotFoundComponent/DocumentNotFoundViewComponent.cs new file mode 100644 index 0000000000..7aeed9beee --- /dev/null +++ b/modules/docs/src/Volo.Docs.Web/Pages/Documents/Shared/DocumentNotFoundComponent/DocumentNotFoundViewComponent.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; +using Volo.Abp.AspNetCore.Mvc; + +namespace Volo.Docs.Pages.Documents.Shared.DocumentNotFoundComponent +{ + public class DocumentNotFoundViewComponent : AbpViewComponent + { + private readonly DocsUiOptions _options; + + public DocumentNotFoundViewComponent(IOptions options) + { + _options = options.Value; + } + public IViewComponentResult Invoke(DocumentNotFoundPageModel model, string defaultErrorMessageKey) + { + model.DocumentsUrlPrefix = _options.RoutePrefix; + + return View("~/Pages/Documents/Shared/DocumentNotFoundComponent/Default.cshtml", model); + } + } +} diff --git a/modules/docs/src/Volo.Docs.Web/Volo.Docs.Web.csproj b/modules/docs/src/Volo.Docs.Web/Volo.Docs.Web.csproj index 2e89e9b255..ed9cf98af8 100644 --- a/modules/docs/src/Volo.Docs.Web/Volo.Docs.Web.csproj +++ b/modules/docs/src/Volo.Docs.Web/Volo.Docs.Web.csproj @@ -18,6 +18,7 @@ + diff --git a/modules/docs/test/Volo.Docs.Admin.Application.Tests/Volo/Docs/DocumentAdminAppService_Tests.cs b/modules/docs/test/Volo.Docs.Admin.Application.Tests/Volo/Docs/DocumentAdminAppService_Tests.cs new file mode 100644 index 0000000000..a969e3390a --- /dev/null +++ b/modules/docs/test/Volo.Docs.Admin.Application.Tests/Volo/Docs/DocumentAdminAppService_Tests.cs @@ -0,0 +1,55 @@ +using System.Threading.Tasks; +using Shouldly; +using Volo.Docs.Admin.Documents; +using Volo.Docs.Documents; +using Xunit; + +namespace Volo.Docs +{ + public class DocumentAdminAppService_Tests : DocsAdminApplicationTestBase + { + private readonly IDocumentAdminAppService _documentAdminAppService; + private readonly IDocumentRepository _documentRepository; + private readonly DocsTestData _testData; + + public DocumentAdminAppService_Tests() + { + _documentAdminAppService = GetRequiredService(); + _documentRepository = GetRequiredService(); + _testData = GetRequiredService(); + } + + [Fact] + public async Task PullAsync() + { + (await _documentRepository.FindAsync(_testData.PorjectId, "Part-I.md", "en", "1.0.0")).ShouldBeNull(); + + await _documentAdminAppService.PullAsync(new PullDocumentInput + { + ProjectId = _testData.PorjectId, + Name = "Part-I.md", + LanguageCode = "en", + Version = "1.0.0" + }); + + (await _documentRepository.FindAsync(_testData.PorjectId, "Part-I.md", "en", "1.0.0")).ShouldNotBeNull(); + } + + [Fact] + public async Task PullAllAsync() + { + (await _documentRepository.FindAsync(_testData.PorjectId, "Part-I.md", "en", "1.0.0")).ShouldBeNull(); + (await _documentRepository.FindAsync(_testData.PorjectId, "Part-II.md", "en", "1.0.0")).ShouldBeNull(); + + await _documentAdminAppService.PullAllAsync(new PullAllDocumentInput + { + ProjectId = _testData.PorjectId, + LanguageCode = "en", + Version = "1.0.0" + }); + + (await _documentRepository.FindAsync(_testData.PorjectId, "Part-I.md", "en", "1.0.0")).ShouldNotBeNull(); + (await _documentRepository.FindAsync(_testData.PorjectId, "Part-II.md", "en", "1.0.0")).ShouldNotBeNull(); + } + } +} diff --git a/modules/docs/test/Volo.Docs.Domain.Tests/Volo/Docs/DocumentSourceFactory_Tests.cs b/modules/docs/test/Volo.Docs.Domain.Tests/Volo/Docs/DocumentSourceFactory_Tests.cs new file mode 100644 index 0000000000..8e56a087d1 --- /dev/null +++ b/modules/docs/test/Volo.Docs.Domain.Tests/Volo/Docs/DocumentSourceFactory_Tests.cs @@ -0,0 +1,25 @@ +using Shouldly; +using Volo.Docs.Documents; +using Volo.Docs.FileSystem.Documents; +using Volo.Docs.GitHub.Documents; +using Xunit; + +namespace Volo.Docs +{ + public class DocumentSourceFactory_Tests : DocsDomainTestBase + { + private readonly IDocumentSourceFactory _documentSourceFactory; + + public DocumentSourceFactory_Tests() + { + _documentSourceFactory = GetRequiredService(); + } + + [Fact] + public void Create() + { + _documentSourceFactory.Create(GithubDocumentSource.Type).GetType().ShouldBe(typeof(GithubDocumentSource)); + _documentSourceFactory.Create(FileSystemDocumentSource.Type).GetType().ShouldBe(typeof(FileSystemDocumentSource)); + } + } +} diff --git a/modules/docs/test/Volo.Docs.Domain.Tests/Volo/Docs/DocumentStoreFactory_Tests.cs b/modules/docs/test/Volo.Docs.Domain.Tests/Volo/Docs/DocumentStoreFactory_Tests.cs deleted file mode 100644 index 73e07ec8e2..0000000000 --- a/modules/docs/test/Volo.Docs.Domain.Tests/Volo/Docs/DocumentStoreFactory_Tests.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Shouldly; -using Volo.Docs.Documents; -using Volo.Docs.FileSystem.Documents; -using Volo.Docs.GitHub.Documents; -using Xunit; - -namespace Volo.Docs -{ - public class DocumentStoreFactory_Tests : DocsDomainTestBase - { - private readonly IDocumentStoreFactory _documentStoreFactory; - - public DocumentStoreFactory_Tests() - { - _documentStoreFactory = GetRequiredService(); - } - - [Fact] - public void Create() - { - _documentStoreFactory.Create(GithubDocumentStore.Type).GetType().ShouldBe(typeof(GithubDocumentStore)); - _documentStoreFactory.Create(FileSystemDocumentStore.Type).GetType().ShouldBe(typeof(FileSystemDocumentStore)); - } - } -} diff --git a/modules/docs/test/Volo.Docs.Domain.Tests/Volo/Docs/GithubDocumentStore_Tests.cs b/modules/docs/test/Volo.Docs.Domain.Tests/Volo/Docs/GithubDocumentSource_Tests.cs similarity index 66% rename from modules/docs/test/Volo.Docs.Domain.Tests/Volo/Docs/GithubDocumentStore_Tests.cs rename to modules/docs/test/Volo.Docs.Domain.Tests/Volo/Docs/GithubDocumentSource_Tests.cs index 76d1f9f68f..1e89966518 100644 --- a/modules/docs/test/Volo.Docs.Domain.Tests/Volo/Docs/GithubDocumentStore_Tests.cs +++ b/modules/docs/test/Volo.Docs.Domain.Tests/Volo/Docs/GithubDocumentSource_Tests.cs @@ -7,15 +7,15 @@ using Xunit; namespace Volo.Docs { - public class GithubDocumentStore_Tests : DocsDomainTestBase + public class GithubDocumentSource_Tests : DocsDomainTestBase { - private readonly IDocumentStoreFactory _documentStoreFactory; + private readonly IDocumentSourceFactory _documentSourceFactory; private readonly IProjectRepository _projectRepository; private readonly DocsTestData _testData; - public GithubDocumentStore_Tests() + public GithubDocumentSource_Tests() { - _documentStoreFactory = GetRequiredService(); + _documentSourceFactory = GetRequiredService(); _projectRepository = GetRequiredService(); _testData = GetRequiredService(); } @@ -23,15 +23,15 @@ namespace Volo.Docs [Fact] public async Task GetDocumentAsync() { - var store = _documentStoreFactory.Create(GithubDocumentStore.Type); + var source = _documentSourceFactory.Create(GithubDocumentSource.Type); var project = await _projectRepository.FindAsync(_testData.PorjectId); project.ShouldNotBeNull(); - var document = await store.GetDocumentAsync(project, "index2", "en", "0.123.0"); + var document = await source.GetDocumentAsync(project, "index2", "en", "0.123.0"); document.ShouldNotBeNull(); - document.Title.ShouldBe("index2"); + document.Name.ShouldBe("index2"); document.FileName.ShouldBe("index2"); document.Version.ShouldBe("0.123.0"); document.Content.ShouldBe("stringContent"); @@ -40,12 +40,12 @@ namespace Volo.Docs [Fact] public async Task GetVersionsAsync() { - var store = _documentStoreFactory.Create(GithubDocumentStore.Type); + var source = _documentSourceFactory.Create(GithubDocumentSource.Type); var project = await _projectRepository.FindAsync(_testData.PorjectId); project.ShouldNotBeNull(); - var document = await store.GetVersionsAsync(project); + var document = await source.GetVersionsAsync(project); document.ShouldNotBeNull(); document.Count.ShouldBe(1); @@ -55,12 +55,12 @@ namespace Volo.Docs [Fact] public async Task GetResource() { - var store = _documentStoreFactory.Create(GithubDocumentStore.Type); + var source = _documentSourceFactory.Create(GithubDocumentSource.Type); var project = await _projectRepository.FindAsync(_testData.PorjectId); project.ShouldNotBeNull(); - var documentResource = await store.GetResource(project, "index.md", "en", "0.123.0"); + var documentResource = await source.GetResource(project, "index.md", "en", "0.123.0"); documentResource.ShouldNotBeNull(); documentResource.Content.ShouldBe(new byte[] diff --git a/modules/docs/test/Volo.Docs.EntityFrameworkCore.Tests/Volo/Docs/EntityFrameworkCore/DocumentRepository_Tests.cs b/modules/docs/test/Volo.Docs.EntityFrameworkCore.Tests/Volo/Docs/EntityFrameworkCore/DocumentRepository_Tests.cs new file mode 100644 index 0000000000..d36c97a2b7 --- /dev/null +++ b/modules/docs/test/Volo.Docs.EntityFrameworkCore.Tests/Volo/Docs/EntityFrameworkCore/DocumentRepository_Tests.cs @@ -0,0 +1,6 @@ +namespace Volo.Docs.EntityFrameworkCore +{ + public class DocumentRepository_Tests : DocumentRepository_Tests + { + } +} \ No newline at end of file diff --git a/modules/docs/test/Volo.Docs.MongoDB.Tests/Volo/Docs/Document/DocumentRepository_Tests.cs b/modules/docs/test/Volo.Docs.MongoDB.Tests/Volo/Docs/Document/DocumentRepository_Tests.cs new file mode 100644 index 0000000000..63e69d099a --- /dev/null +++ b/modules/docs/test/Volo.Docs.MongoDB.Tests/Volo/Docs/Document/DocumentRepository_Tests.cs @@ -0,0 +1,9 @@ +using Volo.Docs.MongoDB; + +namespace Volo.Docs.Document +{ + public class DocumentRepository_Tests : DocumentRepository_Tests + { + + } +} \ No newline at end of file diff --git a/modules/docs/test/Volo.Docs.TestBase/Volo/Docs/DocsTestBase.cs b/modules/docs/test/Volo.Docs.TestBase/Volo/Docs/DocsTestBase.cs index ec8270ae01..56a8ea0203 100644 --- a/modules/docs/test/Volo.Docs.TestBase/Volo/Docs/DocsTestBase.cs +++ b/modules/docs/test/Volo.Docs.TestBase/Volo/Docs/DocsTestBase.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using NSubstitute; @@ -23,6 +23,11 @@ namespace Volo.Docs var repositoryManager = Substitute.For(); repositoryManager.GetFileRawStringContentAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns("stringContent"); + repositoryManager.GetFileRawStringContentAsync( + Arg.Is(x => x.Contains("docs-nav.json", StringComparison.InvariantCultureIgnoreCase)), + Arg.Any(), Arg.Any()) + .Returns("{\"items\":[{\"text\":\"Part-I.md\",\"path\":\"Part-I.md\"},{\"text\":\"Part-II\",\"path\":\"Part-II.md\"}]}"); + repositoryManager.GetFileRawByteArrayContentAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(new byte[] { 0x01, 0x02, 0x03 }); repositoryManager.GetReleasesAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -47,6 +52,25 @@ namespace Volo.Docs "https://api.github.com/repos/abpframework/abp/zipball/0.15.0", null) }); + repositoryManager.GetFileCommitsAsync(Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any()) + .Returns(new List + { + new GitHubCommit("", "", "", "", "", null, null, + new Author("hikalkan ", 2, "", "https://avatars1.githubusercontent.com/u/1?v=4", "", + "https://github.com/hikalkan", "", "", "", "", "", "", "", "", "", "", false), "", + new Commit("", "", "", "", "", null, null, "", new Committer("", "", DateTimeOffset.Now), + null, null, new []{ new GitReference("", "", "", "", "", null, null) }, 1, null), + null, "", null, new []{ new GitReference("", "", "", "", "", null, null) }, null), + + new GitHubCommit("", "", "", "", "", null, null, + new Author("ebicoglu ", 2, "", "https://avatars1.githubusercontent.com/u/2?v=4", "", + "https://github.com/ebicoglu", "", "", "", "", "", "", "", "", "", "", false), "", + new Commit("", "", "", "", "", null, null, "", new Committer("", "", DateTimeOffset.Now), + null, null, new []{ new GitReference("", "", "", "", "", null, null) }, 1, null), + null, "", null, new []{ new GitReference("", "", "", "", "", null, null) }, null) + }); + services.AddSingleton(repositoryManager); } } diff --git a/modules/docs/test/Volo.Docs.TestBase/Volo/Docs/DocsTestDataBuilder.cs b/modules/docs/test/Volo.Docs.TestBase/Volo/Docs/DocsTestDataBuilder.cs index 121d18b44a..e7eadd7562 100644 --- a/modules/docs/test/Volo.Docs.TestBase/Volo/Docs/DocsTestDataBuilder.cs +++ b/modules/docs/test/Volo.Docs.TestBase/Volo/Docs/DocsTestDataBuilder.cs @@ -1,6 +1,8 @@ -using System.Threading.Tasks; +using System; +using System.Threading.Tasks; using Volo.Abp.Data; using Volo.Abp.DependencyInjection; +using Volo.Docs.Documents; using Volo.Docs.GitHub.Documents; using Volo.Docs.Projects; @@ -10,13 +12,16 @@ namespace Volo.Docs { private readonly DocsTestData _testData; private readonly IProjectRepository _projectRepository; + private readonly IDocumentRepository _documentRepository; public DocsTestDataBuilder( DocsTestData testData, - IProjectRepository projectRepository) + IProjectRepository projectRepository, + IDocumentRepository documentRepository) { _testData = testData; _projectRepository = projectRepository; + _documentRepository = documentRepository; } public async Task BuildAsync() @@ -25,7 +30,7 @@ namespace Volo.Docs _testData.PorjectId, "ABP vNext", "ABP", - GithubDocumentStore.Type, + GithubDocumentSource.Type, "md", "index", "docs-nav.json", @@ -38,6 +43,12 @@ namespace Volo.Docs .SetProperty("GitHubUserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"); await _projectRepository.InsertAsync(project); + + await _documentRepository.InsertAsync(new Document(Guid.NewGuid(), project.Id, "CLI.md", "2.0.0", "en", "CLI.md", + "this is abp cli", "md", "https://github.com/abpframework/abp/blob/2.0.0/docs/en/CLI.md", + "https://github.com/abpframework/abp/tree/2.0.0/docs/", + "https://raw.githubusercontent.com/abpframework/abp/2.0.0/docs/en/", "", DateTime.Now, DateTime.Now, + DateTime.Now)); } } } \ No newline at end of file diff --git a/modules/docs/test/Volo.Docs.TestBase/Volo/Docs/DocumentRepository_Tests.cs b/modules/docs/test/Volo.Docs.TestBase/Volo/Docs/DocumentRepository_Tests.cs new file mode 100644 index 0000000000..68a2ebb5e6 --- /dev/null +++ b/modules/docs/test/Volo.Docs.TestBase/Volo/Docs/DocumentRepository_Tests.cs @@ -0,0 +1,38 @@ +using System.Threading.Tasks; +using Shouldly; +using Volo.Abp.Modularity; +using Volo.Docs.Documents; +using Xunit; + +namespace Volo.Docs +{ + public abstract class DocumentRepository_Tests : DocsTestBase + where TStartupModule : IAbpModule + { + protected readonly IDocumentRepository DocumentRepository; + protected readonly DocsTestData DocsTestData; + + protected DocumentRepository_Tests() + { + DocumentRepository = GetRequiredService(); + DocsTestData = GetRequiredService(); + } + + [Fact] + public async Task FindAsync() + { + var document = await DocumentRepository.FindAsync(DocsTestData.PorjectId, "CLI.md", "en", "2.0.0"); + document.ShouldNotBeNull(); + } + + [Fact] + public async Task DeleteAsync() + { + (await DocumentRepository.GetListAsync()).ShouldNotBeEmpty(); + + await DocumentRepository.DeleteAsync(DocsTestData.PorjectId, "CLI.md", "en", "2.0.0"); + + (await DocumentRepository.GetListAsync()).ShouldBeEmpty(); + } + } +} diff --git a/npm/get-version.js b/npm/get-version.js new file mode 100644 index 0000000000..7f3dd79e3b --- /dev/null +++ b/npm/get-version.js @@ -0,0 +1,3 @@ +const fse = require("fs-extra"); + +console.log(fse.readJSONSync("package.json").version); diff --git a/npm/ng-packs/package.json b/npm/ng-packs/package.json index bea13bfd8d..c440aed399 100644 --- a/npm/ng-packs/package.json +++ b/npm/ng-packs/package.json @@ -82,7 +82,7 @@ "protractor": "~5.4.0", "rxjs": "~6.4.0", "snq": "^1.0.3", - "symlink-manager": "^1.4.1", + "symlink-manager": "^1.4.2", "ts-node": "~7.0.0", "tsickle": "^0.37.0", "tslint": "~5.20.0", diff --git a/npm/ng-packs/packages/account/src/lib/account.module.ts b/npm/ng-packs/packages/account/src/lib/account.module.ts index 3923ff4e17..93a496f8b5 100644 --- a/npm/ng-packs/packages/account/src/lib/account.module.ts +++ b/npm/ng-packs/packages/account/src/lib/account.module.ts @@ -3,7 +3,6 @@ import { ThemeSharedModule } from '@abp/ng.theme.shared'; import { NgModule, Provider } from '@angular/core'; import { NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap'; import { NgxValidateCoreModule } from '@ngx-validate/core'; -import { TableModule } from 'primeng/table'; import { AccountRoutingModule } from './account-routing.module'; import { ChangePasswordComponent } from './components/change-password/change-password.component'; import { LoginComponent } from './components/login/login.component'; @@ -29,7 +28,6 @@ import { AuthWrapperComponent } from './components/auth-wrapper/auth-wrapper.com CoreModule, AccountRoutingModule, ThemeSharedModule, - TableModule, NgbDropdownModule, NgxValidateCoreModule, ], diff --git a/npm/ng-packs/packages/core/src/lib/actions/config.actions.ts b/npm/ng-packs/packages/core/src/lib/actions/config.actions.ts index 7e7f932e24..8fd11bd2cb 100644 --- a/npm/ng-packs/packages/core/src/lib/actions/config.actions.ts +++ b/npm/ng-packs/packages/core/src/lib/actions/config.actions.ts @@ -1,4 +1,5 @@ -import { ABP } from '../models'; +import { ABP } from '../models/common'; +import { Config } from '../models/config'; export class PatchRouteByName { static readonly type = '[Config] Patch Route By Name'; @@ -16,3 +17,8 @@ export class AddRoute { static readonly type = '[Config] Add Route'; constructor(public payload: Omit) {} } + +export class SetEnvironment { + static readonly type = '[Config] Set Environment'; + constructor(public environment: Config.Environment) {} +} diff --git a/npm/ng-packs/packages/core/src/lib/services/config-state.service.ts b/npm/ng-packs/packages/core/src/lib/services/config-state.service.ts index 506b278634..cf97e42b0f 100644 --- a/npm/ng-packs/packages/core/src/lib/services/config-state.service.ts +++ b/npm/ng-packs/packages/core/src/lib/services/config-state.service.ts @@ -1,8 +1,12 @@ import { Injectable } from '@angular/core'; import { Store } from '@ngxs/store'; +import { + AddRoute, + GetAppConfiguration, + PatchRouteByName, + SetEnvironment, +} from '../actions/config.actions'; import { ConfigState } from '../states'; -import { GetAppConfiguration, PatchRouteByName, AddRoute } from '../actions/config.actions'; -import { ABP } from '../models'; @Injectable({ providedIn: 'root', @@ -61,4 +65,8 @@ export class ConfigStateService { dispatchAddRoute(...args: ConstructorParameters) { return this.store.dispatch(new AddRoute(...args)); } + + dispatchSetEnvironment(...args: ConstructorParameters) { + return this.store.dispatch(new SetEnvironment(...args)); + } } diff --git a/npm/ng-packs/packages/core/src/lib/states/config.state.ts b/npm/ng-packs/packages/core/src/lib/states/config.state.ts index debbc9b8a0..ff964cfe92 100644 --- a/npm/ng-packs/packages/core/src/lib/states/config.state.ts +++ b/npm/ng-packs/packages/core/src/lib/states/config.state.ts @@ -2,7 +2,12 @@ import { Action, createSelector, Selector, State, StateContext, Store } from '@n import { of } from 'rxjs'; import { switchMap, tap } from 'rxjs/operators'; import snq from 'snq'; -import { GetAppConfiguration, PatchRouteByName, AddRoute } from '../actions/config.actions'; +import { + GetAppConfiguration, + PatchRouteByName, + AddRoute, + SetEnvironment, +} from '../actions/config.actions'; import { SetLanguage } from '../actions/session.actions'; import { ABP } from '../models/common'; import { Config } from '../models/config'; @@ -291,6 +296,13 @@ export class ConfigState { flattedRoutes, }); } + + @Action(SetEnvironment) + setEnvironment({ patchState }: StateContext, environment: Config.Environment) { + return patchState({ + environment, + }); + } } function patchRouteDeep( diff --git a/npm/ng-packs/packages/core/src/lib/utils/route-utils.ts b/npm/ng-packs/packages/core/src/lib/utils/route-utils.ts index 8bbbee60ec..51abe4218b 100644 --- a/npm/ng-packs/packages/core/src/lib/utils/route-utils.ts +++ b/npm/ng-packs/packages/core/src/lib/utils/route-utils.ts @@ -1,4 +1,4 @@ -import { ABP } from '../models'; +import { ABP } from '../models/common'; export function organizeRoutes( routes: ABP.FullRoute[], @@ -33,7 +33,10 @@ export function organizeRoutes( return filteredRoutes; } -export function setChildRoute(routes: ABP.FullRoute[], parentNameArr: ABP.FullRoute[]): ABP.FullRoute[] { +export function setChildRoute( + routes: ABP.FullRoute[], + parentNameArr: ABP.FullRoute[], +): ABP.FullRoute[] { return routes.map(route => { if (route.children && route.children.length) { route.children = setChildRoute(route.children, parentNameArr); diff --git a/npm/ng-packs/packages/identity/src/lib/identity.module.ts b/npm/ng-packs/packages/identity/src/lib/identity.module.ts index 20a332c6ce..f11562a11f 100644 --- a/npm/ng-packs/packages/identity/src/lib/identity.module.ts +++ b/npm/ng-packs/packages/identity/src/lib/identity.module.ts @@ -8,7 +8,6 @@ import { NgbTabsetModule, NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap'; import { ThemeSharedModule } from '@abp/ng.theme.shared'; import { UsersComponent } from './components/users/users.component'; import { PermissionManagementModule } from '@abp/ng.permission-management'; -import { TableModule } from 'primeng/table'; import { NgxValidateCoreModule } from '@ngx-validate/core'; @NgModule({ @@ -19,7 +18,6 @@ import { NgxValidateCoreModule } from '@ngx-validate/core'; IdentityRoutingModule, NgbTabsetModule, ThemeSharedModule, - TableModule, NgbDropdownModule, PermissionManagementModule, NgxValidateCoreModule, diff --git a/npm/ng-packs/packages/tenant-management/src/lib/tenant-management.module.ts b/npm/ng-packs/packages/tenant-management/src/lib/tenant-management.module.ts index 218eda45fa..707762ff4b 100644 --- a/npm/ng-packs/packages/tenant-management/src/lib/tenant-management.module.ts +++ b/npm/ng-packs/packages/tenant-management/src/lib/tenant-management.module.ts @@ -3,7 +3,6 @@ import { ThemeSharedModule } from '@abp/ng.theme.shared'; import { NgModule, Provider } from '@angular/core'; import { NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap'; import { NgxsModule } from '@ngxs/store'; -import { TableModule } from 'primeng/table'; import { TenantsComponent } from './components/tenants/tenants.component'; import { TenantManagementState } from './states/tenant-management.state'; import { TenantManagementRoutingModule } from './tenant-management-routing.module'; @@ -17,7 +16,6 @@ import { NgxValidateCoreModule } from '@ngx-validate/core'; NgxsModule.forFeature([TenantManagementState]), NgxValidateCoreModule, CoreModule, - TableModule, ThemeSharedModule, NgbDropdownModule, FeatureManagementModule, diff --git a/npm/ng-packs/packages/theme-basic/src/lib/components/application-layout/application-layout.component.ts b/npm/ng-packs/packages/theme-basic/src/lib/components/application-layout/application-layout.component.ts index 06f67c8e87..7d7947e833 100644 --- a/npm/ng-packs/packages/theme-basic/src/lib/components/application-layout/application-layout.component.ts +++ b/npm/ng-packs/packages/theme-basic/src/lib/components/application-layout/application-layout.component.ts @@ -1,10 +1,10 @@ import { ABP, ApplicationConfiguration, + AuthService, Config, ConfigState, eLayoutType, - GetAppConfiguration, SessionState, SetLanguage, takeUntilDestroy, @@ -14,15 +14,11 @@ import { AfterViewInit, Component, OnDestroy, - QueryList, Renderer2, TemplateRef, TrackByFunction, ViewChild, - ViewChildren, - ElementRef, } from '@angular/core'; -import { NgbDropdown } from '@ng-bootstrap/ng-bootstrap'; import { Navigate, RouterState } from '@ngxs/router-plugin'; import { Select, Store } from '@ngxs/store'; import compare from 'just-compare'; @@ -32,7 +28,6 @@ import snq from 'snq'; import { AddNavigationElement } from '../../actions'; import { Layout } from '../../models/layout'; import { LayoutState } from '../../states'; -import { AuthService } from 'packages/core/src/lib/services/auth.service'; @Component({ selector: 'abp-layout-application', diff --git a/npm/ng-packs/packages/theme-basic/src/lib/theme-basic.module.ts b/npm/ng-packs/packages/theme-basic/src/lib/theme-basic.module.ts index 00d651f9af..827983b15f 100644 --- a/npm/ng-packs/packages/theme-basic/src/lib/theme-basic.module.ts +++ b/npm/ng-packs/packages/theme-basic/src/lib/theme-basic.module.ts @@ -4,7 +4,6 @@ import { NgModule } from '@angular/core'; import { NgbCollapseModule, NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap'; import { NgxValidateCoreModule } from '@ngx-validate/core'; import { NgxsModule } from '@ngxs/store'; -import { ToastModule } from 'primeng/toast'; import { AccountLayoutComponent } from './components/account-layout/account-layout.component'; import { ApplicationLayoutComponent } from './components/application-layout/application-layout.component'; import { EmptyLayoutComponent } from './components/empty-layout/empty-layout.component'; @@ -21,7 +20,6 @@ export const LAYOUTS = [ApplicationLayoutComponent, AccountLayoutComponent, Empt ThemeSharedModule, NgbCollapseModule, NgbDropdownModule, - ToastModule, NgxValidateCoreModule, NgxsModule.forFeature([LayoutState]), NgxValidateCoreModule.forRoot({ @@ -29,9 +27,11 @@ export const LAYOUTS = [ApplicationLayoutComponent, AccountLayoutComponent, Empt blueprints: { email: 'AbpAccount::ThisFieldIsNotAValidEmailAddress.', max: 'AbpAccount::ThisFieldMustBeBetween{0}And{1}[{{ min }},{{ max }}]', - maxlength: 'AbpAccount::ThisFieldMustBeAStringOrArrayTypeWithAMaximumLengthoOf{0}[{{ requiredLength }}]', + maxlength: + 'AbpAccount::ThisFieldMustBeAStringOrArrayTypeWithAMaximumLengthoOf{0}[{{ requiredLength }}]', min: 'AbpAccount::ThisFieldMustBeBetween{0}And{1}[{{ min }},{{ max }}]', - minlength: 'AbpAccount::ThisFieldMustBeAStringOrArrayTypeWithAMinimumLengthOf{0}[{{ requiredLength }}]', + minlength: + 'AbpAccount::ThisFieldMustBeAStringOrArrayTypeWithAMinimumLengthOf{0}[{{ requiredLength }}]', required: 'AbpAccount::ThisFieldIsRequired.', passwordMismatch: 'AbpIdentity::Identity.PasswordConfirmationFailed', }, diff --git a/npm/ng-packs/packages/theme-shared/src/lib/components/confirmation/confirmation.component.ts b/npm/ng-packs/packages/theme-shared/src/lib/components/confirmation/confirmation.component.ts index afdb024888..92188acb34 100644 --- a/npm/ng-packs/packages/theme-shared/src/lib/components/confirmation/confirmation.component.ts +++ b/npm/ng-packs/packages/theme-shared/src/lib/components/confirmation/confirmation.component.ts @@ -2,7 +2,6 @@ import { Component } from '@angular/core'; import { ConfirmationService } from '../../services/confirmation.service'; import { Confirmation } from '../../models/confirmation'; import { LocalizationService } from '@abp/ng.core'; -import { Toaster } from '../../models/toaster'; @Component({ selector: 'abp-confirmation', @@ -10,9 +9,9 @@ import { Toaster } from '../../models/toaster'; styleUrls: ['./confirmation.component.scss'], }) export class ConfirmationComponent { - confirm = Toaster.Status.confirm; - reject = Toaster.Status.reject; - dismiss = Toaster.Status.dismiss; + confirm = Confirmation.Status.confirm; + reject = Confirmation.Status.reject; + dismiss = Confirmation.Status.dismiss; visible = false; @@ -43,7 +42,7 @@ export class ConfirmationComponent { }); } - close(status: Toaster.Status) { + close(status: Confirmation.Status) { this.confirmationService.clear(status); } } diff --git a/npm/ng-packs/packages/theme-shared/src/lib/handlers/error.handler.ts b/npm/ng-packs/packages/theme-shared/src/lib/handlers/error.handler.ts index 7975fd9833..fedf870c4a 100644 --- a/npm/ng-packs/packages/theme-shared/src/lib/handlers/error.handler.ts +++ b/npm/ng-packs/packages/theme-shared/src/lib/handlers/error.handler.ts @@ -190,8 +190,8 @@ export class ErrorHandler { if (body.details) { message = body.details; title = body.message; - } else if (body.code) { - title = body.code; + } else if (body.message) { + title = DEFAULT_ERROR_MESSAGES.defaultError.title; message = body.message; } else { message = body.message || DEFAULT_ERROR_MESSAGES.defaultError.title; diff --git a/npm/ng-packs/packages/theme-shared/src/lib/models/confirmation.ts b/npm/ng-packs/packages/theme-shared/src/lib/models/confirmation.ts index 40925c1b2c..815fd65c20 100644 --- a/npm/ng-packs/packages/theme-shared/src/lib/models/confirmation.ts +++ b/npm/ng-packs/packages/theme-shared/src/lib/models/confirmation.ts @@ -20,4 +20,10 @@ export namespace Confirmation { } export type Severity = 'neutral' | 'success' | 'info' | 'warning' | 'error'; + + export enum Status { + confirm = 'confirm', + reject = 'reject', + dismiss = 'dismiss', + } } diff --git a/npm/ng-packs/packages/theme-shared/src/lib/models/toaster.ts b/npm/ng-packs/packages/theme-shared/src/lib/models/toaster.ts index 34fe04f351..27a2b6b460 100644 --- a/npm/ng-packs/packages/theme-shared/src/lib/models/toaster.ts +++ b/npm/ng-packs/packages/theme-shared/src/lib/models/toaster.ts @@ -21,6 +21,9 @@ export namespace Toaster { export type Severity = 'neutral' | 'success' | 'info' | 'warning' | 'error'; + /** + * @deprecated Status will be removed from toaster model in v2.2 + */ export enum Status { confirm = 'confirm', reject = 'reject', diff --git a/npm/ng-packs/packages/theme-shared/src/lib/services/confirmation.service.ts b/npm/ng-packs/packages/theme-shared/src/lib/services/confirmation.service.ts index f66dfd768d..2db6d38091 100644 --- a/npm/ng-packs/packages/theme-shared/src/lib/services/confirmation.service.ts +++ b/npm/ng-packs/packages/theme-shared/src/lib/services/confirmation.service.ts @@ -2,19 +2,18 @@ import { Injectable } from '@angular/core'; import { Confirmation } from '../models/confirmation'; import { fromEvent, Observable, Subject, ReplaySubject } from 'rxjs'; import { takeUntil, debounceTime, filter } from 'rxjs/operators'; -import { Toaster } from '../models/toaster'; import { Config } from '@abp/ng.core'; @Injectable({ providedIn: 'root' }) export class ConfirmationService { - status$: Subject; + status$: Subject; confirmation$ = new ReplaySubject(1); info( message: Config.LocalizationParam, title: Config.LocalizationParam, options?: Partial, - ): Observable { + ): Observable { return this.show(message, title, 'info', options); } @@ -22,7 +21,7 @@ export class ConfirmationService { message: Config.LocalizationParam, title: Config.LocalizationParam, options?: Partial, - ): Observable { + ): Observable { return this.show(message, title, 'success', options); } @@ -30,7 +29,7 @@ export class ConfirmationService { message: Config.LocalizationParam, title: Config.LocalizationParam, options?: Partial, - ): Observable { + ): Observable { return this.show(message, title, 'warning', options); } @@ -38,16 +37,16 @@ export class ConfirmationService { message: Config.LocalizationParam, title: Config.LocalizationParam, options?: Partial, - ): Observable { + ): Observable { return this.show(message, title, 'error', options); } show( message: Config.LocalizationParam, title: Config.LocalizationParam, - severity?: Toaster.Severity, + severity?: Confirmation.Severity, options?: Partial, - ): Observable { + ): Observable { this.confirmation$.next({ message, title, @@ -59,9 +58,9 @@ export class ConfirmationService { return this.status$; } - clear(status?: Toaster.Status) { + clear(status?: Confirmation.Status) { this.confirmation$.next(); - this.status$.next(status || Toaster.Status.dismiss); + this.status$.next(status || Confirmation.Status.dismiss); } listenToEscape() { diff --git a/npm/ng-packs/packages/theme-shared/src/lib/tests/confirmation.service.spec.ts b/npm/ng-packs/packages/theme-shared/src/lib/tests/confirmation.service.spec.ts index aa2481419d..918ed4e314 100644 --- a/npm/ng-packs/packages/theme-shared/src/lib/tests/confirmation.service.spec.ts +++ b/npm/ng-packs/packages/theme-shared/src/lib/tests/confirmation.service.spec.ts @@ -3,7 +3,6 @@ import { Component } from '@angular/core'; import { RouterTestingModule } from '@angular/router/testing'; import { createComponentFactory, Spectator } from '@ngneat/spectator/jest'; import { NgxsModule } from '@ngxs/store'; -import { MessageService } from 'primeng/components/common/messageservice'; import { ConfirmationService } from '../services/confirmation.service'; import { ThemeSharedModule } from '../theme-shared.module'; import { OAuthModule, OAuthService } from 'angular-oauth2-oidc'; @@ -24,7 +23,6 @@ describe('ConfirmationService', () => { const createComponent = createComponentFactory({ component: DummyComponent, imports: [CoreModule, ThemeSharedModule.forRoot(), NgxsModule.forRoot(), RouterTestingModule], - providers: [MessageService], mocks: [OAuthService], }); diff --git a/npm/ng-packs/packages/theme-shared/src/lib/tests/error.handler.spec.ts b/npm/ng-packs/packages/theme-shared/src/lib/tests/error.handler.spec.ts index aa22e9c567..d2f2c11e3d 100644 --- a/npm/ng-packs/packages/theme-shared/src/lib/tests/error.handler.spec.ts +++ b/npm/ng-packs/packages/theme-shared/src/lib/tests/error.handler.spec.ts @@ -6,7 +6,6 @@ import { createRoutingFactory, SpectatorRouting } from '@ngneat/spectator/jest'; import { NgxsModule, Store } from '@ngxs/store'; import { DEFAULT_ERROR_MESSAGES, ErrorHandler } from '../handlers'; import { ThemeSharedModule } from '../theme-shared.module'; -import { MessageService } from 'primeng/components/common/messageservice'; import { RouterError, RouterDataResolved } from '@ngxs/router-plugin'; import { NavigationError, ResolveEnd } from '@angular/router'; import { OAuthModule, OAuthService } from 'angular-oauth2-oidc'; diff --git a/npm/ng-packs/packages/theme-shared/src/lib/tests/modal.component.spec.ts b/npm/ng-packs/packages/theme-shared/src/lib/tests/modal.component.spec.ts index ead6d29a23..3bdf2e9d07 100644 --- a/npm/ng-packs/packages/theme-shared/src/lib/tests/modal.component.spec.ts +++ b/npm/ng-packs/packages/theme-shared/src/lib/tests/modal.component.spec.ts @@ -1,8 +1,6 @@ import { LocalizationPipe } from '@abp/ng.core'; import { createHostFactory, SpectatorHost } from '@ngneat/spectator/jest'; import { Store } from '@ngxs/store'; -import { MessageService } from 'primeng/components/common/messageservice'; -import { ToastModule } from 'primeng/toast'; import { timer } from 'rxjs'; import { ButtonComponent, ConfirmationComponent, ModalComponent } from '../components'; import { RouterTestingModule } from '@angular/router/testing'; @@ -16,9 +14,8 @@ describe('ModalComponent', () => { let disappearFn; const createHost = createHostFactory({ component: ModalComponent, - imports: [ToastModule, RouterTestingModule], + imports: [RouterTestingModule], declarations: [ConfirmationComponent, LocalizationPipe, ButtonComponent], - providers: [MessageService], mocks: [Store], }); diff --git a/npm/ng-packs/packages/theme-shared/src/lib/tests/table-sort.directive.spec.ts b/npm/ng-packs/packages/theme-shared/src/lib/tests/table-sort.directive.spec.ts index 7c342174e6..231f627fa1 100644 --- a/npm/ng-packs/packages/theme-shared/src/lib/tests/table-sort.directive.spec.ts +++ b/npm/ng-packs/packages/theme-shared/src/lib/tests/table-sort.directive.spec.ts @@ -1,17 +1,21 @@ import { SpectatorDirective, createDirectiveFactory } from '@ngneat/spectator/jest'; -import { TableModule, Table } from 'primeng/table'; import { TableSortDirective } from '../directives/table-sort.directive'; +import { TableComponent } from '../components/table/table.component'; +import { DummyLocalizationPipe } from './table.component.spec'; +import { PaginationComponent } from '../components'; describe('TableSortDirective', () => { let spectator: SpectatorDirective; let directive: TableSortDirective; const createDirective = createDirectiveFactory({ directive: TableSortDirective, - imports: [TableModule], + declarations: [TableComponent, DummyLocalizationPipe, PaginationComponent], }); beforeEach(() => { - spectator = createDirective(``); + spectator = createDirective( + ``, + ); directive = spectator.directive; }); @@ -21,7 +25,7 @@ describe('TableSortDirective', () => { test('should change table value', () => { expect(directive.value).toEqual([1, 4, 2]); - const table = spectator.query(Table); + const table = spectator.query(TableComponent); expect(table.value).toEqual([1, 2, 4]); }); }); diff --git a/npm/ng-packs/packages/theme-shared/src/lib/tests/toaster.service.spec.ts b/npm/ng-packs/packages/theme-shared/src/lib/tests/toaster.service.spec.ts index 23e99b8204..1ac1116c78 100644 --- a/npm/ng-packs/packages/theme-shared/src/lib/tests/toaster.service.spec.ts +++ b/npm/ng-packs/packages/theme-shared/src/lib/tests/toaster.service.spec.ts @@ -3,7 +3,6 @@ import { Component } from '@angular/core'; import { RouterTestingModule } from '@angular/router/testing'; import { createComponentFactory, Spectator } from '@ngneat/spectator/jest'; import { NgxsModule } from '@ngxs/store'; -import { MessageService } from 'primeng/components/common/messageservice'; import { ToasterService } from '../services/toaster.service'; import { ThemeSharedModule } from '../theme-shared.module'; import { OAuthService } from 'angular-oauth2-oidc'; @@ -24,7 +23,6 @@ describe('ToasterService', () => { const createComponent = createComponentFactory({ component: DummyComponent, imports: [CoreModule, ThemeSharedModule.forRoot(), NgxsModule.forRoot(), RouterTestingModule], - providers: [MessageService], mocks: [OAuthService], }); diff --git a/npm/ng-packs/packages/theme-shared/src/lib/theme-shared.module.ts b/npm/ng-packs/packages/theme-shared/src/lib/theme-shared.module.ts index 69d719fe08..33e6144446 100644 --- a/npm/ng-packs/packages/theme-shared/src/lib/theme-shared.module.ts +++ b/npm/ng-packs/packages/theme-shared/src/lib/theme-shared.module.ts @@ -3,8 +3,6 @@ import { DatePipe } from '@angular/common'; import { APP_INITIALIZER, Injector, ModuleWithProviders, NgModule } from '@angular/core'; import { NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap'; import { NgxValidateCoreModule } from '@ngx-validate/core'; -import { MessageService } from 'primeng/components/common/messageservice'; -import { ToastModule } from 'primeng/toast'; import { BreadcrumbComponent } from './components/breadcrumb/breadcrumb.component'; import { ButtonComponent } from './components/button/button.component'; import { ChartComponent } from './components/chart/chart.component'; @@ -40,7 +38,7 @@ export function appendScript(injector: Injector) { } @NgModule({ - imports: [CoreModule, ToastModule, NgxValidateCoreModule], + imports: [CoreModule, NgxValidateCoreModule], declarations: [ BreadcrumbComponent, ButtonComponent, @@ -92,7 +90,6 @@ export class ThemeSharedModule { deps: [Injector], useFactory: appendScript, }, - { provide: MessageService, useClass: MessageService }, { provide: HTTP_ERROR_CONFIG, useValue: options.httpErrorConfig }, { provide: 'HTTP_ERROR_CONFIG', diff --git a/npm/ng-packs/scripts/package-lock.json b/npm/ng-packs/scripts/package-lock.json index 99f5e5ecd1..3e8d873de9 100644 --- a/npm/ng-packs/scripts/package-lock.json +++ b/npm/ng-packs/scripts/package-lock.json @@ -4,6 +4,15 @@ "lockfileVersion": 1, "requires": true, "dependencies": { + "@types/fs-extra": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-8.0.1.tgz", + "integrity": "sha512-J00cVDALmi/hJOYsunyT52Hva5TnJeKP5yd1r+mH/ZU0mbYZflR0Z5kw5kITtKTRYMhm1JMClOFYdHnQszEvqw==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, "@types/json5": { "version": "0.0.29", "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", @@ -463,9 +472,9 @@ } }, "commander": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-4.0.1.tgz", - "integrity": "sha512-IPF4ouhCP+qdlcmCedhxX4xiGBPyigb8v5NeUp+0LyhwLgxMqyp3S0vl7TAPfS/hiP7FC3caI/PB9lTmP8r1NA==" + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==" }, "component-emitter": { "version": "1.3.0", diff --git a/npm/ng-packs/scripts/package.json b/npm/ng-packs/scripts/package.json index c5f1527943..144a275924 100644 --- a/npm/ng-packs/scripts/package.json +++ b/npm/ng-packs/scripts/package.json @@ -13,12 +13,13 @@ "author": "", "dependencies": { "babel-preset-node6": "^11.0.0", - "commander": "^4.0.1", + "commander": "^4.1.1", "execa": "^2.0.3", "fs-extra": "^8.1.0", "prompt-confirm": "^2.0.4" }, "devDependencies": { + "@types/fs-extra": "^8.0.1", "@types/node": "^13.1.2", "esm": "^3.2.25", "ts-node": "^8.5.4", diff --git a/npm/ng-packs/scripts/publish.ts b/npm/ng-packs/scripts/publish.ts index b7e5d4f219..3a8197522f 100644 --- a/npm/ng-packs/scripts/publish.ts +++ b/npm/ng-packs/scripts/publish.ts @@ -1,9 +1,23 @@ import execa from 'execa'; import fse from 'fs-extra'; +import program from 'commander'; + +program + .option( + '-v, --nextVersion ', + 'next semantic version. Available versions: ["major", "minor", "patch", "premajor", "preminor", "prepatch", "prerelease", "or type a custom version"]', + ) + .option('-p, --preview', 'publish with preview tag'); + +program.parse(process.argv); const publish = async () => { const versions = ['major', 'minor', 'patch', 'premajor', 'preminor', 'prepatch', 'prerelease']; - let nextSemanticVersion = (process.argv[2] || '').toLowerCase(); + + if (!program.nextVersion) { + console.error('Please provide a version with --nextVersion attribute'); + process.exit(1); + } try { await execa('yarn', ['install-new-dependencies'], { stdout: 'inherit' }); @@ -12,7 +26,7 @@ const publish = async () => { await execa( 'yarn', - ['lerna', 'version', nextSemanticVersion, '--yes', '--no-commit-hooks', '--skip-git'], + ['lerna', 'version', program.nextVersion, '--yes', '--no-commit-hooks', '--skip-git'], { stdout: 'inherit', cwd: '../' }, ); @@ -26,7 +40,14 @@ const publish = async () => { await execa( 'yarn', - ['lerna', 'exec', '--', '"npm publish --registry https://registry.npmjs.org"'], + [ + 'lerna', + 'exec', + '--', + `"npm publish --registry https://registry.npmjs.org${ + program.preview ? ' --tag preview' : '' + }"`, + ], { stdout: 'inherit', cwd: '../', diff --git a/npm/ng-packs/scripts/yarn.lock b/npm/ng-packs/scripts/yarn.lock index 2e14671cb5..b58b42d20b 100644 --- a/npm/ng-packs/scripts/yarn.lock +++ b/npm/ng-packs/scripts/yarn.lock @@ -2,11 +2,23 @@ # yarn lockfile v1 +"@types/fs-extra@^8.0.1": + version "8.0.1" + resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-8.0.1.tgz#a2378d6e7e8afea1564e44aafa2e207dadf77686" + integrity sha512-J00cVDALmi/hJOYsunyT52Hva5TnJeKP5yd1r+mH/ZU0mbYZflR0Z5kw5kITtKTRYMhm1JMClOFYdHnQszEvqw== + dependencies: + "@types/node" "*" + "@types/json5@^0.0.29": version "0.0.29" resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee" integrity sha1-7ihweulOEdK4J7y+UnC86n8+ce4= +"@types/node@*": + version "13.7.1" + resolved "https://registry.yarnpkg.com/@types/node/-/node-13.7.1.tgz#238eb34a66431b71d2aaddeaa7db166f25971a0d" + integrity sha512-Zq8gcQGmn4txQEJeiXo/KiLpon8TzAl0kmKH4zdWctPj05nWwp1ClMdAVEloqrQKfaC48PNLdgN/aVaLqUrluA== + "@types/node@^13.1.2": version "13.1.2" resolved "https://registry.yarnpkg.com/@types/node/-/node-13.1.2.tgz#fe94285bf5e0782e1a9e5a8c482b1c34465fa385" @@ -412,10 +424,10 @@ collection-visit@^1.0.0: map-visit "^1.0.0" object-visit "^1.0.0" -commander@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/commander/-/commander-4.0.1.tgz#b67622721785993182e807f4883633e6401ba53c" - integrity sha512-IPF4ouhCP+qdlcmCedhxX4xiGBPyigb8v5NeUp+0LyhwLgxMqyp3S0vl7TAPfS/hiP7FC3caI/PB9lTmP8r1NA== +commander@^4.1.1: + version "4.1.1" + resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068" + integrity sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA== component-emitter@^1.2.1: version "1.3.0" diff --git a/npm/package.json b/npm/package.json index f8bf5fe835..0dc358279b 100644 --- a/npm/package.json +++ b/npm/package.json @@ -1,4 +1,5 @@ { + "version": "2.1.0", "scripts": { "lerna": "lerna", "gulp:app": "node run-gulp-script.js ../templates/app/aspnet-core", @@ -7,11 +8,13 @@ "update:templates": "node abp-package-update-script.js ../templates" }, "devDependencies": { + "@types/fs-extra": "^8.0.1", "glob": "^7.1.5", "lerna": "^3.18.4", "npm-check-updates": "^3.1.25" }, "dependencies": { - "execa": "^3.4.0" + "execa": "^3.4.0", + "fs-extra": "^8.1.0" } } diff --git a/npm/packs/jquery/src/abp.jquery.js b/npm/packs/jquery/src/abp.jquery.js index bf4c920815..76f54df1a0 100644 --- a/npm/packs/jquery/src/abp.jquery.js +++ b/npm/packs/jquery/src/abp.jquery.js @@ -359,13 +359,17 @@ var _loadScript = function (url, loadCallback, failCallback) { _loadFromUrl(url, loadCallback, failCallback, function (urlInfo) { - $.getScript(url) - .done(function () { - urlInfo.succeed(); - }) - .fail(function () { - urlInfo.failed(); - }); + $.get({ + url: url, + dataType: 'text' + }) + .done(function (script) { + $.globalEval(script); + urlInfo.succeed(); + }) + .fail(function () { + urlInfo.failed(); + }); }); }; diff --git a/npm/preview-publish.ps1 b/npm/preview-publish.ps1 new file mode 100644 index 0000000000..d448378750 --- /dev/null +++ b/npm/preview-publish.ps1 @@ -0,0 +1,30 @@ +param( + [string]$Version +) + +npm install + +$NextVersion = $(node get-version.js) + '-preview' + (Get-Date).tostring(“yyyyMMdd”) + '-1' +$rootFolder = (Get-Item -Path "./" -Verbose).FullName + +if(-Not $Version) { +$Version = $NextVersion; +} + +$commands = ( + "cd ng-packs\scripts", + "npm install", + "npm run publish-packages -- --nextVersion $Version --preview", + "cd ../../", + "yarn lerna publish $Version --no-push --yes --no-git-reset --no-commit-hooks --no-git-tag-version --force-publish --dist-tag preview" +) + +foreach ($command in $commands) { + Write-Host $command + Invoke-Expression $command + if($LASTEXITCODE -ne '0' -And $command -notlike '*cd *'){ + Write-Host ("Process failed! " + $command) + Set-Location $rootFolder + exit $LASTEXITCODE + } +} \ No newline at end of file diff --git a/npm/publish.ps1 b/npm/publish.ps1 index 7552eb0505..a510527401 100644 --- a/npm/publish.ps1 +++ b/npm/publish.ps1 @@ -2,19 +2,20 @@ param( [string]$Version ) -if(-Not $Version) { -echo 'Please pass a semantic version like this: ./publish.ps1 -Version patch' -exit -} +npm install +$NextVersion = $(node get-version.js) $rootFolder = (Get-Item -Path "./" -Verbose).FullName +if(-Not $Version) { + $Version = $NextVersion; +} + $commands = ( "cd ng-packs\scripts", "npm install", - "npm run publish-packages -- $Version", + "npm run publish-packages -- --nextVersion $Version", "cd ../../", - "yarn", "yarn lerna publish $Version --no-push --yes --no-git-reset --no-commit-hooks --no-git-tag-version --force-publish", "yarn update:templates", "yarn gulp:app", diff --git a/npm/yarn.lock b/npm/yarn.lock index 7775403939..b331d5ff22 100644 --- a/npm/yarn.lock +++ b/npm/yarn.lock @@ -832,6 +832,13 @@ resolved "https://registry.yarnpkg.com/@types/events/-/events-3.0.0.tgz#2862f3f58a9a7f7c3e78d79f130dd4d71c25c2a7" integrity sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g== +"@types/fs-extra@^8.0.1": + version "8.0.1" + resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-8.0.1.tgz#a2378d6e7e8afea1564e44aafa2e207dadf77686" + integrity sha512-J00cVDALmi/hJOYsunyT52Hva5TnJeKP5yd1r+mH/ZU0mbYZflR0Z5kw5kITtKTRYMhm1JMClOFYdHnQszEvqw== + dependencies: + "@types/node" "*" + "@types/glob@^7.1.1": version "7.1.1" resolved "https://registry.yarnpkg.com/@types/glob/-/glob-7.1.1.tgz#aa59a1c6e3fbc421e07ccd31a944c30eba521575" diff --git a/samples/BookStore-Angular-MongoDb/aspnet-core/src/Acme.BookStore.Domain.Shared/Localization/BookStore/zh-Hans.json b/samples/BookStore-Angular-MongoDb/aspnet-core/src/Acme.BookStore.Domain.Shared/Localization/BookStore/zh-Hans.json index 459fc0fefd..23790bde50 100644 --- a/samples/BookStore-Angular-MongoDb/aspnet-core/src/Acme.BookStore.Domain.Shared/Localization/BookStore/zh-Hans.json +++ b/samples/BookStore-Angular-MongoDb/aspnet-core/src/Acme.BookStore.Domain.Shared/Localization/BookStore/zh-Hans.json @@ -3,6 +3,6 @@ "texts": { "Menu:Home": "首页", "Welcome": "欢迎", - "LongWelcomeMessage": "欢迎来到该应用程序. 这是一个基于ABP框架的启动项目. 有关更多信息, 请访问 cn.abp.io." + "LongWelcomeMessage": "欢迎来到该应用程序. 这是一个基于ABP框架的启动项目. 有关更多信息, 请访问 abp.io." } } \ No newline at end of file diff --git a/samples/BookStore-Modular/application/src/Acme.BookStore.Domain.Shared/Localization/BookStore/zh-Hans.json b/samples/BookStore-Modular/application/src/Acme.BookStore.Domain.Shared/Localization/BookStore/zh-Hans.json index 459fc0fefd..23790bde50 100644 --- a/samples/BookStore-Modular/application/src/Acme.BookStore.Domain.Shared/Localization/BookStore/zh-Hans.json +++ b/samples/BookStore-Modular/application/src/Acme.BookStore.Domain.Shared/Localization/BookStore/zh-Hans.json @@ -3,6 +3,6 @@ "texts": { "Menu:Home": "首页", "Welcome": "欢迎", - "LongWelcomeMessage": "欢迎来到该应用程序. 这是一个基于ABP框架的启动项目. 有关更多信息, 请访问 cn.abp.io." + "LongWelcomeMessage": "欢迎来到该应用程序. 这是一个基于ABP框架的启动项目. 有关更多信息, 请访问 abp.io." } } \ No newline at end of file diff --git a/samples/BookStore/src/Acme.BookStore.Domain.Shared/Localization/BookStore/zh-Hans.json b/samples/BookStore/src/Acme.BookStore.Domain.Shared/Localization/BookStore/zh-Hans.json index 86fe3582bb..a79ebcb9a8 100644 --- a/samples/BookStore/src/Acme.BookStore.Domain.Shared/Localization/BookStore/zh-Hans.json +++ b/samples/BookStore/src/Acme.BookStore.Domain.Shared/Localization/BookStore/zh-Hans.json @@ -3,7 +3,7 @@ "texts": { "Menu:Home": "首页", "Welcome": "欢迎", - "LongWelcomeMessage": "欢迎来到该应用程序. 这是一个基于ABP框架的启动项目. 有关更多信息, 请访问 cn.abp.io.", + "LongWelcomeMessage": "欢迎来到该应用程序. 这是一个基于ABP框架的启动项目. 有关更多信息, 请访问 abp.io.", "Menu:BookStore": "图书商店", "Menu:Books": "图书", "Name": "名称", diff --git a/samples/DashboardDemo/src/DashboardDemo.Domain.Shared/Localization/DashboardDemo/zh-Hans.json b/samples/DashboardDemo/src/DashboardDemo.Domain.Shared/Localization/DashboardDemo/zh-Hans.json index 459fc0fefd..23790bde50 100644 --- a/samples/DashboardDemo/src/DashboardDemo.Domain.Shared/Localization/DashboardDemo/zh-Hans.json +++ b/samples/DashboardDemo/src/DashboardDemo.Domain.Shared/Localization/DashboardDemo/zh-Hans.json @@ -3,6 +3,6 @@ "texts": { "Menu:Home": "首页", "Welcome": "欢迎", - "LongWelcomeMessage": "欢迎来到该应用程序. 这是一个基于ABP框架的启动项目. 有关更多信息, 请访问 cn.abp.io." + "LongWelcomeMessage": "欢迎来到该应用程序. 这是一个基于ABP框架的启动项目. 有关更多信息, 请访问 abp.io." } } \ No newline at end of file diff --git a/samples/MicroserviceDemo/applications/AuthServer.Host/AuthServer.Host.csproj b/samples/MicroserviceDemo/applications/AuthServer.Host/AuthServer.Host.csproj index 158c9360ed..c828edc0ae 100644 --- a/samples/MicroserviceDemo/applications/AuthServer.Host/AuthServer.Host.csproj +++ b/samples/MicroserviceDemo/applications/AuthServer.Host/AuthServer.Host.csproj @@ -29,6 +29,7 @@ + diff --git a/samples/MicroserviceDemo/applications/AuthServer.Host/AuthServerHostModule.cs b/samples/MicroserviceDemo/applications/AuthServer.Host/AuthServerHostModule.cs index 7ff9ae7c51..9c9ccd2a99 100644 --- a/samples/MicroserviceDemo/applications/AuthServer.Host/AuthServerHostModule.cs +++ b/samples/MicroserviceDemo/applications/AuthServer.Host/AuthServerHostModule.cs @@ -1,9 +1,10 @@ -using AuthServer.Host.EntityFrameworkCore; +using AuthServer.Host.EntityFrameworkCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using StackExchange.Redis; using Volo.Abp; +using Volo.Abp.Account; using Volo.Abp.Account.Web; using Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic; using Volo.Abp.Auditing; @@ -34,6 +35,7 @@ namespace AuthServer.Host typeof(AbpSettingManagementEntityFrameworkCoreModule), typeof(AbpIdentityEntityFrameworkCoreModule), typeof(AbpIdentityApplicationContractsModule), + typeof(AbpAccountApplicationModule), typeof(AbpIdentityServerEntityFrameworkCoreModule), typeof(AbpEntityFrameworkCoreSqlServerModule), typeof(AbpAccountWebIdentityServerModule), diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Domain.Shared/Localization/MyProjectName/zh-Hans.json b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Domain.Shared/Localization/MyProjectName/zh-Hans.json index 459fc0fefd..23790bde50 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Domain.Shared/Localization/MyProjectName/zh-Hans.json +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Domain.Shared/Localization/MyProjectName/zh-Hans.json @@ -3,6 +3,6 @@ "texts": { "Menu:Home": "首页", "Welcome": "欢迎", - "LongWelcomeMessage": "欢迎来到该应用程序. 这是一个基于ABP框架的启动项目. 有关更多信息, 请访问 cn.abp.io." + "LongWelcomeMessage": "欢迎来到该应用程序. 这是一个基于ABP框架的启动项目. 有关更多信息, 请访问 abp.io." } } \ No newline at end of file diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Domain/Data/MyProjectNameDbMigrationService.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Domain/Data/MyProjectNameDbMigrationService.cs index f6fd008e66..cde75d4ca7 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Domain/Data/MyProjectNameDbMigrationService.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Domain/Data/MyProjectNameDbMigrationService.cs @@ -1,8 +1,12 @@ -using System.Threading.Tasks; +using System; +using System.Linq; +using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Volo.Abp.Data; using Volo.Abp.DependencyInjection; +using Volo.Abp.MultiTenancy; +using Volo.Abp.TenantManagement; namespace MyCompanyName.MyProjectName.Data { @@ -12,13 +16,19 @@ namespace MyCompanyName.MyProjectName.Data private readonly IDataSeeder _dataSeeder; private readonly IMyProjectNameDbSchemaMigrator _dbSchemaMigrator; + private readonly ITenantRepository _tenantRepository; + private readonly ICurrentTenant _currentTenant; public MyProjectNameDbMigrationService( IDataSeeder dataSeeder, - IMyProjectNameDbSchemaMigrator dbSchemaMigrator) + IMyProjectNameDbSchemaMigrator dbSchemaMigrator, + ITenantRepository tenantRepository, + ICurrentTenant currentTenant) { _dataSeeder = dataSeeder; _dbSchemaMigrator = dbSchemaMigrator; + _tenantRepository = tenantRepository; + _currentTenant = currentTenant; Logger = NullLogger.Instance; } @@ -27,13 +37,43 @@ namespace MyCompanyName.MyProjectName.Data { Logger.LogInformation("Started database migrations..."); - Logger.LogInformation("Migrating database schema..."); + await MigrateHostDatabaseAsync(); + + var i = 0; + var tenants = await _tenantRepository.GetListAsync(); + foreach (var tenant in tenants) + { + i++; + + using (_currentTenant.Change(tenant.Id)) + { + Logger.LogInformation($"Migrating {tenant.Name} database schema... ({i} of {tenants.Count})"); + await MigrateTenantDatabasesAsync(tenant); + Logger.LogInformation($"Successfully completed {tenant.Name} database migrations."); + } + } + + Logger.LogInformation("Successfully completed database migrations."); + } + + private async Task MigrateHostDatabaseAsync() + { + Logger.LogInformation("Migrating host database schema..."); await _dbSchemaMigrator.MigrateAsync(); - Logger.LogInformation("Executing database seed..."); + Logger.LogInformation("Executing host database seed..."); await _dataSeeder.SeedAsync(); - Logger.LogInformation("Successfully completed database migrations."); + Logger.LogInformation("Successfully completed host database migrations."); + } + + private async Task MigrateTenantDatabasesAsync(Tenant tenant) + { + Logger.LogInformation($"Migrating schema for {tenant.Name} database..."); + await _dbSchemaMigrator.MigrateAsync(); + + Logger.LogInformation($"Executing {tenant.Name} tenant database seed..."); + await _dataSeeder.SeedAsync(tenant.Id); } } } \ No newline at end of file diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.EntityFrameworkCore.DbMigrations/EntityFrameworkCore/EntityFrameworkCoreMyProjectNameDbSchemaMigrator.cs b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.EntityFrameworkCore.DbMigrations/EntityFrameworkCore/EntityFrameworkCoreMyProjectNameDbSchemaMigrator.cs index 7064697d1a..71bd4e9059 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.EntityFrameworkCore.DbMigrations/EntityFrameworkCore/EntityFrameworkCoreMyProjectNameDbSchemaMigrator.cs +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.EntityFrameworkCore.DbMigrations/EntityFrameworkCore/EntityFrameworkCoreMyProjectNameDbSchemaMigrator.cs @@ -1,24 +1,36 @@ -using System.Threading.Tasks; +using System; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using MyCompanyName.MyProjectName.Data; using Volo.Abp.DependencyInjection; namespace MyCompanyName.MyProjectName.EntityFrameworkCore { [Dependency(ReplaceServices = true)] - public class EntityFrameworkCoreMyProjectNameDbSchemaMigrator + public class EntityFrameworkCoreMyProjectNameDbSchemaMigrator : IMyProjectNameDbSchemaMigrator, ITransientDependency { - private readonly MyProjectNameMigrationsDbContext _dbContext; + private readonly IServiceProvider _serviceProvider; - public EntityFrameworkCoreMyProjectNameDbSchemaMigrator(MyProjectNameMigrationsDbContext dbContext) + public EntityFrameworkCoreMyProjectNameDbSchemaMigrator( + IServiceProvider serviceProvider) { - _dbContext = dbContext; + _serviceProvider = serviceProvider; } public async Task MigrateAsync() { - await _dbContext.Database.MigrateAsync(); + /* We intentionally resolving the MyProjectNameMigrationsDbContext + * from IServiceProvider (instead of directly injecting it) + * to properly get the connection string of the current tenant in the + * current scope. + */ + + await _serviceProvider + .GetRequiredService() + .Database + .MigrateAsync(); } } } \ No newline at end of file