public override Task Generate(CommandLineGeneratorModel controllerGeneratorModel)
        {
            ValidateNameSpaceName(controllerGeneratorModel);
            var outputPath = ValidateAndGetOutputPath(controllerGeneratorModel);

            return(Task.CompletedTask);
        }
Esempio n. 2
0
        protected virtual CommandLineGeneratorModel GetModel()
        {
            var model = new CommandLineGeneratorModel();

            model.ControllerName = "TestController";
            return(model);
        }
Esempio n. 3
0
        public override async Task Generate(CommandLineGeneratorModel controllerGeneratorModel)
        {
            Contract.Assert(!String.IsNullOrEmpty(controllerGeneratorModel.ModelClass));
            ValidateNameSpaceName(controllerGeneratorModel);
            string outputPath = ValidateAndGetOutputPath(controllerGeneratorModel);

            _areaName = GetAreaName(ApplicationInfo.ApplicationBasePath, outputPath);

            var modelTypeAndContextModel = await ModelMetadataUtilities.ValidateModelAndGetEFMetadata(
                controllerGeneratorModel,
                EntityFrameworkService,
                ModelTypesLocator,
                _areaName
                );

            if (string.IsNullOrEmpty(controllerGeneratorModel.ControllerName))
            {
                //Todo: Pluralize model name
                controllerGeneratorModel.ControllerName = modelTypeAndContextModel.ModelType.Name + Constants.ControllerSuffix;
            }
            var namespaceName = string.IsNullOrEmpty(controllerGeneratorModel.ControllerNamespace)
                ? GetDefaultControllerNamespace(controllerGeneratorModel.RelativeFolderPath)
                : controllerGeneratorModel.ControllerNamespace;

            var templateModel = new ControllerWithContextTemplateModel(modelTypeAndContextModel.ModelType, modelTypeAndContextModel.DbContextFullName)
            {
                ControllerName      = controllerGeneratorModel.ControllerName,
                AreaName            = _areaName,
                UseAsync            = controllerGeneratorModel.UseAsync, // This is no longer used for controllers with context.
                ControllerNamespace = namespaceName,
                ModelMetadata       = modelTypeAndContextModel.ContextProcessingResult.ModelMetadata
            };

            await CodeGeneratorActionsService.AddFileFromTemplateAsync(
                outputPath,
                GetTemplateName(controllerGeneratorModel),
                TemplateFolders,
                templateModel
                );

            Logger.LogMessage("Added Controller : " + outputPath.Substring(ApplicationInfo.ApplicationBasePath.Length));

            await GenerateViewsIfRequired(
                controllerGeneratorModel,
                modelTypeAndContextModel,
                templateModel.ControllerRootName
                );

            if (modelTypeAndContextModel.ContextProcessingResult.ContextProcessingStatus
                == ContextProcessingStatus.ContextAddedButRequiresConfig)
            {
                throw new Exception(string.Format("{0} {1}", MessageStrings.ScaffoldingSuccessful_unregistered,
                                                  MessageStrings.Scaffolding_additionalSteps));
            }
        }
Esempio n. 4
0
 private async Task GenerateControllerAndViews(CommandLineGeneratorModel cgModel)
 {
     try
     {
         // Generate Controller & 3-Views(Index, Details, Edit)
         var generator = ActivatorUtilities.CreateInstance <ControllerWithContextGenerator>(
             this._serviceProvider
             );
         await generator.Generate(cgModel);
     }
     catch (Exception ex)
     {
         this._logger.LogMessage(Xb.Util.GetErrorHighlighted(ex));
         throw ex;
     }
 }
Esempio n. 5
0
        private async Task GenerateViewsIfRequired(
            CommandLineGeneratorModel controllerGeneratorModel,
            ModelTypeAndContextModel modelTypeAndContextModel,
            string controllerRootName
            )
        {
            if (!controllerGeneratorModel.IsRestController && !controllerGeneratorModel.NoViews)
            {
                var layoutDependencyInstaller = ActivatorUtilities.CreateInstance <MvcLayoutDependencyInstaller>(ServiceProvider);
                var viewGenerator             = ActivatorUtilities.CreateInstance <ModelBasedViewScaffolder>(ServiceProvider);

                var areaPath           = string.IsNullOrEmpty(_areaName) ? string.Empty : Path.Combine("Areas", _areaName);
                var viewBaseOutputPath = Path.Combine(
                    ApplicationInfo.ApplicationBasePath,
                    areaPath,
                    Constants.ViewsFolderName,
                    controllerRootName);

                await layoutDependencyInstaller.Execute();

                var viewGeneratorModel = new ViewGeneratorModel()
                {
                    UseDefaultLayout         = controllerGeneratorModel.UseDefaultLayout,
                    PartialView              = false,
                    LayoutPage               = controllerGeneratorModel.LayoutPage,
                    Force                    = controllerGeneratorModel.Force,
                    RelativeFolderPath       = viewBaseOutputPath,
                    ReferenceScriptLibraries = controllerGeneratorModel.ReferenceScriptLibraries
                };

                var viewAndTemplateNames = new Dictionary <string, string>();
                foreach (var viewTemplate in _views)
                {
                    var viewName = viewTemplate == "List" ? "Index" : viewTemplate;
                    viewAndTemplateNames.Add(viewName, viewTemplate);
                }
                await viewGenerator.GenerateViews(
                    viewAndTemplateNames,
                    viewGeneratorModel,
                    modelTypeAndContextModel,
                    viewBaseOutputPath
                    );

                await layoutDependencyInstaller.InstallDependencies();
            }
        }
