Beispiel #1
0
        // TODO: rework this to use the TemplateModel, as opposed to the RazorPageGeneratorModel (command line model)
        internal async Task GenerateView(RazorPageGeneratorModel razorGeneratorModel, ModelTypeAndContextModel modelTypeAndContextModel, string outputPath)
        {
            IEnumerable <string> templateFolders = GetTemplateFoldersForContentVersion();

            if (razorGeneratorModel.RazorPageName.EndsWith(Constants.ViewExtension, StringComparison.OrdinalIgnoreCase))
            {
                int viewNameLength = razorGeneratorModel.RazorPageName.Length - Constants.ViewExtension.Length;
                razorGeneratorModel.RazorPageName = razorGeneratorModel.RazorPageName.Substring(0, viewNameLength);
            }

            var templateName          = razorGeneratorModel.TemplateName + Constants.RazorTemplateExtension;
            var pageModelTemplateName = razorGeneratorModel.TemplateName + "PageModel" + Constants.RazorTemplateExtension;
            var pageModelOutputPath   = outputPath + ".cs";
            await _codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath, templateName, templateFolders, TemplateModel);

            _logger.LogMessage("Added RazorPage : " + outputPath.Substring(ApplicationInfo.ApplicationBasePath.Length));
            if (!razorGeneratorModel.NoPageModel)
            {
                await _codeGeneratorActionsService.AddFileFromTemplateAsync(pageModelOutputPath, pageModelTemplateName, templateFolders, TemplateModel);

                _logger.LogMessage("Added PageModel : " + pageModelOutputPath.Substring(ApplicationInfo.ApplicationBasePath.Length));
            }

            await AddRequiredFiles(razorGeneratorModel);
        }
        /*
         *  This is the main entry point for the code generator.
         */
        public async Task GenerateCode(CommandLineModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (string.IsNullOrEmpty(model.ViewName))
            {
                throw new ArgumentException("Please specify the name of file to be generated using the --name option");
            }

            var templateModel = new CustomTemplateModel()
            {
                ScaffolderName = this.scaffolderName
            };

            var outputFolder = string.IsNullOrEmpty(model.RelativeFolderPath)
                    ? _applicationInfo.ApplicationBasePath
                    : Path.Combine(_applicationInfo.ApplicationBasePath, model.RelativeFolderPath);

            var outputPath = Path.Combine(outputFolder, model.ViewName) + generatedFileExtension;

            if (File.Exists(outputPath) && !model.Force)
            {
                throw new InvalidOperationException($"File already exists '{outputPath}' use -f to force over write.");
            }

            await _codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath, "View.cshtml", TemplateFolders, templateModel);

            _logger.LogMessage($"Added: {outputPath.Substring(_applicationInfo.ApplicationBasePath.Length)}");
        }
        private async Task AddTemplateFiles(IdentityGeneratorTemplateModel templateModel)
        {
            var projectDir = Path.GetDirectoryName(_projectContext.ProjectFullPath);
            var templates  = templateModel.FilesToGenerate.Where(t => t.IsTemplate);

            foreach (var template in templates)
            {
                var outputPath = Path.Combine(projectDir, template.OutputPath);
                if (template.ShouldOverWrite != OverWriteCondition.Never || !_fileSystem.FileExists(outputPath))
                {
                    // We never overwrite some files like _ViewImports.cshtml.
                    _logger.LogMessage($"Adding template: {template.Name}", LogMessageLevel.Trace);
                    await _codegeneratorActionService.AddFileFromTemplateAsync(
                        outputPath,
                        template.SourcePath,
                        TemplateFolders,
                        templateModel);
                }
            }

            if (!templateModel.IsUsingExistingDbContext)
            {
                _connectionStringsWriter.AddConnectionString(
                    connectionStringName: $"{templateModel.DbContextClass}Connection",
                    dataBaseName: templateModel.ApplicationName,
                    useSQLite: templateModel.UseSQLite);
            }
        }
        public async Task GenerateCode(BaseModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (string.IsNullOrEmpty(model.ClassName))
            {
                throw new ArgumentException("Please specify the name of the command using --bundleName");
            }

            var files = GetFiles(model.ClassName);

            foreach (var code in files)
            {
                if (File.Exists(code.DestinationPath) && !model.Force)
                {
                    throw new InvalidOperationException($"File already exists '{code.DestinationPath}' use -f to force over write.");
                }
            }

            model.Namespace = _applicationInfo.ApplicationName.ReplaceLast(".Infrastructure", "");
            foreach (var code in files)
            {
                await _codeGeneratorActionsService.AddFileFromTemplateAsync(code.DestinationPath, code.File, TemplateFolders, model);

                _logger.LogMessage($"Added: {code.DestinationPath.Substring(code.DestinationPath.LastIndexOf('/'))}");
            }
        }
        public async Task GenerateReadmeForArea()
        {
            var templateName = "ReadMe" + Constants.RazorTemplateExtension;
            var outputPath   = Path.Combine(_applicationInfo.ApplicationBasePath,
                                            Constants.ReadMeOutputFileName);

            await _codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath,
                                                                        templateName,
                                                                        TemplateFolders,
                                                                        new ReadMeTemplateModel()
            {
                StartupList   = null,
                RootNamespace = string.Empty,     //Does not matter.
                IsAreaReadMe  = true
            });
        }
