public virtual void Write(AspDotNetWriteConfiguration configuration, List <FileTemplate> files)
        {
            Logger.Trace("Generate generator controller for ASP.net...");
            if (!configuration.Language.IsCsharp())
            {
                throw new InvalidOperationException($"Can not generate ASP.net Controller for language {configuration.Language?.Name ?? "Empty"}. Only Csharp is currently implemented");
            }

            if (configuration.Standalone)
            {
                throw new InvalidOperationException("Can not generate Generator.Controller with KY.Generator.CLI.Standalone use KY.Generator.CLI instead");
            }
            string        nameSpace     = (configuration.GeneratorController.Namespace ?? configuration.Namespace).AssertIsNotNull(nameof(configuration.Namespace), "asp writer requires a namespace");
            ClassTemplate classTemplate = files.AddFile(configuration.GeneratorController.RelativePath ?? configuration.RelativePath, configuration.AddHeader)
                                          .AddNamespace(nameSpace)
                                          .AddClass("GeneratorController", Code.Type(configuration.Template.ControllerBase))
                                          .WithUsing("System")
                                          .WithUsing("System.Linq")
                                          .WithUsing("KY.Generator")
                                          .WithUsing("KY.Generator.Output");

            classTemplate.Usings.AddRange(configuration.Template.Usings);

            if (configuration.Template.UseOwnCache)
            {
                GenericTypeTemplate type = Code.Generic("Dictionary", Code.Type("string"), Code.Type("MemoryOutput"));
                classTemplate.AddField("cache", type)
                .FormatName(configuration)
                .Static()
                .Readonly()
                .DefaultValue = Code.New(type);
            }

            MethodTemplate createMethod = classTemplate.AddMethod("Create", Code.Type("string"))
                                          .FormatName(configuration)
                                          .WithParameter(Code.Type("string"), "configuration");

            if (!configuration.Template.ValidateInput)
            {
                createMethod.WithAttribute("ValidateInput", Code.Local("false"));
            }

            MethodTemplate commandMethod = classTemplate.AddMethod("Command", Code.Type("string"))
                                           .FormatName(configuration)
                                           .WithParameter(Code.Type("string"), "command");

            MultilineCodeFragment createCode = createMethod.Code;

            createCode.AddLine(Code.Declare(Code.Type("string"), "id", Code.Local("Guid").Method("NewGuid").Method("ToString")))
            .AddLine(Code.Declare(Code.Type("MemoryOutput"), "output", Code.New(Code.Type("MemoryOutput"))))
            .AddLine(Code.Declare(Code.Type("Generator"), "generator", Code.New(Code.Type("Generator"))))
            .AddLine(Code.Local("generator").Method("SetOutput", Code.Local("output")).Close());
            MultilineCodeFragment commandCode = commandMethod.Code;

            commandCode.AddLine(Code.Declare(Code.Type("string"), "id", Code.Local("Guid").Method("NewGuid").Method("ToString")))
            .AddLine(Code.Declare(Code.Type("MemoryOutput"), "output", Code.New(Code.Type("MemoryOutput"))))
            .AddLine(Code.Declare(Code.Type("Generator"), "generator", Code.New(Code.Type("Generator"))))
            .AddLine(Code.Local("generator").Method("SetOutput", Code.Local("output")).Close());
            foreach (string ns in configuration.GeneratorController.Usings)
            {
                classTemplate.AddUsing(ns);
            }
            foreach (string moduleType in configuration.GeneratorController.PreloadModules)
            {
                createCode.AddLine(Code.Local("generator").GenericMethod("PreloadModule", Code.Type(moduleType)).Close());
                commandCode.AddLine(Code.Local("generator").GenericMethod("PreloadModule", Code.Type(moduleType)).Close());
            }
            foreach (AspDotNetControllerConfigureModule configure in configuration.GeneratorController.Configures)
            {
                createCode.AddLine(Code.Local("generator").Method(configure.Module, Code.Lambda("x", Code.Csharp("x." + configure.Action))));
                commandCode.AddLine(Code.Local("generator").Method(configure.Module, Code.Lambda("x", Code.Csharp("x." + configure.Action))));
            }
            createCode.AddLine(Code.Local("generator").Method("ParseConfiguration", Code.Local("configuration")).Close())
            .AddLine(Code.Local("generator").Method("Run").Close())
            .AddBlankLine();
            commandCode.AddLine(Code.Local("generator").Method("ParseCommand", Code.Local("command")).Close())
            .AddLine(Code.Local("generator").Method("Run").Close())
            .AddBlankLine();
            if (configuration.Template.UseOwnCache)
            {
                createCode.AddLine(Code.Local("cache").Index(Code.Local("id")).Assign(Code.Local("output")).Close());
                commandCode.AddLine(Code.Local("cache").Index(Code.Local("id")).Assign(Code.Local("output")).Close());
            }
            else
            {
                createCode.AddLine(Code.Static(Code.Type("HttpContext")).Property("Current").Property("Cache").Index(Code.Local("id")).Assign(Code.Local("output")).Close());
                commandCode.AddLine(Code.Static(Code.Type("HttpContext")).Property("Current").Property("Cache").Index(Code.Local("id")).Assign(Code.Local("output")).Close());
            }
            createCode.AddLine(Code.Return(Code.Local("id")));
            commandCode.AddLine(Code.Return(Code.Local("id")));

            ChainedCodeFragment getFromCacheForFilesFragment = configuration.Template.UseOwnCache
                                                                   ? (ChainedCodeFragment)Code.Local("cache")
                                                                   : Code.Static(Code.Type("HttpContext")).Property("Current").Property("Cache");
            MethodTemplate getFilesMethod = classTemplate.AddMethod("GetFiles", Code.Type("string"))
                                            .FormatName(configuration)
                                            .WithParameter(Code.Type("string"), "id");

            getFilesMethod.Code.AddLine(Code.If(Code.Local("id").Equals().Null(), x => x.Code.AddLine(Code.Return(Code.Null()))))
            .AddLine(Code.Declare(Code.Type("MemoryOutput"), "output", getFromCacheForFilesFragment.Index(Code.Local("id")).As(Code.Type("MemoryOutput"))))
            .AddLine(Code.Return(Code.InlineIf(Code.Local("output").Equals().Null(),
                                               Code.Null(),
                                               Code.Local("string").Method("Join", Code.Local("Environment").Property("NewLine"),
                                                                           Code.Local("output").Property("Files").Method("Select", Code.Lambda("x", Code.Local("x").Property("Key")))))));

            ChainedCodeFragment getFromCacheForFileFragment = configuration.Template.UseOwnCache
                                                                  ? (ChainedCodeFragment)Code.Local("cache")
                                                                  : Code.Static(Code.Type("HttpContext")).Property("Current").Property("Cache");
            MethodTemplate getFileMethod = classTemplate.AddMethod("GetFile", Code.Type("string"))
                                           .FormatName(configuration)
                                           .WithParameter(Code.Type("string"), "id")
                                           .WithParameter(Code.Type("string"), "path");

            getFileMethod.Code.AddLine(Code.If(Code.Local("id").Equals().Null(), x => x.Code.AddLine(Code.Return(Code.Null()))))
            .AddLine(Code.Declare(Code.Type("MemoryOutput"), "output", getFromCacheForFileFragment.Index(Code.Local("id")).As(Code.Type("MemoryOutput"))))
            .AddLine(Code.Return(Code.InlineIf(Code.Local("output").Equals().Null().Or().Not().Local("output").Property("Files").Method("ContainsKey", Code.Local("path")),
                                               Code.Null(),
                                               Code.Local("output").Property("Files").Index(Code.Local("path")))));
            MethodTemplate availableMethod = classTemplate.AddMethod("Available", Code.Type("bool"))
                                             .FormatName(configuration);

            availableMethod.Code.AddLine(Code.Return(Code.Local("true")));

            if (configuration.Template.UseAttributes)
            {
                classTemplate.WithUsing("Microsoft.AspNetCore.Mvc")
                .WithAttribute("Route", Code.String("[controller]"))
                .WithAttribute("Route", Code.String("api/v1/[controller]"));
                createMethod.WithAttribute("HttpPost", Code.String("[action]"));
                commandMethod.WithAttribute("HttpPost", Code.String("[action]"));
                getFilesMethod.WithAttribute("HttpPost", Code.String("[action]"));
                getFileMethod.WithAttribute("HttpPost", Code.String("[action]"));
                availableMethod.WithAttribute("HttpGet", Code.String("[action]"));
            }
        }