Esempio n. 6
0
        protected string ValidateAndGetOutputPath(CommandLineGeneratorModel commandLineModel, string outputFileName)
        {
            string outputFolder = String.IsNullOrEmpty(commandLineModel.RelativeFolderPath)
                ? ApplicationEnvironment.ApplicationBasePath
                : Path.Combine(ApplicationEnvironment.ApplicationBasePath, commandLineModel.RelativeFolderPath);

            var outputPath = Path.Combine(outputFolder, outputFileName);

            if (File.Exists(outputPath) && !commandLineModel.Force)
            {
                throw new InvalidOperationException(string.Format(
                                                        CultureInfo.CurrentCulture,
                                                        "The file {0} exists, use -f option to overwrite",
                                                        outputPath));
            }

            return(outputPath);
        }
Esempio n. 7
0
        internal async Task Generate(CommandLineGeneratorModel model)
        {
            DocumentationViewModel viewModel = new DocumentationViewModel();

            viewModel.Attributes      = new List <AttributeInfo>();
            viewModel.Interfaces      = new List <InterfaceInfo>();
            viewModel.BaseControllers = new List <BaseControllerInfo>();
            viewModel.Models          = new List <ModelInfo>();

            ParseAttributes(viewModel);
            ParseInterfaces(viewModel);
            ParseBaseControllers(viewModel);
            ParseModels(viewModel);

            var viewOutputPath = Path.Combine(
                ApplicationEnvironment.ApplicationBasePath,
                "Views",
                "Home",
                "Documentation.cshtml");
            await CodeGeneratorActionsService.AddFileFromTemplateAsync(viewOutputPath,
                                                                       "StaticDocumentationBuilder.cshtml", TemplateFolders, viewModel);
        }
Esempio n. 8
0
 public async Task GenerateCode(CommandLineGeneratorModel model)
 {
     var generator = ActivatorUtilities.CreateInstance <DocumentationGenerator>(ServiceProvider);
     await generator.Generate(model);
 }
Esempio n. 9
0
        public static void Main(string[] args)
        {
            var app = new CommandLineApplication(false)
            {
                Name = "Coalesce"
            };

            app.HelpOption("-h|--help");
            var dataContextClass   = app.Option("-dc|--dataContext", "Data Context containing the classes to scaffold", CommandOptionType.SingleValue);
            var force              = app.Option("-f|--force", "Use this option to overwrite existing files", CommandOptionType.SingleValue);
            var relativeFolderPath = app.Option("-outDir|--relativeFolderPath", "Specify the relative output folder path from project where the file needs to be generated, if not specified, file will be generated in the project folder", CommandOptionType.SingleValue);
            var onlyGenerateFiles  = app.Option("-filesOnly|--onlyGenerateFiles", "Will only generate the file output and will not restore any of the packages", CommandOptionType.SingleValue);
            var validateOnly       = app.Option("-vo|--validateOnly", "Validates the model but does not generate the models", CommandOptionType.SingleValue);
            var area            = app.Option("-a|--area", "The area where the generated/scaffolded code should be placed", CommandOptionType.SingleValue);
            var module          = app.Option("-m|--module", "The prefix to apply to the module name of the generated typescript files", CommandOptionType.SingleValue);
            var webProject      = app.Option("-wp|--webproject", "Relative path to the web project; if empty will search up from current folder for first project.json", CommandOptionType.SingleValue);
            var dataProject     = app.Option("-dp|--dataproject", "Relative path to the data project", CommandOptionType.SingleValue);
            var targetNamespace = app.Option("-ns|--namespace", "Target Namespace for the generated code", CommandOptionType.SingleValue);

            app.OnExecute(async() =>
            {
                var model = new CommandLineGeneratorModel
                {
                    DataContextClass       = dataContextClass.Value() ?? "",
                    Force                  = force.Value() != null && force.Value().ToLower() == "true",
                    RelativeFolderPath     = relativeFolderPath.Value() ?? "",
                    OnlyGenerateFiles      = onlyGenerateFiles.Value() != null && onlyGenerateFiles.Value().ToLower() == "true",
                    ValidateOnly           = validateOnly.Value() != null && validateOnly.Value().ToLower() == "true",
                    AreaLocation           = area.Value() ?? "",
                    TypescriptModulePrefix = module.Value() ?? "",
                    TargetNamespace        = targetNamespace.Value() ?? ""
                };

                // Find the web project
                ProjectContext webContext = DependencyProvider.ProjectContext(webProject.Value());
                if (webContext == null)
                {
                    throw new ArgumentException("Web project or target namespace was not found.");
                }

                // Find the data project
                ProjectContext dataContext = DependencyProvider.ProjectContext(dataProject.Value());
                if (dataContext == null)
                {
                    throw new ArgumentException("Data project was not found.");
                }

                Console.WriteLine("");

                CommandLineGenerator generator = new CommandLineGenerator(webContext, dataContext);

                await generator.GenerateCode(model);

                return(0);
            });

            try
            {
                app.Execute(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);
                    Console.WriteLine(ex.InnerException.StackTrace);
                }
            }
        }
 protected override string GetTemplateName(CommandLineGeneratorModel controllerGeneratorModel)
 {
     throw new NotImplementedException();
 }