Beispiel #6
0
        private async Task GenerateStartup(List <StartupContent> startupList)
        {
            var templateName    = "Startup" + Constants.RazorTemplateExtension;
            var applicationName = _applicationInfo.ApplicationName;
            var outputPath      = Path.Combine(_applicationInfo.ApplicationBasePath,
                                               "Startup" + Constants.CodeFileExtension);

            await _codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath,
                                                                        templateName,
                                                                        TemplateFolders,
                                                                        new ReadMeTemplateModel()
            {
                StartupList   = startupList,
                RootNamespace = applicationName
            });
        }
Beispiel #7
0
        public async Task GenerateCode([NotNull] ViewGeneratorModel viewGeneratorModel)
        {
            // Validate model
            string      validationMessage;
            ITypeSymbol model, dataContext;

            if (!ValidationUtil.TryValidateType(viewGeneratorModel.ModelClass, "model", _modelTypesLocator, out model, out validationMessage) ||
                !ValidationUtil.TryValidateType(viewGeneratorModel.DataContextClass, "dataContext", _modelTypesLocator, out dataContext, out validationMessage))
            {
                throw new ArgumentException(validationMessage);
            }

            if (string.IsNullOrEmpty(viewGeneratorModel.ViewName))
            {
                throw new ArgumentException("The ViewName cannot be empty");
            }

            // Validation successful
            Contract.Assert(model != null, "Validation succeded but model type not set");
            Contract.Assert(dataContext != null, "Validation succeded but DataContext type not set");

            var outputPath = Path.Combine(
                _applicationEnvironment.ApplicationBasePath,
                Constants.ViewsFolderName,
                model.Name,
                viewGeneratorModel.ViewName + ".cshtml");

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

            var templateName = viewGeneratorModel.TemplateName + ".cshtml";

            var dbContextFullName = dataContext.FullNameForSymbol();
            var modelTypeFullName = model.FullNameForSymbol();

            var modelMetadata = await _entityFrameworkService.GetModelMetadata(
                dbContextFullName,
                model);

            var templateModel = new ViewGeneratorTemplateModel()
            {
                ViewDataTypeName         = modelTypeFullName,
                ViewName                 = viewGeneratorModel.ViewName,
                LayoutPageFile           = viewGeneratorModel.LayoutPage,
                IsLayoutPageSelected     = viewGeneratorModel.UseLayout,
                IsPartialView            = viewGeneratorModel.PartialView,
                ReferenceScriptLibraries = viewGeneratorModel.ReferenceScriptLibraries,
                ModelMetadata            = modelMetadata,
                JQueryVersion            = "1.10.2" //Todo
            };

            await _codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath, templateName, TemplateFolders, templateModel);
        }
