-
-
- @MultiTenancyStringLocalizer["Tenant"]
-
- @if (CurrentTenant.Id == null)
- {
-
- @MultiTenancyStringLocalizer["NotSelected"]
-
- }
- else
- {
- @(CurrentTenant.Name ?? CurrentTenant.Id.Value.ToString())
- }
-
-
-
-
@MultiTenancyStringLocalizer["Switch"]
+ (TenantResolveResultAccessor.Result?.AppliedResolvers?.Contains(CookieTenantResolveContributor.ContributorName) == true))
+ {
+
+
+
+
+ @MultiTenancyStringLocalizer["Tenant"]
+
+ @if (CurrentTenant.Id == null)
+ {
+
+ @MultiTenancyStringLocalizer["NotSelected"]
+
+ }
+ else
+ {
+ @(CurrentTenant.Name ?? CurrentTenant.Id.Value.ToString())
+ }
+
+
+
-
}
@(await Component.InvokeAsync
())
@RenderBody()
diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc/Microsoft/AspNetCore/Http/AbpFormFileExtensions.cs b/framework/src/Volo.Abp.AspNetCore.Mvc/Microsoft/AspNetCore/Http/AbpFormFileExtensions.cs
index c808250a3e..31768b5e6a 100644
--- a/framework/src/Volo.Abp.AspNetCore.Mvc/Microsoft/AspNetCore/Http/AbpFormFileExtensions.cs
+++ b/framework/src/Volo.Abp.AspNetCore.Mvc/Microsoft/AspNetCore/Http/AbpFormFileExtensions.cs
@@ -1,4 +1,5 @@
using System.IO;
+using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Http
{
@@ -11,5 +12,13 @@ namespace Microsoft.AspNetCore.Http
return stream.GetAllBytes();
}
}
+
+ public static async Task GetAllBytesAsync(this IFormFile file)
+ {
+ using (var stream = file.OpenReadStream())
+ {
+ return await stream.GetAllBytesAsync();
+ }
+ }
}
}
diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcModule.cs b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcModule.cs
index 06ce49551b..21a675ddc4 100644
--- a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcModule.cs
+++ b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcModule.cs
@@ -43,21 +43,6 @@ namespace Volo.Abp.AspNetCore.Mvc
public override void ConfigureServices(ServiceConfigurationContext context)
{
- //Configure Razor
- context.Services.Insert(0,
- ServiceDescriptor.Singleton>(
- new ConfigureOptions(options =>
- {
- options.FileProviders.Add(
- new RazorViewEngineVirtualFileProvider(
- context.Services.GetSingletonInstance>()
- )
- );
- }
- )
- )
- );
-
Configure(options =>
{
options.IgnoredInterfaces.AddIfNotContains(typeof(IAsyncActionFilter));
@@ -101,7 +86,16 @@ namespace Volo.Abp.AspNetCore.Mvc
};
})
.AddViewLocalization(); //TODO: How to configure from the application? Also, consider to move to a UI module since APIs does not care about it.
-
+
+ Configure(options =>
+ {
+ options.FileProviders.Add(
+ new RazorViewEngineVirtualFileProvider(
+ context.Services.GetSingletonInstance>()
+ )
+ );
+ });
+
context.Services.ExecutePreConfiguredActions(mvcBuilder);
//TODO: AddViewLocalization by default..?
diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApiExploring/AbpApiDefinitionController.cs b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApiExploring/AbpApiDefinitionController.cs
index ae72975486..e1c2d1f859 100644
--- a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApiExploring/AbpApiDefinitionController.cs
+++ b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApiExploring/AbpApiDefinitionController.cs
@@ -14,9 +14,9 @@ namespace Volo.Abp.AspNetCore.Mvc.ApiExploring
}
[HttpGet]
- public ApplicationApiDescriptionModel Get()
+ public ApplicationApiDescriptionModel Get(ApplicationApiDescriptionModelRequestDto model)
{
- return _modelProvider.CreateApiModel();
+ return _modelProvider.CreateApiModel(model);
}
}
}
diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApplicationConfigurations/AbpApplicationConfigurationAppService.cs b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApplicationConfigurations/AbpApplicationConfigurationAppService.cs
index 69f75a31b2..4b4cf521c2 100644
--- a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApplicationConfigurations/AbpApplicationConfigurationAppService.cs
+++ b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApplicationConfigurations/AbpApplicationConfigurationAppService.cs
@@ -8,9 +8,11 @@ using System.Globalization;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Volo.Abp.Application.Services;
+using Volo.Abp.AspNetCore.Mvc.MultiTenancy;
using Volo.Abp.Authorization;
using Volo.Abp.Features;
using Volo.Abp.Localization;
+using Volo.Abp.MultiTenancy;
using Volo.Abp.Settings;
using Volo.Abp.Users;
@@ -19,6 +21,7 @@ namespace Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations
public class AbpApplicationConfigurationAppService : ApplicationService, IAbpApplicationConfigurationAppService
{
private readonly AbpLocalizationOptions _localizationOptions;
+ private readonly AbpMultiTenancyOptions _multiTenancyOptions;
private readonly IServiceProvider _serviceProvider;
private readonly IAbpAuthorizationPolicyProvider _abpAuthorizationPolicyProvider;
private readonly IAuthorizationService _authorizationService;
@@ -30,6 +33,7 @@ namespace Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations
public AbpApplicationConfigurationAppService(
IOptions localizationOptions,
+ IOptions multiTenancyOptions,
IServiceProvider serviceProvider,
IAbpAuthorizationPolicyProvider abpAuthorizationPolicyProvider,
IAuthorizationService authorizationService,
@@ -48,6 +52,7 @@ namespace Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations
_featureDefinitionManager = featureDefinitionManager;
_languageProvider = languageProvider;
_localizationOptions = localizationOptions.Value;
+ _multiTenancyOptions = multiTenancyOptions.Value;
}
public virtual async Task GetAsync()
@@ -60,11 +65,31 @@ namespace Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations
Features = await GetFeaturesConfigAsync(),
Localization = await GetLocalizationConfigAsync(),
CurrentUser = GetCurrentUser(),
- Setting = await GetSettingConfigAsync()
+ Setting = await GetSettingConfigAsync(),
+ MultiTenancy = GetMultiTenancy(),
+ CurrentTenant = GetCurrentTenant()
};
}
+ protected virtual CurrentTenantDto GetCurrentTenant()
+ {
+ return new CurrentTenantDto()
+ {
+ Id = CurrentTenant.Id,
+ Name = CurrentTenant.Name,
+ IsAvailable = CurrentTenant.IsAvailable
+ };
+ }
+
+ protected virtual MultiTenancyInfoDto GetMultiTenancy()
+ {
+ return new MultiTenancyInfoDto
+ {
+ IsEnabled = _multiTenancyOptions.IsEnabled
+ };
+ }
+
protected virtual CurrentUserDto GetCurrentUser()
{
return new CurrentUserDto
diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs
index 3069d72e9d..aefad0f02e 100644
--- a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs
+++ b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
+using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
@@ -12,10 +13,13 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Volo.Abp.Application.Services;
+using Volo.Abp.AspNetCore.Mvc.ApiExploring;
using Volo.Abp.AspNetCore.Mvc.Conventions;
using Volo.Abp.AspNetCore.Mvc.Utils;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Http.Modeling;
+using Volo.Abp.Reflection;
+using Volo.Abp.Threading;
namespace Volo.Abp.AspNetCore.Mvc
{
@@ -39,7 +43,7 @@ namespace Volo.Abp.AspNetCore.Mvc
Logger = NullLogger.Instance;
}
- public ApplicationApiDescriptionModel CreateApiModel()
+ public ApplicationApiDescriptionModel CreateApiModel(ApplicationApiDescriptionModelRequestDto input)
{
//TODO: Can cache the model?
@@ -54,19 +58,22 @@ namespace Volo.Abp.AspNetCore.Mvc
continue;
}
- AddApiDescriptionToModel(apiDescription, model);
+ AddApiDescriptionToModel(apiDescription, model, input);
}
}
return model;
}
- private void AddApiDescriptionToModel(ApiDescription apiDescription, ApplicationApiDescriptionModel model)
+ private void AddApiDescriptionToModel(
+ ApiDescription apiDescription,
+ ApplicationApiDescriptionModel applicationModel,
+ ApplicationApiDescriptionModelRequestDto input)
{
var controllerType = apiDescription.ActionDescriptor.AsControllerActionDescriptor().ControllerTypeInfo.AsType();
var setting = FindSetting(controllerType);
- var moduleModel = model.GetOrAddModule(GetRootPath(controllerType, setting));
+ var moduleModel = applicationModel.GetOrAddModule(GetRootPath(controllerType, setting));
var controllerModel = moduleModel.GetOrAddController(controllerType.FullName, CalculateControllerName(controllerType, setting), controllerType, _modelOptions.IgnoredInterfaces);
@@ -80,6 +87,7 @@ namespace Volo.Abp.AspNetCore.Mvc
}
Logger.LogDebug($"ActionApiDescriptionModel.Create: {controllerModel.ControllerName}.{uniqueMethodName}");
+
var actionModel = controllerModel.AddAction(uniqueMethodName, ActionApiDescriptionModel.Create(
uniqueMethodName,
method,
@@ -88,6 +96,11 @@ namespace Volo.Abp.AspNetCore.Mvc
GetSupportedVersions(controllerType, method, setting)
));
+ if (input.IncludeTypes)
+ {
+ AddCustomTypesToModel(applicationModel, method);
+ }
+
AddParameterDescriptionsToModel(actionModel, method, apiDescription);
}
@@ -149,6 +162,68 @@ namespace Volo.Abp.AspNetCore.Mvc
return supportedVersions.Select(v => v.ToString()).Distinct().ToList();
}
+ private void AddCustomTypesToModel(ApplicationApiDescriptionModel applicationModel, MethodInfo method)
+ {
+ foreach (var parameterInfo in method.GetParameters())
+ {
+ AddCustomTypesToModel(applicationModel, parameterInfo.ParameterType);
+ }
+
+ AddCustomTypesToModel(applicationModel, method.ReturnType);
+ }
+
+ private static void AddCustomTypesToModel(ApplicationApiDescriptionModel applicationModel, [CanBeNull] Type type)
+ {
+ if (type == null)
+ {
+ return;
+ }
+
+ type = AsyncHelper.UnwrapTask(type);
+
+ if (type == typeof(object) ||
+ type == typeof(void) ||
+ type == typeof(Enum) ||
+ type == typeof(ValueType) ||
+ TypeHelper.IsPrimitiveExtended(type))
+ {
+ return;
+ }
+
+ if (TypeHelper.IsEnumerable(type, out var itemType))
+ {
+ AddCustomTypesToModel(applicationModel, itemType);
+ return;
+ }
+
+ if (TypeHelper.IsDictionary(type, out var keyType, out var valueType))
+ {
+ AddCustomTypesToModel(applicationModel, keyType);
+ AddCustomTypesToModel(applicationModel, valueType);
+ return;
+ }
+
+ /* TODO: Add interfaces
+ */
+
+ var typeName = ModelingTypeHelper.GetFullNameHandlingNullableAndGenerics(type);
+
+ if (applicationModel.Types.ContainsKey(typeName))
+ {
+ return;
+ }
+
+ var typeModel = TypeApiDescriptionModel.Create(type);
+ applicationModel.Types[typeName] = typeModel;
+
+ AddCustomTypesToModel(applicationModel, type.BaseType);
+
+ foreach (var propertyInfo in type.GetProperties())
+ {
+ AddCustomTypesToModel(applicationModel, propertyInfo.PropertyType);
+ }
+ }
+
private void AddParameterDescriptionsToModel(ActionApiDescriptionModel actionModel, MethodInfo method, ApiDescription apiDescription)
{
if (!apiDescription.ParameterDescriptions.Any())
diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Conventions/AbpServiceConvention.cs b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Conventions/AbpServiceConvention.cs
index 9875ccd808..0254a6022b 100644
--- a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Conventions/AbpServiceConvention.cs
+++ b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Conventions/AbpServiceConvention.cs
@@ -12,6 +12,7 @@ using Volo.Abp.Application.Services;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Http;
using Volo.Abp.Http.Modeling;
+using Volo.Abp.Http.ProxyScripting.Generators;
using Volo.Abp.Reflection;
namespace Volo.Abp.AspNetCore.Mvc.Conventions
@@ -81,7 +82,7 @@ namespace Volo.Abp.AspNetCore.Mvc.Conventions
continue;
}
- if (!TypeHelper.IsPrimitiveExtended(prm.ParameterInfo.ParameterType))
+ if (!TypeHelper.IsPrimitiveExtended(prm.ParameterInfo.ParameterType, includeEnums: true))
{
if (CanUseFormBodyBinding(action, prm))
{
@@ -94,7 +95,15 @@ namespace Volo.Abp.AspNetCore.Mvc.Conventions
protected virtual bool CanUseFormBodyBinding(ActionModel action, ParameterModel parameter)
{
- if (_options.ConventionalControllers.FormBodyBindingIgnoredTypes.Any(t => t.IsAssignableFrom(parameter.ParameterInfo.ParameterType)))
+ //We want to use "id" as path parameter, not body!
+ if (parameter.ParameterName == "id")
+ {
+ return false;
+ }
+
+ if (_options.ConventionalControllers
+ .FormBodyBindingIgnoredTypes
+ .Any(t => t.IsAssignableFrom(parameter.ParameterInfo.ParameterType)))
{
return false;
}
@@ -251,7 +260,7 @@ namespace Volo.Abp.AspNetCore.Mvc.Conventions
if (!selector.ActionConstraints.OfType().Any())
{
- selector.ActionConstraints.Add(new HttpMethodActionConstraint(new[] {httpMethod}));
+ selector.ActionConstraints.Add(new HttpMethodActionConstraint(new[] { httpMethod }));
}
}
}
@@ -295,9 +304,24 @@ namespace Volo.Abp.AspNetCore.Mvc.Conventions
var url = $"api/{rootPath}/{controllerNameInUrl.ToCamelCase()}";
//Add {id} path if needed
- if (action.Parameters.Any(p => p.ParameterName == "id"))
+ var idParameterModel = action.Parameters.FirstOrDefault(p => p.ParameterName == "id");
+ if (idParameterModel != null)
{
- url += "/{id}";
+ if (TypeHelper.IsPrimitiveExtended(idParameterModel.ParameterType, includeEnums: true))
+ {
+ url += "/{id}";
+ }
+ else
+ {
+ var properties = idParameterModel
+ .ParameterType
+ .GetProperties(BindingFlags.Instance | BindingFlags.Public);
+
+ foreach (var property in properties)
+ {
+ url += "/{" + property.Name + "}";
+ }
+ }
}
//Add action name if needed
@@ -341,7 +365,7 @@ namespace Volo.Abp.AspNetCore.Mvc.Conventions
protected virtual string NormalizeUrlControllerName(string rootPath, string controllerName, ActionModel action, string httpMethod, [CanBeNull] ConventionalControllerSetting configuration)
{
- if(configuration?.UrlControllerNameNormalizer == null)
+ if (configuration?.UrlControllerNameNormalizer == null)
{
return controllerName;
}
@@ -364,7 +388,7 @@ namespace Volo.Abp.AspNetCore.Mvc.Conventions
protected virtual bool IsEmptySelector(SelectorModel selector)
{
- return selector.AttributeRouteModel == null
+ return selector.AttributeRouteModel == null
&& selector.ActionConstraints.IsNullOrEmpty()
&& selector.EndpointMetadata.IsNullOrEmpty();
}
diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkerBase.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkerBase.cs
index 1ce71ca3f9..3326c4e65f 100644
--- a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkerBase.cs
+++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkerBase.cs
@@ -1,5 +1,7 @@
+using System;
using System.Threading;
using System.Threading.Tasks;
+using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
@@ -11,14 +13,34 @@ namespace Volo.Abp.BackgroundWorkers
public abstract class BackgroundWorkerBase : IBackgroundWorker
{
//TODO: Add UOW, Localization and other useful properties..?
+ public IServiceProvider ServiceProvider { get; set; }
+ protected readonly object ServiceProviderLock = new object();
- public ILogger Logger { protected get; set; }
+ protected TService LazyGetRequiredService(ref TService reference)
+ => LazyGetRequiredService(typeof(TService), ref reference);
- protected BackgroundWorkerBase()
+ protected TRef LazyGetRequiredService(Type serviceType, ref TRef reference)
{
- Logger = NullLogger.Instance;
+ if (reference == null)
+ {
+ lock (ServiceProviderLock)
+ {
+ if (reference == null)
+ {
+ reference = (TRef)ServiceProvider.GetRequiredService(serviceType);
+ }
+ }
+ }
+
+ return reference;
}
-
+
+ public ILoggerFactory LoggerFactory => LazyGetRequiredService(ref _loggerFactory);
+ private ILoggerFactory _loggerFactory;
+
+ protected ILogger Logger => _lazyLogger.Value;
+ private Lazy _lazyLogger => new Lazy(() => LoggerFactory?.CreateLogger(GetType().FullName) ?? NullLogger.Instance, true);
+
public virtual Task StartAsync(CancellationToken cancellationToken = default)
{
Logger.LogDebug("Started background worker: " + ToString());
diff --git a/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkersApplicationInitializationContextExtensions.cs b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkersApplicationInitializationContextExtensions.cs
new file mode 100644
index 0000000000..ccb3beac5d
--- /dev/null
+++ b/framework/src/Volo.Abp.BackgroundWorkers/Volo/Abp/BackgroundWorkers/BackgroundWorkersApplicationInitializationContextExtensions.cs
@@ -0,0 +1,38 @@
+using System;
+using JetBrains.Annotations;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Volo.Abp.BackgroundWorkers
+{
+ public static class BackgroundWorkersApplicationInitializationContextExtensions
+ {
+ public static ApplicationInitializationContext AddBackgroundWorker([NotNull] this ApplicationInitializationContext context)
+ where TWorker : IBackgroundWorker
+ {
+ Check.NotNull(context, nameof(context));
+
+ context.AddBackgroundWorker(typeof(TWorker));
+
+ return context;
+ }
+
+ public static ApplicationInitializationContext AddBackgroundWorker([NotNull] this ApplicationInitializationContext context, [NotNull] Type workerType)
+ {
+ Check.NotNull(context, nameof(context));
+ Check.NotNull(workerType, nameof(workerType));
+
+ if (!workerType.IsAssignableTo())
+ {
+ throw new AbpException($"Given type ({workerType.AssemblyQualifiedName}) must implement the {typeof(IBackgroundWorker).AssemblyQualifiedName} interface, but it doesn't!");
+ }
+
+ context.ServiceProvider
+ .GetRequiredService()
+ .Add(
+ (IBackgroundWorker)context.ServiceProvider.GetRequiredService(workerType)
+ );
+
+ return context;
+ }
+ }
+}
diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/AbpCliCoreModule.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/AbpCliCoreModule.cs
index 63fb4f8eee..f5a5a44980 100644
--- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/AbpCliCoreModule.cs
+++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/AbpCliCoreModule.cs
@@ -28,10 +28,11 @@ namespace Volo.Abp.Cli
options.Commands["add-package"] = typeof(AddPackageCommand);
options.Commands["add-module"] = typeof(AddModuleCommand);
options.Commands["login"] = typeof(LoginCommand);
- options.Commands["logout"] = typeof(LogoutCommand);
+ options.Commands["logout"] = typeof(LogoutCommand);
+ options.Commands["generate-proxy"] = typeof(GenerateProxyCommand);
options.Commands["suite"] = typeof(SuiteCommand);
options.Commands["switch-to-preview"] = typeof(SwitchNightlyPreviewCommand);
- options.Commands["switch-to-stable"] = typeof(SwitchStableCommand);
+ options.Commands["switch-to-stable"] = typeof(SwitchStableCommand);
});
}
}
diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/GenerateProxyCommand.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/GenerateProxyCommand.cs
new file mode 100644
index 0000000000..17fe2d3781
--- /dev/null
+++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Commands/GenerateProxyCommand.cs
@@ -0,0 +1,731 @@
+using System;
+using System.IO;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+using Newtonsoft.Json.Linq;
+using Volo.Abp.Cli.Args;
+using Volo.Abp.Cli.ProjectBuilding;
+using Volo.Abp.Cli.ProjectBuilding.Building;
+using Volo.Abp.DependencyInjection;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+
+namespace Volo.Abp.Cli.Commands
+{
+ public class GenerateProxyCommand : IConsoleCommand, ITransientDependency
+ {
+ public static Dictionary> propertyList = new Dictionary>();
+ public ILogger Logger { get; set; }
+
+ protected TemplateProjectBuilder TemplateProjectBuilder { get; }
+
+ public GenerateProxyCommand(TemplateProjectBuilder templateProjectBuilder)
+ {
+ TemplateProjectBuilder = templateProjectBuilder;
+
+ Logger = NullLogger.Instance;
+ }
+
+ public async Task ExecuteAsync(CommandLineArgs commandLineArgs)
+ {
+ var angularPath = $"angular.json";
+ if (!File.Exists(angularPath))
+ {
+ throw new CliUsageException(
+ "angular.json file not found. You must run this command in angular folder." +
+ Environment.NewLine + Environment.NewLine +
+ GetUsageInfo()
+ );
+ }
+
+ var module = commandLineArgs.Options.GetOrNull(Options.Module.Short, Options.Module.Long);
+ module = module == null ? "app" : module.ToLower();
+
+ var apiUrl = commandLineArgs.Options.GetOrNull(Options.ApiUrl.Short, Options.ApiUrl.Long);
+ if (string.IsNullOrWhiteSpace(apiUrl))
+ {
+ var environmentJson = File.ReadAllText("src/environments/environment.ts").Split("export const environment = ")[1].Replace(";", " ");
+ var environment = JObject.Parse(environmentJson);
+ apiUrl = environment["apis"]["default"]["url"].ToString();
+ }
+ apiUrl += "/api/abp/api-definition?IncludeTypes=true";
+
+ var uiFramework = GetUiFramework(commandLineArgs);
+
+ WebClient client = new WebClient();
+ string json = client.DownloadString(apiUrl);
+ //var sr = File.OpenText("api-definition.json");
+ //var json = sr.ReadToEnd();
+
+ Logger.LogInformation("Downloading api definition...");
+ Logger.LogInformation("Api Url: " + apiUrl);
+
+ var data = JObject.Parse(json);
+
+ Logger.LogInformation("Modules are combining");
+ var moduleList = GetCombinedModules(data, module);
+
+ if (moduleList.Count < 1)
+ {
+ throw new CliUsageException(
+ "Module can not find!" +
+ Environment.NewLine + Environment.NewLine +
+ GetUsageInfo()
+ );
+ }
+
+ Logger.LogInformation("Modules and types are creating");
+
+ foreach (var moduleItem in moduleList)
+ {
+ var moduleValue = JObject.Parse(moduleItem.Value);
+
+ var rootPath = moduleItem.Key;
+
+ Logger.LogInformation($"{rootPath} directory is creating");
+
+ Directory.CreateDirectory($"src/app/{rootPath}/shared/models");
+ Directory.CreateDirectory($"src/app/{rootPath}/shared/services");
+
+ var serviceIndexList = new List();
+ var modelIndexList = new List();
+
+ foreach (var controller in moduleValue.Root.ToList().Select(item => item.First))
+ {
+ var serviceFileText = new StringBuilder();
+
+ serviceFileText.AppendLine("[firstTypeList]");
+ serviceFileText.AppendLine("import { Injectable } from '@angular/core';");
+ serviceFileText.AppendLine("import { Observable } from 'rxjs';");
+ serviceFileText.AppendLine("[secondTypeList]");
+ serviceFileText.AppendLine("");
+ serviceFileText.AppendLine("@Injectable({providedIn: 'root'})");
+ serviceFileText.AppendLine("export class [controllerName]Service {");
+ serviceFileText.AppendLine(" constructor(private restService: RestService) {}");
+ serviceFileText.AppendLine("");
+
+ var firstTypeList = new List();
+ var secondTypeList = new List();
+
+ var controllerName = (string)controller["controllerName"];
+ var controllerServiceName = controllerName.PascalToKebabCase() + ".service.ts";
+
+ foreach (var actionItem in controller["actions"])
+ {
+ var action = actionItem.First;
+ var actionName = (string)action["uniqueName"];
+
+ actionName = (char.ToLower(actionName[0]) + actionName.Substring(1)).Replace("Async", "").Replace("Controller", "");
+
+ var returnValueType = (string)action["returnValue"]["type"];
+
+ var parameters = action["parameters"];
+ var parametersText = new StringBuilder();
+ var parametersIndex = 0;
+ var bodyExtra = "";
+ var modelBindingExtra = "";
+ var modelBindingExtraList = new List();
+ var parameterModel = new List();
+
+ foreach (var parameter in parameters.OrderBy(p => p["bindingSourceId"]))
+ {
+ var bindingSourceId = (string)parameter["bindingSourceId"];
+ bindingSourceId = char.ToLower(bindingSourceId[0]) + bindingSourceId.Substring(1);
+
+ var name = (string)parameter["name"];
+ var typeSimple = (string)parameter["typeSimple"];
+ var typeArray = ((string)parameter["type"]).Split(".");
+ var type = (typeArray[typeArray.Length - 1]).TrimEnd('>');
+ var isOptional = (bool)parameter["isOptional"];
+ var defaultValue = (string)parameter["defaultValue"];
+
+ var modelIndex = CreateType(data, (string)parameter["type"], rootPath, modelIndexList);
+
+ if (!string.IsNullOrWhiteSpace(modelIndex))
+ {
+ modelIndexList.Add(modelIndex);
+ }
+
+ if (bindingSourceId == "body")
+ {
+ bodyExtra = ", body";
+ parameterModel = AddParameter(bindingSourceId, type, isOptional, defaultValue, bindingSourceId, parameterModel);
+ }
+ else if (bindingSourceId == "path")
+ {
+ parameterModel = AddParameter(name, typeSimple, isOptional, defaultValue, bindingSourceId, parameterModel);
+ }
+ else if (bindingSourceId == "modelBinding")
+ {
+ var parameterNameOnMethod = (string)parameter["nameOnMethod"];
+
+ var parametersOnMethod = action["parametersOnMethod"];
+ foreach (var parameterOnMethod in parametersOnMethod)
+ {
+ var parametersOnMethodName = (string)parameterOnMethod["name"];
+ if (parametersOnMethodName == parameterNameOnMethod)
+ {
+ typeSimple = (string)parameterOnMethod["typeSimple"];
+ typeArray = ((string)parameterOnMethod["type"]).Split(".");
+ type = typeArray[typeArray.Length - 1];
+ isOptional = (bool)parameterOnMethod["isOptional"];
+ defaultValue = (string)parameterOnMethod["defaultValue"];
+
+ if (typeSimple == "string" || typeSimple == "boolean" || typeSimple == "number")
+ {
+ parameterModel = AddParameter(name, typeSimple, isOptional, defaultValue, bindingSourceId, parameterModel);
+ }
+
+ modelIndex = CreateType(data, (string)parameterOnMethod["type"], rootPath, modelIndexList);
+
+ if (!string.IsNullOrWhiteSpace(modelIndex))
+ {
+ modelIndexList.Add(modelIndex);
+ }
+ }
+ }
+
+ if (typeSimple != "string" && typeSimple != "boolean" && typeSimple != "number")
+ {
+ parametersText.Append($"params = {{}} as {type}");
+ modelBindingExtra = ", params";
+ if (!string.IsNullOrWhiteSpace(modelIndex))
+ {
+ secondTypeList.Add(type);
+ }
+ else {
+ firstTypeList.Add(type);
+ }
+ break;
+ }
+ }
+ }
+
+ if (parameterModel != null && parameterModel.Count > 0)
+ {
+ foreach (var parameterItem in parameterModel.OrderBy(p => p.DisplayOrder))
+ {
+ var parameterItemModelName = parameterItem.Type.PascalToKebabCase() + ".ts";
+ var parameterItemModelPath = $"src/app/{rootPath}/shared/models/{parameterItemModelName}";
+ if (parameterItem.BindingSourceId == "body" && !File.Exists(parameterItemModelPath))
+ {
+ parameterItem.Type = "any";
+ }
+
+ parametersIndex++;
+
+ if (parametersIndex > 1)
+ {
+ parametersText.Append(", ");
+ }
+
+ parametersText.Append(parameterItem.Name + (parameterItem.IsOptional ? "?" : "") + ": " + parameterItem.Type + (parameterItem.Value != null ? (" = " + (string.IsNullOrWhiteSpace(parameterItem.Value) ? "''" : parameterItem.Value)) : ""));
+
+ if (parameterItem.BindingSourceId == "modelBinding")
+ {
+ modelBindingExtraList.Add(parameterItem.Name);
+ }
+ else if (parameterItem.BindingSourceId == "body" && File.Exists(parameterItemModelPath))
+ {
+ secondTypeList.Add(parameterItem.Type);
+ }
+ }
+ }
+
+ if (returnValueType != null)
+ {
+ if (returnValueType.IndexOf('<') > -1)
+ {
+ var firstTypeArray = returnValueType.Split("<")[0].Split(".");
+ var firstType = firstTypeArray[firstTypeArray.Length - 1];
+
+ var secondTypeArray = returnValueType.Split("<")[1].Split(".");
+ var secondType = secondTypeArray[secondTypeArray.Length - 1].TrimEnd('>');
+
+ var secondTypeModelName = secondType.PascalToKebabCase() + ".ts";
+ var secondTypeModelPath = $"src/app/{rootPath}/shared/models/{secondTypeModelName}";
+ if (firstType == "List" && !File.Exists(secondTypeModelPath))
+ {
+ secondType = "any";
+ }
+
+ serviceFileText.AppendLine(
+ firstType == "List"
+ ? $" {actionName}({parametersText}): Observable<{secondType}[]> {{"
+ : $" {actionName}({parametersText}): Observable<{firstType}<{secondType}>> {{");
+
+ if (firstType != "List")
+ {
+ firstTypeList.Add(firstType);
+ }
+
+ if (secondType != "any")
+ {
+ secondTypeList.Add(secondType);
+ }
+ }
+ else
+ {
+ var typeArray = returnValueType.Split(".");
+ var type = typeArray[typeArray.Length - 1].TrimEnd('>');
+
+ type = type switch
+ {
+ "Void" => "void",
+ "String" => "string",
+ "IActionResult" => "void",
+ "ActionResult" => "void",
+ _ => type
+ };
+
+ serviceFileText.AppendLine(
+ $" {actionName}({parametersText}): Observable<{type}> {{");
+
+ if (type != "void" && type != "string")
+ {
+ secondTypeList.Add(type);
+ }
+ }
+
+ var modelIndex = CreateType(data, returnValueType, rootPath, modelIndexList);
+
+ if (!string.IsNullOrWhiteSpace(modelIndex))
+ {
+ modelIndexList.Add(modelIndex);
+ }
+ }
+
+ if (modelBindingExtraList != null && modelBindingExtraList.Count > 0)
+ {
+ modelBindingExtra = ", params: { " + string.Join(", ", modelBindingExtraList.ToArray()) + " }";
+ }
+
+ var url = ((string)action["url"]).Replace("/{", "/${");
+ var httpMethod = (string)action["httpMethod"];
+
+ serviceFileText.AppendLine(
+ url.Contains("${")
+ ? $" return this.restService.request({{ url: `/{url}`, method: '{httpMethod}'{bodyExtra}{modelBindingExtra} }});"
+ : $" return this.restService.request({{ url: '/{url}', method: '{httpMethod}'{bodyExtra}{modelBindingExtra} }});");
+
+
+ serviceFileText.AppendLine(" }");
+ }
+
+ serviceIndexList.Add(controllerServiceName.Replace(".ts", ""));
+
+ if (firstTypeList != null && firstTypeList.Count > 0)
+ {
+ var firstTypeListDistinct = ", " + string.Join(", ", firstTypeList.Where(p => p != "void").Distinct().ToArray());
+ serviceFileText.Replace("[firstTypeList]",
+ $"import {{ RestService {firstTypeListDistinct}}} from '@abp/ng.core';");
+ }
+ else
+ {
+ serviceFileText.Replace("[firstTypeList]",
+ $"import {{ RestService }} from '@abp/ng.core';");
+ }
+
+ if (secondTypeList != null && secondTypeList.Count > 0)
+ {
+ var secondTypeListDistinct = string.Join(", ", secondTypeList.Where(p => p != "void").Distinct().ToArray());
+ serviceFileText.Replace("[secondTypeList]",
+ $"import {{{secondTypeListDistinct}}} from '../models';");
+ }
+ else
+ {
+ serviceFileText.Replace("[secondTypeList]", "");
+ }
+
+ serviceFileText.AppendLine("}");
+
+ serviceFileText.Replace("[controllerName]", controllerName);
+ File.WriteAllText($"src/app/{rootPath}/shared/services/{controllerServiceName}", serviceFileText.ToString());
+ }
+
+ var serviceIndexFileText = new StringBuilder();
+
+ foreach (var serviceIndexItem in serviceIndexList.Distinct())
+ {
+ serviceIndexFileText.AppendLine($"export * from './{serviceIndexItem}';");
+ }
+
+ File.WriteAllText($"src/app/{rootPath}/shared/services/index.ts", serviceIndexFileText.ToString());
+
+ var modelIndexFileText = new StringBuilder();
+
+ foreach (var modelIndexItem in modelIndexList.Distinct())
+ {
+ modelIndexFileText.AppendLine($"export * from './{modelIndexItem}';");
+ }
+
+ File.WriteAllText($"src/app/{rootPath}/shared/models/index.ts", modelIndexFileText.ToString());
+ }
+
+ Logger.LogInformation("Completed!");
+ }
+
+ private Dictionary GetCombinedModules(JToken data, string module)
+ {
+ var moduleList = new Dictionary();
+
+ foreach (var moduleItem in data["modules"])
+ {
+ var rootPath = ((string)moduleItem.First["rootPath"]).ToLower();
+
+ if (moduleList.Any(p => p.Key == rootPath))
+ {
+ var value = moduleList[rootPath];
+
+ moduleList[rootPath] = value.TrimEnd('}') + "," + moduleItem.First["controllers"].ToString().TrimStart('{');
+ }
+ else
+ {
+ moduleList.Add(rootPath, moduleItem.First["controllers"].ToString());
+ }
+ }
+
+ if (module != "all")
+ {
+ moduleList = moduleList.Where(p => p.Key.ToLower() == module).ToDictionary(p => p.Key, s => s.Value);
+ }
+
+ return moduleList;
+ }
+
+ private static string CreateType(JObject data, string returnValueType, string rootPath, List modelIndexList)
+ {
+ var type = data["types"][returnValueType];
+
+ if (type == null)
+ {
+ return null;
+ }
+
+ if (returnValueType.StartsWith("Volo.Abp.Application.Dtos")
+ || returnValueType.StartsWith("System.Collections")
+ || returnValueType == "System.String"
+ || returnValueType == "System.Void"
+ || returnValueType.Contains("System.Net.HttpStatusCode?")
+ || returnValueType.Contains("IActionResult")
+ || returnValueType.Contains("ActionResult")
+ || returnValueType.Contains("IStringValueType")
+ || returnValueType.Contains("IValueValidator")
+ )
+ {
+ return null;
+ }
+
+ var typeNameSplit = returnValueType.Split(".");
+ var typeName = typeNameSplit[typeNameSplit.Length - 1];
+
+ if (typeName.Contains("HttpStatusCode"))
+ {
+
+ }
+
+ var typeModelName = typeName.Replace("<", "").Replace(">", "").Replace("?","").PascalToKebabCase() + ".ts";
+
+ var path = $"src/app/{rootPath}/shared/models/{typeModelName}";
+
+ var modelFileText = new StringBuilder();
+
+ var baseType = (string)type["baseType"];
+ var extends = "";
+ var customBaseTypeName = "";
+ var baseTypeName = "";
+
+ if (!string.IsNullOrWhiteSpace(baseType))
+ {
+ var baseTypeSplit = baseType.Split(".");
+ baseTypeName = baseTypeSplit[baseTypeSplit.Length - 1].Replace("<", "").Replace(">", "");
+ var baseTypeKebabCase = "./" + baseTypeName.PascalToKebabCase();
+
+ if (baseType != "System.Enum")
+ {
+ if (baseType.Contains("Volo.Abp.Application.Dtos"))
+ {
+ baseTypeKebabCase = "@abp/ng.core";
+
+ baseTypeName = baseType.Split("Volo.Abp.Application.Dtos")[1].Split("<")[0].TrimStart('.');
+ customBaseTypeName = baseType.Split("Volo.Abp.Application.Dtos")[1].Replace("System.Guid", "string").TrimStart('.');
+ }
+
+ if (baseTypeName.Contains("guid") || baseTypeName.Contains("Guid"))
+ {
+ baseTypeName = "string";
+ }
+
+ modelFileText.AppendLine($"import {{ {baseTypeName} }} from '{baseTypeKebabCase}';");
+ extends = "extends " + (!string.IsNullOrWhiteSpace(customBaseTypeName) ? customBaseTypeName : baseTypeName);
+
+ var modelIndex = CreateType(data, baseType, rootPath, modelIndexList);
+ if (!string.IsNullOrWhiteSpace(modelIndex))
+ {
+ modelIndexList.Add(modelIndex);
+ }
+ }
+ }
+
+ if (baseType == "System.Enum" && (bool)type["isEnum"])
+ {
+ modelFileText.AppendLine($"export enum {typeName} {{");
+
+ var enumNameList = type["enumNames"].ToArray();
+ var enumValueList = type["enumValues"].ToArray();
+
+ for (var i = 0; i < enumNameList.Length; i++)
+ {
+ modelFileText.AppendLine($" {enumNameList[i]} = {enumValueList[i]},");
+ }
+
+ modelFileText.AppendLine("}");
+ }
+ else
+ {
+ modelFileText.AppendLine("");
+ modelFileText.AppendLine($"export class {typeName} {extends} {{");
+
+ foreach (var property in type["properties"])
+ {
+ var propertyName = (string)property["name"];
+ propertyName = (char.ToLower(propertyName[0]) + propertyName.Substring(1));
+ var typeSimple = (string)property["typeSimple"];
+
+ var modelIndex = CreateType(data, (string)property["type"], rootPath, modelIndexList);
+
+ if (typeSimple.IndexOf("[") > -1 && typeSimple.IndexOf("]") > -1)
+ {
+ typeSimple = typeSimple.Replace("[", "").Replace("]", "") + "[]";
+ }
+
+ if (typeSimple.StartsWith("Volo.Abp"))
+ {
+ var typeSimpleSplit = typeSimple.Split(".");
+ typeSimple = typeSimpleSplit[typeSimpleSplit.Length - 1];
+ }
+
+ if (typeSimple.StartsWith("System.Object"))
+ {
+ typeSimple = typeSimple.Replace("System.Object", "object");
+ }
+
+ if (typeSimple.Contains("?"))
+ {
+ typeSimple = typeSimple.Replace("?", "");
+ propertyName += "?";
+ }
+
+ if (typeSimple != "boolean"
+ && typeSimple != "string"
+ && typeSimple != "number"
+ && typeSimple != "boolean[]"
+ && typeSimple != "string[]"
+ && typeSimple != "number[]"
+ )
+ {
+ var typeSimpleModelName = typeSimple.PascalToKebabCase() + ".ts";
+ var modelPath = $"src/app/{rootPath}/shared/models/{typeSimpleModelName}";
+ if (!File.Exists(modelPath))
+ {
+ typeSimple = "any" + (typeSimple.Contains("[]") ? "[]" : "");
+ }
+ }
+
+ if (propertyList.Any(p => p.Key == baseTypeName && p.Value.Any(q => q.Key == propertyName && q.Value == typeSimple)))
+ {
+ continue;
+ }
+
+ if (!string.IsNullOrWhiteSpace(modelIndex))
+ {
+ var propertyTypeSplit = ((string)property["type"]).Split(".");
+ var propertyType = propertyTypeSplit[propertyTypeSplit.Length - 1];
+ modelFileText.Insert(0, "");
+ modelFileText.Insert(0, $"import {{ {propertyType} }} from '../models';");
+ modelFileText.Insert(0, "");
+ modelIndexList.Add(modelIndex);
+ }
+
+ if (propertyList.Any(p => p.Key == typeName && !p.Value.Any(q => q.Key == propertyName)))
+ {
+ propertyList[typeName].Add(propertyName, typeSimple);
+ }
+ else if (!propertyList.Any(p => p.Key == typeName))
+ {
+ var newProperty = new Dictionary();
+ newProperty.Add(propertyName, typeSimple);
+ propertyList.Add(typeName, newProperty);
+ }
+
+ modelFileText.AppendLine($" {propertyName}: {typeSimple};");
+ }
+
+ modelFileText.AppendLine("");
+
+ modelFileText.AppendLine($" constructor(initialValues: Partial<{typeName}> = {{}}) {{");
+
+ if (!string.IsNullOrWhiteSpace(baseType))
+ {
+ modelFileText.AppendLine(" super(initialValues);");
+ modelFileText.AppendLine(" }");
+ }
+ else
+ {
+ modelFileText.AppendLine(" if (initialValues) {");
+ modelFileText.AppendLine(" for (const key in initialValues) {");
+ modelFileText.AppendLine(" if (initialValues.hasOwnProperty(key)) {");
+ modelFileText.AppendLine(" this[key] = initialValues[key];");
+
+ modelFileText.AppendLine(" }");
+ modelFileText.AppendLine(" }");
+ modelFileText.AppendLine(" }");
+ modelFileText.AppendLine(" }");
+ }
+
+ modelFileText.AppendLine("}");
+ }
+
+ File.WriteAllText($"src/app/{rootPath}/shared/models/{typeModelName}", modelFileText.ToString());
+
+ return typeModelName.Replace(".ts", "");
+ }
+
+ private static List