/// <summary> /// 生成代码 /// </summary> /// <param name="project">项目信息</param> /// <param name="selectionRelativePath"></param> /// <param name="codeGeneratorViewModel"></param> private void GenerateCode(Project project, string selectionRelativePath, WebFormsCodeGeneratorViewModel codeGeneratorViewModel) { // Get Model Type var modelType = codeGeneratorViewModel.ModelType.CodeType; // Ensure the Data Context string dbContextTypeName = codeGeneratorViewModel.DbContextModelType.TypeName; IEntityFrameworkService efService = Context.ServiceProvider.GetService <IEntityFrameworkService>(); ModelMetadata efMetadata = efService.AddRequiredEntity(Context, dbContextTypeName, modelType.FullName); // Get the dbContext ICodeTypeService codeTypeService = GetService <ICodeTypeService>(); CodeType dbContext = codeTypeService.GetCodeType(project, dbContextTypeName); // Get the dbContext namespace string dbContextNamespace = dbContext.Namespace != null ? dbContext.Namespace.FullName : String.Empty; // Ensure the Dynamic Data Field templates EnsureDynamicDataFieldTemplates(project, dbContextNamespace, dbContextTypeName); // Add Web Forms Pages from Templates AddWebFormsPages( project, selectionRelativePath, dbContextNamespace, dbContextTypeName, modelType, efMetadata, codeGeneratorViewModel.UseMasterPage, codeGeneratorViewModel.DesktopMasterPage, codeGeneratorViewModel.DesktopPlaceholderId, codeGeneratorViewModel.OverwriteViews ); }
protected internal override void Scaffold() { ModelMetadata codeModelModelMetadatum; if (!base.Model.ViewTemplate.IsModelRequired) { codeModelModelMetadatum = new CodeModelModelMetadata(); base.Model.IsReferenceScriptLibrariesSelected = false; } else if (base.Model.DataContextType == null) { codeModelModelMetadatum = (base.Model.ModelType == null ? new CodeModelModelMetadata() : new CodeModelModelMetadata(base.Model.ModelType.CodeType)); } else { IEntityFrameworkService service = base.Context.ServiceProvider.GetService <IEntityFrameworkService>(); codeModelModelMetadatum = service.AddRequiredEntity(base.Context, base.Model.DataContextType.TypeName, base.Model.ModelType.TypeName); } try { this.GenerateView(codeModelModelMetadatum, base.Model.SelectionRelativePath); } finally { base.Context.AddTelemetryData("MvcViewScaffolderOptions", (uint)this.GetTelemetryOptions()); base.Context.AddTelemetryData("MvcViewTemplateName", base.Model.ViewTemplate.Name); } }
// Setting Columns : display name, allow null private bool?ShowColumnSetting() { var modelType = _codeGeneratorViewModel.ModelType.CodeType; string savefolderPath = Path.Combine(Context.ActiveProject.GetFullPath(), "CodeGen"); StorageMan <MetaTableInfo> sm = new StorageMan <MetaTableInfo>(modelType.Name, savefolderPath); MetaTableInfo data = sm.Read(); if (data.Columns.Any()) { _ModelMetadataVM = new ModelMetadataViewModel(data); } else { string dbContextTypeName = _codeGeneratorViewModel.DbContextModelType.TypeName; ICodeTypeService codeTypeService = GetService <ICodeTypeService>(); CodeType dbContext = codeTypeService.GetCodeType(Context.ActiveProject, dbContextTypeName); IEntityFrameworkService efService = Context.ServiceProvider.GetService <IEntityFrameworkService>(); ModelMetadata efMetadata = efService.AddRequiredEntity(Context, dbContextTypeName, modelType.FullName); _ModelMetadataVM = new ModelMetadataViewModel(efMetadata); } ModelMetadataDialog dialog = new ModelMetadataDialog(_ModelMetadataVM); bool?isOk = dialog.ShowModal(); if (isOk == true) { sm.Save(_ModelMetadataVM.DataModel); } return(isOk); }
protected ModelMetadata GenerateContextAndController() { string typeName = base.Model.ModelType.TypeName; string str = base.Model.DataContextType.TypeName; IEntityFrameworkService service = base.Context.ServiceProvider.GetService <IEntityFrameworkService>(); ModelMetadata modelMetadatum = service.AddRequiredEntity(base.Context, str, typeName); CodeType codeType = base.Context.ServiceProvider.GetService <ICodeTypeService>().GetCodeType(base.Context.ActiveProject, str); base.GenerateController(this.AddTemplateParameters(codeType, modelMetadatum)); return(modelMetadatum); }
protected ModelMetadata GenerateContextAndController() { string modelTypeName = Model.ModelType.TypeName; string dbContextTypeName = Model.DataContextType.TypeName; // First Scaffold the DB Context IEntityFrameworkService efService = Context.ServiceProvider.GetService <IEntityFrameworkService>(); ModelMetadata modelMetadata = efService.AddRequiredEntity(Context, dbContextTypeName, modelTypeName); // After the above step the dbContext must have been created. CodeType dbContextType = Context.ServiceProvider.GetService <ICodeTypeService>().GetCodeType(Context.ActiveProject, dbContextTypeName); IDictionary <string, object> templateParameters = AddTemplateParameters(dbContextType, modelMetadata); // scaffold the controller GenerateController(templateParameters); return(modelMetadata); }
/// <summary> /// Any UI to be displayed after the scaffolder has been selected from the Add Scaffold dialog. /// Any validation on the input for values in the UI should be completed before returning from this method. /// </summary> /// <returns></returns> public override bool ShowUIAndValidate() { // Bring up the selection dialog and allow user to select a model type SelectModelWindow window = new SelectModelWindow(_viewModel); bool?showDialog = window.ShowDialog(); TargetProject = Context.ActiveProject; ProjectBuilder projectBuilder = new ProjectBuilder(); projectBuilder.BuildProject(Context.ActiveProject); GetProjectUrl(); _entityModelType = window.EntityType.SelectedItem as ModelType; var entityModel = window.EntityType.SelectedItem as ModelType; var dbContextModel = window.DbContextType.SelectedItem as ModelType; IEntityFrameworkService efService = Context.ServiceProvider.GetService(typeof(IEntityFrameworkService)) as IEntityFrameworkService; ModelMetadata entityMetadata = efService.AddRequiredEntity(this.Context, dbContextModel.CodeType.FullName, entityModel.TypeName); _entityType = _entityModelType.ShortTypeName; _entityProperties = new Dictionary <string, string>(); foreach (var eProperty in entityMetadata.Properties) { if (eProperty.IsAutoGenerated) { continue; } if (eProperty.IsPrimaryKey) { _entityKeyType = eProperty.ShortTypeName; _entityKeyName = eProperty.PropertyName; continue; } _entityProperties.Add(eProperty.PropertyName, eProperty.ShortTypeName); } return(showDialog ?? false); }
protected IDictionary <string, ModelMetadata> GetOneToManyModelDictionary(ModelMetadata efMetadata, IEntityFrameworkService efService, string dbContextTypeName) { var dict = new Dictionary <string, ModelMetadata>(); foreach (var prop in efMetadata.Properties) { if (prop.AssociationDirection == AssociationDirection.OneToMany) { string propname = prop.PropertyName; //var relmeta = prop.RelatedModel; string typename = prop.TypeName; ModelMetadata modelMetadata = efService.AddRequiredEntity(Context, dbContextTypeName, typename); if (!dict.ContainsKey(propname)) { dict.Add(propname, modelMetadata); } } } return(dict); }
// Collects the common data needed by all of the scaffolded output and generates: // 1) Dynamic Data Field Templates // 2) Web Forms Pages private void GenerateCode(Project project, string selectionRelativePath, WebFormsCodeGeneratorViewModel codeGeneratorViewModel) { // Get Model Type var modelType = codeGeneratorViewModel.ModelType.CodeType; // Ensure the Data Context string dbContextTypeName = codeGeneratorViewModel.DbContextModelType.TypeName; IEntityFrameworkService efService = Context.ServiceProvider.GetService <IEntityFrameworkService>(); ModelMetadata efMetadata = efService.AddRequiredEntity(Context, dbContextTypeName, modelType.FullName); var oneToManyModels = GetOneToManyModelDictionary(efMetadata, efService, dbContextTypeName); // Get the dbContext ICodeTypeService codeTypeService = GetService <ICodeTypeService>(); CodeType dbContext = codeTypeService.GetCodeType(project, dbContextTypeName); // Get the dbContext namespace string dbContextNamespace = dbContext.Namespace != null ? dbContext.Namespace.FullName : String.Empty; // Ensure the Dynamic Data Field templates EnsureDynamicDataFieldTemplates(project, dbContextNamespace, dbContextTypeName); EnsurePepositoriesTemplates(project, dbContextNamespace, dbContextTypeName); EnsureExtensionsTemplates(project, dbContextNamespace, dbContextTypeName); AddEntityRepositoryTemplates( project, selectionRelativePath, dbContextNamespace, dbContextTypeName, modelType, efMetadata, codeGeneratorViewModel.OverwriteViews ); // Add Web Forms Pages from Templates AddWebFormsPages( project, selectionRelativePath, dbContextNamespace, dbContextTypeName, modelType, efMetadata, codeGeneratorViewModel.UseMasterPage, codeGeneratorViewModel.DesktopMasterPage, codeGeneratorViewModel.DesktopPlaceholderId, codeGeneratorViewModel.OverwriteViews, oneToManyModels ); foreach (var dicitem in oneToManyModels) { var metadata = dicitem.Value; var modelName = this.GetModelName(efMetadata, metadata.EntitySetName); AddEntityRepositoryTemplates( project, selectionRelativePath, dbContextNamespace, dbContextTypeName, modelType, metadata, codeGeneratorViewModel.OverwriteViews, modelName ); } // Add Web Forms Pages from Templates }
// Collects the common data needed by all of the scaffolded output and generates: // 1) Add Controller // 2) Add View private void GenerateCode(Project project, string selectionRelativePath, MvcCodeGeneratorViewModel codeGeneratorViewModel) { // Get Model Type var modelType = codeGeneratorViewModel.ModelType.CodeType; // Get the dbContext string dbContextTypeName = codeGeneratorViewModel.DbContextModelType.TypeName; ICodeTypeService codeTypeService = GetService <ICodeTypeService>(); CodeType dbContext = codeTypeService.GetCodeType(project, dbContextTypeName); // Get the Entity Framework Meta Data IEntityFrameworkService efService = Context.ServiceProvider.GetService <IEntityFrameworkService>(); ModelMetadata efMetadata = efService.AddRequiredEntity(Context, dbContextTypeName, modelType.FullName); // Create Controller string controllerName = codeGeneratorViewModel.ControllerName; string controllerRootName = controllerName.Replace("Controller", ""); string outputFolderPath = Path.Combine(selectionRelativePath, controllerName); string viewPrefix = codeGeneratorViewModel.ViewPrefix; string programTitle = codeGeneratorViewModel.ProgramTitle; AddMvcController(project: project , controllerName: controllerName , controllerRootName: controllerRootName , outputPath: outputFolderPath , ContextTypeName: dbContext.Name , modelType: modelType , efMetadata: efMetadata , viewPrefix: viewPrefix , overwrite: codeGeneratorViewModel.OverwriteViews); if (!codeGeneratorViewModel.GenerateViews) { return; } // add Metadata for Model outputFolderPath = Path.Combine(GetModelFolderPath(selectionRelativePath), modelType.Name + "Metadata"); AddModelMetadata(project: project , controllerName: controllerName , controllerRootName: controllerRootName , outputPath: outputFolderPath , ContextTypeName: dbContext.Name , modelType: modelType , efMetadata: efMetadata , overwrite: codeGeneratorViewModel.OverwriteViews); //_ViewStart & Create _Layout string viewRootPath = GetViewsFolderPath(selectionRelativePath); if (codeGeneratorViewModel.LayoutPageSelected) { string areaName = GetAreaName(selectionRelativePath); AddDependencyFile(project, viewRootPath, areaName); } // EditorTemplates, DisplayTemplates AddDataFieldTemplates(project, viewRootPath); // Views for C.R.U.D string viewFolderPath = Path.Combine(viewRootPath, controllerRootName); foreach (string viewName in new string[4] { "Index", "Create", "Edit", "EditForm" }) { //string viewName = string.Format(view, viewPrefix); //未完成 /* * Index CustIndex * Create CustCreate * Edit CustEdit * EditForm CustEditForm * * _Edit _CustEdit */ AddView(project , viewFolderPath, viewPrefix, viewName, programTitle , controllerRootName, modelType, efMetadata , referenceScriptLibraries: codeGeneratorViewModel.ReferenceScriptLibraries , isLayoutPageSelected: codeGeneratorViewModel.LayoutPageSelected , layoutPageFile: codeGeneratorViewModel.LayoutPageFile , overwrite: codeGeneratorViewModel.OverwriteViews ); } }
public override void GenerateCode() { // Obtendo informações do projeto corrente, sempre do tipo ASP.Net MVC, onde foi ativada a extension Project projetoCorrente = Context.ActiveProject; // Obtendo uma lista de todos os projetos abertos na Instância corrente do Visual Studio. Permite a criação de objetos Solution solucao = projetoCorrente.DTE.Solution; var listaDeProjetos = new List <Project>(); // Define uma lista com todos os projetos abertos foreach (Project p in solucao.Projects) { if (p.Kind == Constants.vsProjectKindSolutionItems) { listaDeProjetos.AddRange(p.ExtrairSubProjetos()); } else { listaDeProjetos.Add(p); } } // Contexto do banco selecionado pelo Programador var contextoDoBanco = _viewModel.ContextoDeBancoSelecionado; // Lista de Entidades selecionadas pelo Programador var listaDeEntidades = _viewModel.ListaDeEntidadesSelecionadas; // Define o projeto onde estão as entidades selecionadas Project projetoDaEntidade = null; foreach (Project p1 in listaDeProjetos) { if (listaDeEntidades[0].CodeType.Namespace.FullName.StartsWith(p1.Name + ".")) { projetoDaEntidade = p1; break; } } // Define o projeto onde existe o contexto do banco Project projetoDoContexto = null; foreach (Project p2 in listaDeProjetos) { if (contextoDoBanco.CodeType.Namespace.FullName.StartsWith(p2.Name + ".")) { projetoDoContexto = p2; break; } } var namespacePadrao = string.Empty; var diretorioDaArea = string.Empty; if (_viewModel.EhArea) { // TODO: Controlar entidades que devem ser criadas dentro de áreas //string AreaName = _viewModel.AreaSelecionada; //ProjectItem AreaItem = T4Area(projetoCorrente, nomeDaArea); //diretorioDaArea = string.Format("Areas\\{0}\\", nomeDaArea); //namespacePadrao = AreaItem.GetDefaultNamespace(); } var diretorioRelativo = diretorioDaArea; // Para cada entidade selecionada, cria um Repositório, um Serviço e um MVC ou MVVM foreach (var entidade in listaDeEntidades.Select(p => p.CodeType)) { // Entity Framework Meta Data // Os VSPackages gerenciados pode usar GetService para obter as interfaces VSSDK COM consultando os assemblies de interoperabilidade IEntityFrameworkService efService = (IEntityFrameworkService)Context.ServiceProvider.GetService(typeof(IEntityFrameworkService)); // Obtem todas as informações da entidade que o Entity possui. Tipos dos campos e relacionamentos ModelMetadata efMetadata = efService.AddRequiredEntity(Context, contextoDoBanco.TypeName, entidade.FullName); // Adiciona a intreface do repositório na camada do contexto do banco RepositorioTipadoInterface(projetoDaEntidade, entidade, contextoDoBanco, efMetadata); // Adiciona classe de repositório na camada do contexto do banco RepositorioTipado(projetoDoContexto, entidade, contextoDoBanco, efMetadata); // Adiciona classe de serviço na mesma camada do domínio / entidades ServicoTipado(projetoDaEntidade, entidade, contextoDoBanco, efMetadata); NgControle(projetoCorrente, entidade, diretorioRelativo, namespacePadrao, contextoDoBanco, efMetadata); NgVisao(projetoCorrente, entidade, diretorioRelativo, namespacePadrao, contextoDoBanco, efMetadata); } }
/// <summary> /// This method is executed after the ShowUIAndValidate method, and this is where the actual code generation should occur. /// In this example, we are generating a new file from t4 template based on the ModelType selected in our UI. /// </summary> public override void GenerateCode() { // Get the selected code type var codeType = _viewModel.SelectedModelType.CodeType; var codeType2 = _viewModel.SelectedModelType2.CodeType; var filterClass = _viewModel.SelectedModelType3.CodeType; string[] regions = _viewModel.regions.Split(';'); // Setup the scaffolding item creation parameters to be passed into the T4 template. string str = ""; string t = String.Concat(str.Where(s => String.Equals(s + "", (s + "").ToUpper(), StringComparison.Ordinal))); string modelTypeName = codeType.FullName; string dbContextTypeName = codeType2.FullName; string storedProcedureName = filterClass.Name; storedProcedureName = storedProcedureName.Substring(0, storedProcedureName.Length - 7); // First Scaffold the DB Context IEntityFrameworkService efService = (IEntityFrameworkService)Context.ServiceProvider.GetService(typeof(IEntityFrameworkService)); ModelMetadata modelMetadata = efService.AddRequiredEntity(Context, dbContextTypeName, modelTypeName); Type storedClass = Type.GetType(filterClass.FullName); string[,] p = getParamsMatrix(dbContextTypeName, storedProcedureName); Type contextClass = Type.GetType(dbContextTypeName); MethodInfo[] mi = contextClass.GetMethods(); List <MethodInfo> li = new List <MethodInfo>(mi); li = li.Where(i => i.Name.Contains("spWS_")).OrderBy(i => i.Name).ToList(); string[,] AllWsParams = new string[100, 4]; int comp = 0; bool typeMethod; foreach (var item in li) { typeMethod = item.ReturnType.Name.Contains("ObjectResult"); AllWsParams[comp, 0] = typeMethod.ToString(); AllWsParams[comp, 1] = item.Name; AllWsParams[comp, 2] = getParamsStringWithType(dbContextTypeName, item.Name); AllWsParams[comp, 3] = getParamsString(dbContextTypeName, item.Name); comp++; } var parameters = new Dictionary <string, object>() { { "ProjectName", Context.ActiveProject.Name }, { "ContextName", dbContextTypeName }, { "AllWsParams", AllWsParams }, { "Regions", regions } }; // Add the custom scaffolding item from T4 template. this.AddFolder(Context.ActiveProject, @"WebServices"); this.AddFileFromTemplate(Context.ActiveProject, "WebServices\\" + Context.ActiveProject.Name, "WebServiceASMX", parameters, skipIfExists: false); this.AddFileFromTemplate(Context.ActiveProject, "WebServices\\" + Context.ActiveProject.Name + ".asmx", "WebServiceCS", parameters, skipIfExists: false); }
/// <summary> /// This method is executed after the ShowUIAndValidate method, and this is where the actual code generation should occur. /// In this example, we are generating a new file from t4 template based on the ModelType selected in our UI. /// </summary> public override void GenerateCode() { Project projectActive = Context.ActiveProject; Solution solution = projectActive.DTE.Solution; List <Project> list = new List <Project>(); foreach (Project projectA in solution.Projects) { if (projectA.Kind == Constants.vsProjectKindSolutionItems) { list.AddRange(GetSolutionFolderProjects(projectA)); } else { list.Add(projectA); } } var dbContextClass = _viewModel.SelectedContextType; var modelTypes = _viewModel.SelectedModelType; //find context projects Project projectContext = null; foreach (Project projectA in list) { if (dbContextClass.CodeType.Namespace.FullName.StartsWith(projectA.Name + ".")) { projectContext = projectA; } } string defaultNamespace = null; string AreaPath = string.Empty; //return; if (_viewModel.SelectedController != "MVC") { AddWebApiConfig(projectActive, dbContextClass, modelTypes.Select(p => p.CodeType).ToList(), projectContext.Name + ".Models"); } #region Area Init if (_viewModel.IsArea) { string AreaName = _viewModel.SelectedArea; ProjectItem AreaItem = AddArea(projectActive, AreaName); AreaPath = string.Format("Areas\\{0}\\", AreaName); defaultNamespace = AreaItem.GetDefaultNamespace(); } #endregion Area Init var selectionRelativePath = AreaPath; AddMvcModels(projectActive, selectionRelativePath + "Models\\", defaultNamespace); foreach (var codeType in modelTypes.Select(p => p.CodeType)) { // Get the Entity Framework Meta Data IEntityFrameworkService efService = (IEntityFrameworkService)Context.ServiceProvider.GetService(typeof(IEntityFrameworkService)); ModelMetadata efMetadata = efService.AddRequiredEntity(Context, dbContextClass.TypeName, codeType.FullName); if (efMetadata.PrimaryKeys.Count() > 1) { continue; } if (_viewModel.SelectedController != "MVC") { AddViewsControllers(projectActive, selectionRelativePath + "Controllers\\", codeType, defaultNamespace); } AddBLL(projectContext, "BLL\\", codeType, dbContextClass, efMetadata); if (_viewModel.SelectedController == "WEBAPI") { AddMvcControllers(projectActive, selectionRelativePath + "Controllers\\API\\", codeType, efMetadata, defaultNamespace); } else if (_viewModel.SelectedController == "ODataV3" || _viewModel.SelectedController == "ODataV4") { AddMvcControllers(projectActive, selectionRelativePath + "Controllers\\OData\\", codeType, efMetadata, defaultNamespace); } else { AddMvcControllers(projectActive, selectionRelativePath + "Controllers\\", codeType, efMetadata, defaultNamespace); } AddMvcViews(projectActive, selectionRelativePath + "Views\\", codeType, dbContextClass, efMetadata, defaultNamespace); } }