Beispiel #8
0
        public async Task GenerateCode(ViewGeneratorModel viewGeneratorModel)
        {
            if (viewGeneratorModel == null)
            {
                throw new ArgumentNullException(nameof(viewGeneratorModel));
            }

            if (string.IsNullOrEmpty(viewGeneratorModel.ViewName))
            {
                throw new ArgumentException(CodeGenerators.Mvc.MessageStrings.ViewNameRequired);
            }

            if (string.IsNullOrEmpty(viewGeneratorModel.TemplateName))
            {
                throw new ArgumentException(CodeGenerators.Mvc.MessageStrings.TemplateNameRequired);
            }

            var outputPath = ValidateAndGetOutputPath(viewGeneratorModel, outputFileName: viewGeneratorModel.ViewName + Constants.ViewExtension);
            var modelTypeAndContextModel = await ValidateModelAndGetMetadata(viewGeneratorModel);

            var layoutDependencyInstaller = ActivatorUtilities.CreateInstance <MvcLayoutDependencyInstaller>(_serviceProvider);
            await layoutDependencyInstaller.Execute();

            if (viewGeneratorModel.ViewName.EndsWith(Constants.ViewExtension, StringComparison.OrdinalIgnoreCase))
            {
                int viewNameLength = viewGeneratorModel.ViewName.Length - Constants.ViewExtension.Length;
                viewGeneratorModel.ViewName = viewGeneratorModel.ViewName.Substring(0, viewNameLength);
            }

            bool isLayoutSelected = !viewGeneratorModel.PartialView &&
                                    (viewGeneratorModel.UseDefaultLayout || !String.IsNullOrEmpty(viewGeneratorModel.LayoutPage));

            var templateModel = new ViewGeneratorTemplateModel()
            {
                ViewDataTypeName      = modelTypeAndContextModel.ModelType.FullName,
                ViewDataTypeShortName = modelTypeAndContextModel.ModelType.Name,
                ViewName                 = viewGeneratorModel.ViewName,
                LayoutPageFile           = viewGeneratorModel.LayoutPage,
                IsLayoutPageSelected     = isLayoutSelected,
                IsPartialView            = viewGeneratorModel.PartialView,
                ReferenceScriptLibraries = viewGeneratorModel.ReferenceScriptLibraries,
                ModelMetadata            = modelTypeAndContextModel.ContextProcessingResult.ModelMetadata,
                JQueryVersion            = "1.10.2" //Todo
            };

            var templateName = viewGeneratorModel.TemplateName + Constants.RazorTemplateExtension;
            await _codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath, templateName, TemplateFolders, templateModel);

            _logger.LogMessage("Added View : " + outputPath.Substring(ApplicationInfo.ApplicationBasePath.Length));

            await layoutDependencyInstaller.InstallDependencies();

            if (modelTypeAndContextModel.ContextProcessingResult.ContextProcessingStatus == ContextProcessingStatus.ContextAddedButRequiresConfig)
            {
                throw new Exception(string.Format("{0} {1}", CodeGenerators.Mvc.MessageStrings.ScaffoldingSuccessful_unregistered, CodeGenerators.Mvc.MessageStrings.Scaffolding_additionalSteps));
            }
        }