Esempio n. 2
0
        public virtual void Write(AngularWriteConfiguration configuration, List <ITransferObject> transferObjects, List <FileTemplate> files)
        {
            Logger.Trace("Generate angular service for ASP.net controller...");
            if (!configuration.Language.IsTypeScript())
            {
                throw new InvalidOperationException($"Can not generate service for ASP.net Controller for language {configuration.Language?.Name ?? "Empty"}");
            }
            string httpClient       = configuration.Service.HttpClient?.Name ?? "HttpClient";
            string httpClientImport = configuration.Service.HttpClient?.Import ?? "@angular/common/http";

            foreach (HttpServiceTransferObject controller in transferObjects.OfType <HttpServiceTransferObject>())
            {
                Dictionary <HttpServiceActionParameterTransferObject, ParameterTemplate> mapping = new Dictionary <HttpServiceActionParameterTransferObject, ParameterTemplate>();
                string        controllerName = controller.Name.TrimEnd("Controller");
                ClassTemplate classTemplate  = files.AddFile(configuration.Service.RelativePath, configuration.AddHeader)
                                               .AddNamespace(string.Empty)
                                               .AddClass(configuration.Service.Name ?? controllerName + "Service")
                                               .FormatName(configuration)
                                               .WithUsing(httpClient, httpClientImport)
                                               .WithUsing("Injectable", "@angular/core")
                                               .WithUsing("Observable", "rxjs")
                                               .WithUsing("Subject", "rxjs")
                                               .WithAttribute("Injectable", Code.AnonymousObject().WithProperty("providedIn", Code.String("root")));
                FieldTemplate httpField       = classTemplate.AddField("http", Code.Type(httpClient)).Readonly().FormatName(configuration);
                FieldTemplate serviceUrlField = classTemplate.AddField("serviceUrl", Code.Type("string")).Public().FormatName(configuration).Default(Code.String(string.Empty));
                classTemplate.AddConstructor().WithParameter(Code.Type(httpClient), "http")
                .WithCode(Code.This().Field(httpField).Assign(Code.Local("http")).Close());
                string relativeModelPath = FileSystem.RelativeTo(configuration.Model?.RelativePath ?? ".", configuration.Service.RelativePath);
                foreach (HttpServiceActionTransferObject action in controller.Actions)
                {
                    ICodeFragment errorCode = Code.Lambda("error", Code.Local("subject").Method("error", Code.Local("error")));
                    this.MapType(controller.Language, configuration.Language, action.ReturnType);
                    TypeTemplate returnType = action.ReturnType.ToTemplate();
                    this.AddUsing(action.ReturnType, classTemplate, configuration, relativeModelPath);
                    MethodTemplate methodTemplate = classTemplate.AddMethod(action.Name, Code.Generic("Observable", returnType))
                                                    .FormatName(configuration);
                    foreach (HttpServiceActionParameterTransferObject parameter in action.Parameters)
                    {
                        this.MapType(controller.Language, configuration.Language, parameter.Type);
                        this.AddUsing(parameter.Type, classTemplate, configuration, relativeModelPath);
                        ParameterTemplate parameterTemplate = methodTemplate.AddParameter(parameter.Type.ToTemplate(), parameter.Name).FormatName(configuration);
                        mapping.Add(parameter, parameterTemplate);
                    }
                    methodTemplate.AddParameter(Code.Type("{}"), "httpOptions?");
                    TypeTemplate subjectType = Code.Generic("Subject", returnType);
                    methodTemplate.WithCode(Code.Declare(subjectType, "subject", Code.New(subjectType)));
                    string uri = ("/" + (controller.Route?.Replace("[controller]", controllerName.ToLower()).TrimEnd('/') ?? controllerName) + "/" + action.Route?.Replace("[action]", action.Name.ToLower())).TrimEnd('/');

                    List <HttpServiceActionParameterTransferObject> inlineParameters    = action.Parameters.Where(x => !x.FromBody && x.Inline).OrderBy(x => x.InlineIndex).ToList();
                    List <HttpServiceActionParameterTransferObject> urlParameters       = action.Parameters.Where(x => !x.FromBody && !x.Inline && x.AppendName).ToList();
                    List <HttpServiceActionParameterTransferObject> urlDirectParameters = action.Parameters.Where(x => !x.FromBody && !x.Inline && !x.AppendName).ToList();
                    uri = urlParameters.Count > 0 ? $"{uri}?{urlParameters.First().Name}=" : urlDirectParameters.Count > 0 ? $"{uri}?" : uri;
                    MultilineCodeFragment code            = Code.Multiline();
                    DeclareTemplate       declareTemplate = null;
                    bool hasReturnType = returnType.Name != "void";
                    bool isPrimitive   = this.IsPrimitive(returnType);
                    if (returnType.Name == "Array")
                    {
                        TypeTemplate type = ((GenericTypeTemplate)returnType).Types[0];
                        declareTemplate = Code.Declare(returnType, "list", Code.TypeScript("[]")).Constant();
                        code.AddLine(declareTemplate)
                        .AddLine(Code.TypeScript("for (const entry of <[]>result)").StartBlock())
                        .AddLine(Code.Local(declareTemplate).Method("push", isPrimitive ? (ICodeFragment)Code.Cast(type, Code.Local("entry")) : Code.New(type, Code.Local("entry"))).Close())
                        .AddLine(Code.TypeScript("").EndBlock());
                    }
                    else if (hasReturnType)
                    {
                        declareTemplate = Code.Declare(returnType, "model", isPrimitive ? (ICodeFragment)Code.Cast(returnType, Code.Local("result")) : Code.New(returnType, Code.Local("result"))).Constant();
                        code.AddLine(declareTemplate);
                    }
                    code.AddLine(Code.Local("subject").Method("next").WithParameter(declareTemplate.ToLocal()).Close())
                    .AddLine(Code.Local("subject").Method("complete").Close());
                    ChainedCodeFragment parameterUrl = Code.This().Field(serviceUrlField);
                    if (inlineParameters.Count == 0)
                    {
                        parameterUrl = parameterUrl.Append(Code.String(uri));
                    }
                    foreach (HttpServiceActionParameterTransferObject parameter in inlineParameters)
                    {
                        string[] chunks = uri.Split(new [] { $"{{{parameter.Name}}}" }, StringSplitOptions.RemoveEmptyEntries);
                        parameterUrl = parameterUrl.Append(Code.String(chunks[0])).Append(Code.Local(parameter.Name));
                        uri          = chunks.Length == 1 ? string.Empty : chunks[1];
                    }
                    bool isFirst = true;
                    foreach (HttpServiceActionParameterTransferObject parameter in urlDirectParameters)
                    {
                        if (isFirst)
                        {
                            isFirst      = false;
                            parameterUrl = parameterUrl.Append(Code.Local(parameter.Name));
                        }
                        else
                        {
                            parameterUrl = parameterUrl.Append(Code.String("&")).Append(Code.Local(parameter.Name));
                        }
                    }
                    foreach (HttpServiceActionParameterTransferObject parameter in urlParameters)
                    {
                        if (isFirst)
                        {
                            isFirst      = false;
                            parameterUrl = parameterUrl.Append(Code.Local(mapping[parameter]));
                        }
                        else
                        {
                            parameterUrl = parameterUrl.Append(Code.String($"&{parameter.Name}=")).Append(Code.Local(mapping[parameter]));
                        }
                    }

                    methodTemplate.WithCode(
                        Code.This()
                        .Field(httpField)
                        .Method(action.Type.ToString().ToLowerInvariant(),
                                parameterUrl,
                                action.RequireBodyParameter ? Code.Local(action.Parameters.Single(x => x.FromBody).Name) : null,
                                Code.Local("httpOptions")
                                )
                        .Method("subscribe", Code.Lambda(hasReturnType ? "result" : null, code), errorCode).Close()
                        );
                    methodTemplate.WithCode(Code.Return(Code.Local("subject")));
                }
            }
        }