Exemplo n.º 1
0
        public virtual void Write(AspDotNetWriteConfiguration configuration)
        {
            List <FileTemplate> files = new List <FileTemplate>();

            if (configuration.GeneratorController != null)
            {
                this.resolver.Create <AspDotNetGeneratorControllerWriter>().Write(configuration, files);
            }
            if (configuration.Controllers.Count > 0)
            {
                this.resolver.Create <AspDotNetEntityControllerWriter>().Write(configuration);
            }
        }
Exemplo n.º 2
0
        public virtual void Write(ConfigurationBase configurationBase, List <ITransferObject> transferObjects, IOutput output)
        {
            AspDotNetWriteConfiguration configuration = (AspDotNetWriteConfiguration)configurationBase;
            List <FileTemplate>         files         = new List <FileTemplate>();

            if (configuration.GeneratorController != null)
            {
                this.resolver.Create <AspDotNetGeneratorControllerWriter>().Write(configuration, files);
            }
            if (configuration.Controllers.Count > 0)
            {
                this.resolver.Create <AspDotNetEntityControllerWriter>().Write(configuration, transferObjects, files);
            }
            files.ForEach(file => configuration.Language.Write(file, output));
        }
        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]"));
            }
        }
        public virtual void Write(AspDotNetWriteConfiguration configuration, List <ITransferObject> transferObjects, List <FileTemplate> files)
        {
            if (!configuration.Language.IsCsharp())
            {
                throw new InvalidOperationException($"Can not generate ASP.net Controller for language {configuration.Language?.Name ?? "Empty"}. Only Csharp is currently implemented");
            }
            foreach (AspDotNetWriteEntityControllerConfiguration controllerConfiguration in configuration.Controllers)
            {
                EntityTransferObject entity = transferObjects.OfType <EntityTransferObject>().FirstOrDefault(x => x.Name == controllerConfiguration.Entity)
                                              .AssertIsNotNull(nameof(controllerConfiguration.Entity), $"Entity {controllerConfiguration.Entity} not found. Ensure it is read before.");

                string        nameSpace  = (controllerConfiguration.Namespace ?? configuration.Namespace).AssertIsNotNull(nameof(configuration.Namespace), "asp writer requires a namespace");
                ClassTemplate controller = files.AddFile(configuration.RelativePath, configuration.AddHeader)
                                           .AddNamespace(nameSpace)
                                           .AddClass(controllerConfiguration.Name ?? entity.Name + "Controller", Code.Type(configuration.Template.ControllerBase))
                                           .FormatName(configuration)
                                           .WithAttribute("Route", Code.String(controllerConfiguration.Route ?? "[controller]"));

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

                TypeTemplate modelType = entity.Model.ToTemplate();

                configuration.Usings.ForEach(x => controller.AddUsing(x));
                controllerConfiguration.Usings.ForEach(x => controller.AddUsing(x));

                FieldTemplate repositoryField = controller.AddField("repository", Code.Type(entity.Name + "Repository")).Readonly();
                controller.AddConstructor().Code.AddLine(Code.This().Field(repositoryField).Assign(Code.New(repositoryField.Type)).Close());

                if (controllerConfiguration.Get != null)
                {
                    controller.AddUsing("System.Linq");
                    MethodTemplate method = controller.AddMethod("Get", Code.Generic("IEnumerable", modelType));
                    if (configuration.Template.UseAttributes)
                    {
                        method.WithAttribute("HttpGet", Code.String(controllerConfiguration.Get.Name ?? "[action]"));
                    }
                    DeclareTemplate queryable = Code.Declare(Code.Generic("IQueryable", modelType), "queryable", Code.This().Field(repositoryField).Method("Get"));
                    method.Code.AddLine(queryable);
                    foreach (PropertyTransferObject property in entity.Model.Properties)
                    {
                        ParameterTemplate parameter = method.AddParameter(property.Type.ToTemplate(), property.Name, Code.Local("default")).FormatName(configuration);
                        method.Code.AddLine(Code.If(Code.Local(parameter).NotEquals().Local("default"), x => x.Code.AddLine(Code.Local(queryable).Assign(Code.Local(queryable).Method("Where", Code.Lambda("x", Code.Local("x").Property(property.Name).Equals().Local(parameter)))).Close())));
                    }
                    method.Code.AddLine(Code.Return(Code.Local(queryable)));
                }
                if (controllerConfiguration.Post != null)
                {
                    MethodTemplate method = controller.AddMethod("Post", Code.Void());
                    if (configuration.Template.UseAttributes)
                    {
                        method.WithAttribute("HttpPost", Code.String(controllerConfiguration.Post.Name ?? "[action]"));
                    }
                    ParameterTemplate parameter = method.AddParameter(modelType, "entity")
                                                  .WithAttribute("FromBody");

                    method.Code.AddLine(Code.This().Field(repositoryField).Method("Add", Code.Local(parameter)).Close());
                }
                if (controllerConfiguration.Patch != null)
                {
                    MethodTemplate method = controller.AddMethod("Patch", Code.Void());
                    if (configuration.Template.UseAttributes)
                    {
                        method.WithAttribute("HttpPatch", Code.String(controllerConfiguration.Patch.Name ?? "[action]"));
                    }
                    ParameterTemplate parameter = method.AddParameter(modelType, "entity")
                                                  .WithAttribute("FromBody");

                    method.Code.AddLine(Code.This().Field(repositoryField).Method("Update", Code.Local(parameter)).Close());
                }
                if (controllerConfiguration.Put != null)
                {
                    MethodTemplate method = controller.AddMethod("Put", Code.Void());
                    if (configuration.Template.UseAttributes)
                    {
                        method.WithAttribute("HttpPut", Code.String(controllerConfiguration.Put.Name ?? "[action]"));
                    }
                    ParameterTemplate parameter = method.AddParameter(modelType, "entity")
                                                  .WithAttribute("FromBody");

                    method.Code.AddLine(Code.This().Field(repositoryField).Method("Update", Code.Local(parameter)).Close());
                }
                if (controllerConfiguration.Delete != null)
                {
                    MethodTemplate method = controller.AddMethod("Delete", Code.Void());
                    if (configuration.Template.UseAttributes)
                    {
                        method.WithAttribute("HttpDelete", Code.String(controllerConfiguration.Delete.Name ?? "[action]"));
                    }
                    List <ParameterTemplate> parameters = new List <ParameterTemplate>();
                    foreach (EntityKeyTransferObject key in entity.Keys)
                    {
                        PropertyTransferObject property = entity.Model.Properties.First(x => x.Name.Equals(key.Name, StringComparison.InvariantCultureIgnoreCase));
                        parameters.Add(method.AddParameter(property.Type.ToTemplate(), property.Name)
                                       .FormatName(configuration));
                    }
                    method.Code.AddLine(Code.This().Field(repositoryField).Method("Delete", parameters.Select(x => Code.Local(x))).Close());
                }
            }
        }