Beispiel #9
0
        public async Task GenerateCode([NotNull] ViewGeneratorModel viewGeneratorModel)
        {
            if (string.IsNullOrEmpty(viewGeneratorModel.ViewName))
            {
                throw new ArgumentException("The ViewName cannot be empty");
            }

            if (string.IsNullOrEmpty(viewGeneratorModel.TemplateName))
            {
                throw new ArgumentException("The TemplateName cannot be empty");
            }

            var outputPath = ValidateAndGetOutputPath(viewGeneratorModel, outputFileName: viewGeneratorModel.ViewName + Constants.ViewExtension);
            var modelTypeAndContextModel = await ValidateModelAndGetMetadata(viewGeneratorModel);

            var layoutDependencyInstaller = ActivatorUtilities.CreateInstance <MvcLayoutDependencyInstaller>(_serviceProvider);
            await layoutDependencyInstaller.Execute();

            if (viewGeneratorModel.ViewName.EndsWith(Constants.ViewExtension, StringComparison.OrdinalIgnoreCase))
            {
                int viewNameLength = viewGeneratorModel.ViewName.Length - Constants.ViewExtension.Length;
                viewGeneratorModel.ViewName = viewGeneratorModel.ViewName.Substring(0, viewNameLength);
            }

            bool isLayoutSelected = !viewGeneratorModel.PartialView &&
                                    (viewGeneratorModel.UseDefaultLayout || !String.IsNullOrEmpty(viewGeneratorModel.LayoutPage));

            var templateModel = new ViewGeneratorTemplateModel()
            {
                ViewDataTypeName      = modelTypeAndContextModel.ModelType.FullName,
                ViewDataTypeShortName = modelTypeAndContextModel.ModelType.Name,
                ViewName                 = viewGeneratorModel.ViewName,
                LayoutPageFile           = viewGeneratorModel.LayoutPage,
                IsLayoutPageSelected     = isLayoutSelected,
                IsPartialView            = viewGeneratorModel.PartialView,
                ReferenceScriptLibraries = viewGeneratorModel.ReferenceScriptLibraries,
                ModelMetadata            = modelTypeAndContextModel.ContextProcessingResult.ModelMetadata,
                JQueryVersion            = "1.10.2" //Todo
            };

            var templateName = viewGeneratorModel.TemplateName + Constants.RazorTemplateExtension;
            await _codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath, templateName, TemplateFolders, templateModel);

            _logger.LogMessage("Added View : " + outputPath.Substring(ApplicationEnvironment.ApplicationBasePath.Length));

            await layoutDependencyInstaller.InstallDependencies();

            if (modelTypeAndContextModel.ContextProcessingResult.ContextProcessingStatus == ContextProcessingStatus.ContextAddedButRequiresConfig)
            {
                throw new Exception("Scaffolding generated all the code but the new context created could be registered using dependency injection." +
                                    "There may be additional steps required for the generated code to work. Refer to <forward-link>");
            }
        }
Beispiel #10
0
        public async Task GenerateAsync(MvcModel model)
        {
            logger.LogMessage("creating controller");
            model.ControllerName = string.Concat(model.ModelClass, Constants.ControllerSuffix);

            logger.LogMessage("creating model controller");

            var templateModel = new ClassNameModel(className: model.ControllerName, namespaceName: NameSpaceUtilities.GetSafeNameSpaceFromPath(applicationInfo.ApplicationBasePath));

            logger.LogMessage("creating files");
            var outputPath = ValidateAndGetOutputPath(model, string.Concat(model.ControllerName, Constants.CodeFileExtension));
            await codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath, Constants.EmptyControllerTemplate, TemplateFolders, templateModel);
        }
        internal async Task GenerateView(ViewGeneratorModel viewGeneratorModel, ModelTypeAndContextModel modelTypeAndContextModel, string outputPath)
        {
            if (viewGeneratorModel.ViewName.EndsWith(Constants.ViewExtension, StringComparison.OrdinalIgnoreCase))
            {
                int viewNameLength = viewGeneratorModel.ViewName.Length - Constants.ViewExtension.Length;
                viewGeneratorModel.ViewName = viewGeneratorModel.ViewName.Substring(0, viewNameLength);
            }

            var templateModel = GetViewGeneratorTemplateModel(viewGeneratorModel, modelTypeAndContextModel);
            var templateName  = viewGeneratorModel.TemplateName + Constants.RazorTemplateExtension;
            await _codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath, templateName, TemplateFolders, templateModel);

            _logger.LogMessage("Added View : " + outputPath.Substring(ApplicationInfo.ApplicationBasePath.Length));

            await AddRequiredFiles(viewGeneratorModel);
        }