Esempio n. 11
0
 protected override string GetTemplateName(CommandLineGeneratorModel generatorModel)
 {
     return(generatorModel.IsRestController ? Constants.ApiControllerWithContextTemplate : Constants.MvcControllerWithContextTemplate);
 }
Esempio n. 12
0
        /// <summary>
        /// Exec code generation
        /// </summary>
        /// <param name="genModel"></param>
        /// <returns></returns>
        public async Task GenerateCode(XbCodeGeneratorModel genModel)
        {
            try
            {
                if (genModel == null)
                {
                    throw new ArgumentNullException(nameof(genModel));
                }

                this._modelName = genModel.ModelName
                                  ?? throw new ArgumentException(MessageStrings.ModelNameRequired);
                this._dbContextName = genModel.DbContextName
                                      ?? throw new ArgumentException(MessageStrings.DbContextNameRequired);
                this._controllerName = genModel.ControllerName
                                       ?? throw new ArgumentException(MessageStrings.ControllerNameRequired);
                this._areaName = genModel.AreaName;

                // When multiple this NuGet packages are installed,
                // depending on the situation, older versions may be used.
                var version = this.GetType().GetTypeInfo().Assembly.GetName().Version.ToString();
                this._logger.LogMessage($"Generator version: {version}");

                if (!string.IsNullOrEmpty(genModel.ControllerName) &&
                    (Xb.Str.Right(genModel.ControllerName, 10).ToLower() == "controller"))
                {
                    this._controllerName = genModel.ControllerName;
                    this._baseName       = Xb.Str.SliceReverse(genModel.ControllerName, -10);
                }
                else
                {
                    this._controllerName = genModel.ControllerName + "Controller";
                    this._baseName       = genModel.ControllerName;
                }

                var cgModel = new CommandLineGeneratorModel()
                {
                    ModelClass         = this._modelName,
                    DataContextClass   = this._dbContextName,
                    ControllerName     = this._controllerName,
                    RelativeFolderPath = string.IsNullOrEmpty(this._areaName)
                        ? "Controllers"
                        : Path.Combine("Areas", this._areaName, "Controllers")
                };

                this._modelTypeAndContextModel = await ModelMetadataUtilities.ValidateModelAndGetEFMetadata(
                    cgModel,
                    this._entityFrameworkService,
                    this._modelTypesLocator,
                    this._areaName
                    );

                this._logger.LogMessage($"Model name: {this._modelName}");
                this._logger.LogMessage($"DbContext name: {this._dbContextName}");
                this._logger.LogMessage($"Controller name: {this._controllerName}"
                                        + ((this._controllerName == genModel.ControllerName)
                        ? ""
                        : $" (passing: {genModel.ControllerName})"));
                this._logger.LogMessage($"Area name: {this._areaName}");

                await this.GenerateControllerAndViews(cgModel);

                await this.GenerateStore();

                await this.GenerateViewModel();
            }
            catch (Exception ex)
            {
                this._logger?.LogMessage(Xb.Util.GetErrorHighlighted(ex));
                throw ex;
            }
        }