Beispiel #12
0
        internal async Task GenerateModel(
            ModelGeneratorModel generatorModel,
            ModelTypeAndContextModel modelTypeAndContextModel,
            string outputPath)
        {
            var templateName = generatorModel.TemplateName + Constants.RazorTemplateExtension;
            await _codeGeneratorActionsService.AddFileFromTemplateAsync(
                outputPath,
                templateName,
                TemplateFolders,
                generatorModel
                );

            this._logger.LogMessage("Added Model : "
                                    + outputPath.Substring(ApplicationInfo.ApplicationBasePath.Length));

            await AddRequiredFiles(generatorModel);
        }
        private async Task AddTemplateFiles(IdentityGeneratorTemplateModel templateModel)
        {
            var templates  = IdentityGeneratorFilesConfig.GetTemplateFiles(templateModel);
            var projectDir = Path.GetDirectoryName(_projectContext.ProjectFullPath);

            foreach (var template in templates)
            {
                _logger.LogMessage($"Adding template: {template.Key}", LogMessageLevel.Trace);
                await _codegeneratorActionService.AddFileFromTemplateAsync(
                    Path.Combine(projectDir, template.Value),
                    template.Key,
                    TemplateFolders,
                    templateModel);
            }

            _connectionStringsWriter.AddConnectionString(
                connectionStringName: $"{templateModel.DbContextClass}Connection",
                dataBaseName: templateModel.ApplicationName,
                useSQLite: templateModel.UseSQLite);
        }
        public void GenerateCode(AdvancedGeneratorModel model)
        {
            var types = modelTypesLocator.GetAllTypes();

            if (!string.IsNullOrEmpty(model.TypeFilter))
            {
                var regex = new Regex(model.TypeFilter);
                types = types.Where(t => regex.IsMatch(t.Name));
            }

            var templateModel = new TemplateModel
            {
                Namespace = model.Namespace,
                Types     = types.Select(t =>
                                         new TemplateModelType
                {
                    Name       = t.Name,
                    Properties = (t.TypeSymbol as INamedTypeSymbol)
                                 .GetMembers()
                                 .Where(m => m.Kind == SymbolKind.Property)
                                 .OfType <IPropertySymbol>()
                                 .Select(m => new TemplateModelProperty {
                        Name = m.Name, Type = m.Type.Name
                    }).ToArray()
                }).ToArray()
            };

            var templateFolders = TemplateFoldersUtilities
                                  .GetTemplateFolders(this.GetType().Assembly.GetName().Name,
                                                      applicationInfo.ApplicationBasePath,
                                                      new string[] { "Advanced" },
                                                      projectContext);

            var outputFilePath = Path.Combine(applicationInfo.ApplicationBasePath, model.OutputFile);

            codeGeneratorActionsService.AddFileFromTemplateAsync(outputFilePath, TemplateName, templateFolders, templateModel);
        }
Beispiel #15
0
        public async Task GenerateCode([NotNull] ViewGeneratorModel viewGeneratorModel)
        {
            // Validate model
            string      validationMessage;
            ITypeSymbol model, dataContext;

            if (!ValidationUtil.TryValidateType(viewGeneratorModel.ModelClass, "model", _modelTypesLocator, out model, out validationMessage))
            {
                throw new ArgumentException(validationMessage);
            }

            if (string.IsNullOrEmpty(viewGeneratorModel.ViewName))
            {
                throw new ArgumentException("The ViewName cannot be empty");
            }

            if (viewGeneratorModel.ViewName.EndsWith(Constants.ViewExtension, StringComparison.OrdinalIgnoreCase))
            {
                int viewNameLength = viewGeneratorModel.ViewName.Length - Constants.ViewExtension.Length;
                viewGeneratorModel.ViewName = viewGeneratorModel.ViewName.Substring(0, viewNameLength);
            }

            if (string.IsNullOrEmpty(viewGeneratorModel.TemplateName))
            {
                throw new ArgumentException("The TemplateName cannot be empty");
            }

            ValidationUtil.TryValidateType(viewGeneratorModel.DataContextClass, "dataContext", _modelTypesLocator, out dataContext, out validationMessage);

            // Validation successful
            Contract.Assert(model != null, "Validation succeded but model type not set");

            var appbasePath = _applicationEnvironment.ApplicationBasePath;
            var outputPath  = Path.Combine(
                appbasePath,
                Constants.ViewsFolderName,
                model.Name,
                viewGeneratorModel.ViewName + Constants.ViewExtension);

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

            var templateName = viewGeneratorModel.TemplateName + Constants.RazorTemplateExtension;

            var dbContextFullName = dataContext != null?dataContext.ToDisplayString() : viewGeneratorModel.DataContextClass;

            var modelTypeFullName = model.ToDisplayString();

            var modelMetadata = await _entityFrameworkService.GetModelMetadata(
                dbContextFullName,
                model);

            var layoutDependencyInstaller = _typeActivator.CreateInstance <MvcLayoutDependencyInstaller>(_serviceProvider);

            bool isLayoutSelected = viewGeneratorModel.UseDefaultLayout ||
                                    !String.IsNullOrEmpty(viewGeneratorModel.LayoutPage);

            await layoutDependencyInstaller.Execute();

            var templateModel = new ViewGeneratorTemplateModel()
            {
                ViewDataTypeName      = modelTypeFullName,
                ViewDataTypeShortName = model.Name,
                ViewName                 = viewGeneratorModel.ViewName,
                LayoutPageFile           = viewGeneratorModel.LayoutPage,
                IsLayoutPageSelected     = isLayoutSelected,
                IsPartialView            = viewGeneratorModel.PartialView,
                ReferenceScriptLibraries = viewGeneratorModel.ReferenceScriptLibraries,
                ModelMetadata            = modelMetadata,
                JQueryVersion            = "1.10.2" //Todo
            };

            await _codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath, templateName, TemplateFolders, templateModel);

            _logger.LogMessage("Added View : " + outputPath.Substring(appbasePath.Length));

            await layoutDependencyInstaller.InstallDependencies();
        }
        private async Task GenerateController(ControllerGeneratorModel controllerGeneratorModel,
                                              ITypeSymbol model,
                                              ITypeSymbol dataContext,
                                              string controllerNameSpace,
                                              MvcLayoutDependencyInstaller layoutDependencyInstaller)
        {
            if (string.IsNullOrEmpty(controllerGeneratorModel.ControllerName))
            {
                //Todo: Pluralize model name
                controllerGeneratorModel.ControllerName = model.Name + Constants.ControllerSuffix;
            }

            // Validation successful
            Contract.Assert(model != null, "Validation succeded but model type not set");

            string outputPath = ValidateAndGetOutputPath(controllerGeneratorModel);

            var dbContextFullName = dataContext != null?dataContext.ToDisplayString() : controllerGeneratorModel.DataContextClass;

            var modelTypeFullName = model.ToDisplayString();

            var modelMetadata = await _entityFrameworkService.GetModelMetadata(
                dbContextFullName,
                model);

            await layoutDependencyInstaller.Execute();

            var templateName  = "ControllerWithContext.cshtml";
            var templateModel = new ControllerGeneratorTemplateModel(model, dbContextFullName)
            {
                ControllerName      = controllerGeneratorModel.ControllerName,
                AreaName            = string.Empty, //ToDo
                UseAsync            = controllerGeneratorModel.UseAsync,
                ControllerNamespace = controllerNameSpace,
                ModelMetadata       = modelMetadata
            };

            var appBasePath = _applicationEnvironment.ApplicationBasePath;
            await _codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath, templateName, TemplateFolders, templateModel);

            _logger.LogMessage("Added Controller : " + outputPath.Substring(appBasePath.Length));

            if (!controllerGeneratorModel.NoViews)
            {
                foreach (var viewTemplate in _views)
                {
                    var viewName = viewTemplate == "List" ? "Index" : viewTemplate;
                    // ToDo: This is duplicated from ViewGenerator.
                    bool isLayoutSelected = controllerGeneratorModel.UseDefaultLayout ||
                                            !String.IsNullOrEmpty(controllerGeneratorModel.LayoutPage);

                    var viewTemplateModel = new ViewGeneratorTemplateModel()
                    {
                        ViewDataTypeName      = modelTypeFullName,
                        ViewDataTypeShortName = model.Name,
                        ViewName                 = viewName,
                        LayoutPageFile           = controllerGeneratorModel.LayoutPage,
                        IsLayoutPageSelected     = isLayoutSelected,
                        IsPartialView            = false,
                        ReferenceScriptLibraries = controllerGeneratorModel.ReferenceScriptLibraries,
                        ModelMetadata            = modelMetadata,
                        JQueryVersion            = "1.10.2"
                    };

                    var viewOutputPath = Path.Combine(
                        appBasePath,
                        Constants.ViewsFolderName,
                        templateModel.ControllerRootName,
                        viewName + Constants.ViewExtension);

                    await _codeGeneratorActionsService.AddFileFromTemplateAsync(viewOutputPath,
                                                                                viewTemplate + Constants.RazorTemplateExtension, TemplateFolders, viewTemplateModel);

                    _logger.LogMessage("Added View : " + viewOutputPath.Substring(appBasePath.Length));
                }
            }
        }
Beispiel #17
0
        public async Task GenerateCode([NotNull] ControllerGeneratorModel controllerGeneratorModel)
        {
            // Validate model
            string      validationMessage;
            ITypeSymbol model, dataContext;

            if (!ValidationUtil.TryValidateType(controllerGeneratorModel.ModelClass, "model", _modelTypesLocator, out model, out validationMessage))
            {
                throw new ArgumentException(validationMessage);
            }

            if (string.IsNullOrWhiteSpace(controllerGeneratorModel.DataContextClass))
            {
                throw new ArgumentException("Please provide a name for DataContext");
            }
            ValidationUtil.TryValidateType(controllerGeneratorModel.DataContextClass, "dataContext", _modelTypesLocator, out dataContext, out validationMessage);

            if (string.IsNullOrEmpty(controllerGeneratorModel.ControllerName))
            {
                //Todo: Pluralize model name
                controllerGeneratorModel.ControllerName = model.Name + Constants.ControllerSuffix;
            }

            // Validation successful
            Contract.Assert(model != null, "Validation succeded but model type not set");

            var outputPath = Path.Combine(
                _applicationEnvironment.ApplicationBasePath,
                Constants.ControllersFolderName,
                controllerGeneratorModel.ControllerName + ".cs");

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

            var dbContextFullName = dataContext != null?dataContext.FullNameForSymbol() : controllerGeneratorModel.DataContextClass;

            var modelTypeFullName = model.FullNameForSymbol();

            var modelMetadata = await _entityFrameworkService.GetModelMetadata(
                dbContextFullName,
                model);

            var templateName  = "ControllerWithContext.cshtml";
            var templateModel = new ControllerGeneratorTemplateModel(model, dbContextFullName)
            {
                ControllerName = controllerGeneratorModel.ControllerName,
                AreaName       = string.Empty, //ToDo
                UseAsync       = controllerGeneratorModel.UseAsync,
                ModelMetadata  = modelMetadata
            };

            await _codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath, templateName, TemplateFolders, templateModel);

            if (!controllerGeneratorModel.NoViews)
            {
                foreach (var viewTemplate in _views)
                {
                    var viewName = viewTemplate == "List" ? "Index" : viewTemplate;
                    // ToDo: This is duplicated from ViewGenerator.
                    var viewTemplateModel = new ViewGeneratorTemplateModel()
                    {
                        ViewDataTypeName         = modelTypeFullName,
                        ViewName                 = viewName,
                        LayoutPageFile           = controllerGeneratorModel.LayoutPage,
                        IsLayoutPageSelected     = controllerGeneratorModel.UseLayout,
                        IsPartialView            = false,
                        ReferenceScriptLibraries = controllerGeneratorModel.ReferenceScriptLibraries,
                        ModelMetadata            = modelMetadata,
                        JQueryVersion            = "1.10.2"
                    };

                    var viewOutputPath = Path.Combine(
                        _applicationEnvironment.ApplicationBasePath,
                        Constants.ViewsFolderName,
                        model.Name,
                        viewName + ".cshtml");

                    await _codeGeneratorActionsService.AddFileFromTemplateAsync(viewOutputPath,
                                                                                viewTemplate + ".cshtml", TemplateFolders, viewTemplateModel);
                }
            }
        }