Beispiel #1
0
        internal static async Task <ModelTypeAndContextModel> ValidateModelAndGetEFMetadata(
            CommonCommandLineModel commandLineModel,
            IEntityFrameworkService entityFrameworkService,
            IModelTypesLocator modelTypesLocator,
            string areaName)
        {
            ModelType model       = ValidationUtil.ValidateType(commandLineModel.ModelClass, "model", modelTypesLocator);
            ModelType dataContext = ValidationUtil.ValidateType(commandLineModel.DataContextClass, "dataContext", modelTypesLocator, throwWhenNotFound: false);

            // Validation successful
            Contract.Assert(model != null, MessageStrings.ValidationSuccessfull_modelUnset);

            var dbContextFullName = dataContext != null ? dataContext.FullName : commandLineModel.DataContextClass;

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

            return(new ModelTypeAndContextModel()
            {
                ModelType = model,
                DbContextFullName = dbContextFullName,
                ContextProcessingResult = modelMetadata
            });
        }
Beispiel #2
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="logger"></param>
 public XbCodeGenerator(
     IApplicationInfo applicationInfo,
     IServiceProvider serviceProvider,
     IModelTypesLocator modelTypesLocator,
     IEntityFrameworkService entityFrameworkService,
     ILogger logger
     )
 {
     try
     {
         this._applicationInfo = applicationInfo
                                 ?? throw new ArgumentNullException(nameof(applicationInfo));
         this._serviceProvider = serviceProvider
                                 ?? throw new ArgumentNullException(nameof(serviceProvider));
         this._modelTypesLocator = modelTypesLocator
                                   ?? throw new ArgumentNullException(nameof(modelTypesLocator));
         this._entityFrameworkService = entityFrameworkService
                                        ?? throw new ArgumentNullException(nameof(entityFrameworkService));
         this._logger = logger
                        ?? throw new ArgumentNullException(nameof(logger));
     }
     catch (Exception ex)
     {
         this._logger?.LogMessage(Xb.Util.GetErrorHighlighted(ex));
         throw ex;
     }
 }
Beispiel #3
0
        // 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);
        }
Beispiel #4
0
        /// <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 AddScaffoldDependencies(List <NuGetPackage> packages)
        {
            base.AddScaffoldDependencies(packages);
            IEntityFrameworkService service = base.Context.ServiceProvider.GetService <IEntityFrameworkService>();

            packages.AddRange(service.Dependencies);
        }
        protected override void AddTemplateParameters(IDictionary <string, object> templateParameters)
        {
            base.AddTemplateParameters(templateParameters);
            CodeType      codeType = base.Model.ModelType.CodeType;
            ModelMetadata codeModelModelMetadatum = new CodeModelModelMetadata(codeType);

            if ((int)codeModelModelMetadatum.PrimaryKeys.Length == 0)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "The entity type '{0}' has no key defined. Define a key for this entity type.", codeType.Name));
            }
            templateParameters.Add("ModelMetadata", codeModelModelMetadatum);
            List <CodeType> codeTypes = new List <CodeType>()
            {
                codeType
            };

            templateParameters.Add("RequiredNamespaces", base.GetRequiredNamespaces(codeTypes));
            templateParameters.Add("ModelTypeNamespace", (codeType.Namespace != null ? codeType.Namespace.FullName : string.Empty));
            templateParameters.Add("ModelTypeName", codeType.Name);
            templateParameters.Add("UseAsync", base.Model.IsAsyncSelected);
            IEntityFrameworkService service = base.Context.ServiceProvider.GetService <IEntityFrameworkService>();
            string pluralizedWord           = service.GetPluralizedWord(codeType.Name, CultureInfo.InvariantCulture);

            templateParameters.Add("EntitySetName", pluralizedWord);
            CodeDomProvider codeDomProvider = ValidationUtil.GenerateCodeDomProvider(ProjectExtensions.GetCodeLanguage(base.Model.ActiveProject));
            string          str             = codeDomProvider.CreateEscapedIdentifier(codeType.Name.ToLowerInvariantFirstChar());
            string          str1            = codeDomProvider.CreateEscapedIdentifier(pluralizedWord.ToLowerInvariantFirstChar());

            templateParameters.Add("ModelVariable", str);
            templateParameters.Add("EntitySetVariable", str1);
            templateParameters.Add("ODataModificationMessage", "The WebApiConfig class may require additional changes to add a route for this controller. Merge these statements into the Register method of the WebApiConfig class as applicable. Note that OData URLs are case sensitive.");

            templateParameters.Add("IsLegacyOdataVersion", base.Framework.IsODataLegacy(base.Context));
        }
Beispiel #7
0
 public TodoItemViewModel(
     INavigationService navigationService,
     IEntityFrameworkService entityFrameworkService)
 {
     _navigationService      = navigationService;
     _entityFrameworkService = entityFrameworkService;
 }
Beispiel #8
0
        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);
            }
        }
Beispiel #9
0
 protected internal override void AddScaffoldDependencies(List <NuGetPackage> packages)
 {
     if (base.Model.DataContextType != null)
     {
         IEntityFrameworkService service = base.Context.ServiceProvider.GetService <IEntityFrameworkService>();
         packages.AddRange(service.Dependencies);
     }
 }
        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);
        }
        public string GenerateControllerName(string modelClassName)
        {
            if (string.IsNullOrWhiteSpace(modelClassName))
            {
                return(null);
            }
            IEntityFrameworkService service = base.Context.ServiceProvider.GetService <IEntityFrameworkService>();
            string pluralizedWord           = service.GetPluralizedWord(modelClassName, CultureInfo.GetCultureInfo(1033)) ?? modelClassName;

            return(base.GetGeneratedName(string.Concat(pluralizedWord, "{0}", MvcProjectUtil.ControllerSuffix), base.CodeFileExtension));
        }
Beispiel #12
0
        // Todo: Instead of each generator taking services, provide them in some base class?
        // However for it to be effective, it should be property dependecy injection rather
        // than constructor injection.
        public ViewGenerator(
            ILibraryManager libraryManager,
            IApplicationEnvironment environment,
            IModelTypesLocator modelTypesLocator,
            IEntityFrameworkService entityFrameworkService,
            ICodeGeneratorActionsService codeGeneratorActionsService,
            IServiceProvider serviceProvider,
            ILogger logger)
            : base(environment)
        {
            if (libraryManager == null)
            {
                throw new ArgumentNullException(nameof(libraryManager));
            }

            if (environment == null)
            {
                throw new ArgumentNullException(nameof(environment));
            }

            if (modelTypesLocator == null)
            {
                throw new ArgumentNullException(nameof(modelTypesLocator));
            }

            if (entityFrameworkService == null)
            {
                throw new ArgumentNullException(nameof(entityFrameworkService));
            }

            if (codeGeneratorActionsService == null)
            {
                throw new ArgumentNullException(nameof(codeGeneratorActionsService));
            }

            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            _libraryManager = libraryManager;
            _codeGeneratorActionsService = codeGeneratorActionsService;
            _modelTypesLocator = modelTypesLocator;
            _entityFrameworkService = entityFrameworkService;
            _serviceProvider = serviceProvider;
            _logger = logger;
        }
Beispiel #13
0
        // Todo: Instead of each generator taking services, provide them in some base class?
        // However for it to be effective, it should be property dependecy injection rather
        // than constructor injection.
        public ViewGenerator(
            ILibraryManager libraryManager,
            IApplicationInfo applicationInfo,
            IModelTypesLocator modelTypesLocator,
            IEntityFrameworkService entityFrameworkService,
            ICodeGeneratorActionsService codeGeneratorActionsService,
            IServiceProvider serviceProvider,
            ILogger logger)
            : base(applicationInfo)
        {
            if (libraryManager == null)
            {
                throw new ArgumentNullException(nameof(libraryManager));
            }

            if (applicationInfo == null)
            {
                throw new ArgumentNullException(nameof(applicationInfo));
            }

            if (modelTypesLocator == null)
            {
                throw new ArgumentNullException(nameof(modelTypesLocator));
            }

            if (entityFrameworkService == null)
            {
                throw new ArgumentNullException(nameof(entityFrameworkService));
            }

            if (codeGeneratorActionsService == null)
            {
                throw new ArgumentNullException(nameof(codeGeneratorActionsService));
            }

            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            _libraryManager = libraryManager;
            _codeGeneratorActionsService = codeGeneratorActionsService;
            _modelTypesLocator           = modelTypesLocator;
            _entityFrameworkService      = entityFrameworkService;
            _serviceProvider             = serviceProvider;
            _logger = logger;
        }
Beispiel #14
0
 // Todo: Instead of each generator taking services, provide them in some base class?
 // However for it to be effective, it should be property dependecy injection rather
 // than constructor injection.
 public ViewGenerator(
     [NotNull] ILibraryManager libraryManager,
     [NotNull] IApplicationEnvironment environment,
     [NotNull] IModelTypesLocator modelTypesLocator,
     [NotNull] IEntityFrameworkService entityFrameworkService,
     [NotNull] ICodeGeneratorActionsService codeGeneratorActionsService)
 {
     _libraryManager              = libraryManager;
     _applicationEnvironment      = environment;
     _codeGeneratorActionsService = codeGeneratorActionsService;
     _modelTypesLocator           = modelTypesLocator;
     _entityFrameworkService      = entityFrameworkService;
 }
Beispiel #15
0
 public ControllerWithContextGenerator(
     [NotNull] ILibraryManager libraryManager,
     [NotNull] IApplicationEnvironment environment,
     [NotNull] IModelTypesLocator modelTypesLocator,
     [NotNull] IEntityFrameworkService entityFrameworkService,
     [NotNull] ICodeGeneratorActionsService codeGeneratorActionsService,
     [NotNull] IServiceProvider serviceProvider,
     [NotNull] ILogger logger)
     : base(libraryManager, environment, codeGeneratorActionsService, serviceProvider, logger)
 {
     ModelTypesLocator      = modelTypesLocator;
     EntityFrameworkService = entityFrameworkService;
 }
        protected internal void AddScaffoldDependencies(List <NuGetPackage> packages)
        {
            if (packages == null)
            {
                throw new ArgumentNullException("packages");
            }

            base.AddScaffoldDependencies(packages);

            IEntityFrameworkService efService = Context.ServiceProvider.GetService <IEntityFrameworkService>();

            packages.AddRange(efService.Dependencies);
        }
        private void GetStoreProcedureFunction_TESTCODE()
        {
            string                  dbContextTypeName = this.DbContextModelType.TypeName;
            ICodeTypeService        codeTypeService   = GetService <ICodeTypeService>();
            Project                 project           = _context.ActiveProject;
            CodeType                dbContext         = codeTypeService.GetCodeType(project, dbContextTypeName);
            IEntityFrameworkService efService         = _context.ServiceProvider.GetService <IEntityFrameworkService>();

            //ModelMetadata efMetadata = efService.AddRequiredEntity(_context, dbContextTypeName, "");

            //GetMethodInfo(string.Format("{0}, {1}", dbContextTypeName, project.Name));


            foreach (CodeElement code in dbContext.Members)
            {
                if (code.Kind == vsCMElement.vsCMElementFunction)
                {
                    //if (code.Name != "QueryBooks")
                    //    continue;

                    CodeFunction myMethod = (CodeFunction)code;
                    //讀取參數
                    foreach (CodeElement p in myMethod.Parameters)
                    {
                        CodeParameter p1 = (CodeParameter)p;

                        string pName = p1.Name;
                        string pType = p1.Type.AsString;
                    }

                    CodeTypeRef returnTypeRef = myMethod.Type;
                    string      enumType      = returnTypeRef.AsFullName;
                    int         idx1          = enumType.IndexOf("<");
                    int         idx2          = enumType.LastIndexOf(">");
                    string      baseType      = enumType.Substring(idx1 + 1, idx2 - idx1 - 1);
                    CodeType    returnModel   = codeTypeService.GetCodeType(project, baseType);
                    // 讀取回傳型別
                    foreach (CodeElement cc in returnModel.Members)
                    {
                        if (cc.Kind == vsCMElement.vsCMElementProperty)
                        {
                            CodeProperty p2    = (CodeProperty)cc;
                            string       pName = p2.Name;
                            string       pType = p2.Type.AsString;
                        }
                    }
                }
            }
        }
        public ControllerWithContextGenerator(
            ILibraryManager libraryManager,
            IApplicationEnvironment environment,
            IModelTypesLocator modelTypesLocator,
            IEntityFrameworkService entityFrameworkService,
            ICodeGeneratorActionsService codeGeneratorActionsService,
            IServiceProvider serviceProvider,
            ILogger logger)
            : base(libraryManager, environment, codeGeneratorActionsService, serviceProvider, logger)
        {
            if (libraryManager == null)
            {
                throw new ArgumentNullException(nameof(libraryManager));
            }

            if (environment == null)
            {
                throw new ArgumentNullException(nameof(environment));
            }

            if (modelTypesLocator == null)
            {
                throw new ArgumentNullException(nameof(modelTypesLocator));
            }

            if (entityFrameworkService == null)
            {
                throw new ArgumentNullException(nameof(entityFrameworkService));
            }

            if (codeGeneratorActionsService == null)
            {
                throw new ArgumentNullException(nameof(codeGeneratorActionsService));
            }

            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            ModelTypesLocator = modelTypesLocator;
            EntityFrameworkService = entityFrameworkService;
        }
        public ControllerWithContextGenerator(
            ILibraryManager libraryManager,
            IApplicationInfo applicationInfo,
            IModelTypesLocator modelTypesLocator,
            IEntityFrameworkService entityFrameworkService,
            ICodeGeneratorActionsService codeGeneratorActionsService,
            IServiceProvider serviceProvider,
            ILogger logger)
            : base(libraryManager, applicationInfo, codeGeneratorActionsService, serviceProvider, logger)
        {
            if (libraryManager == null)
            {
                throw new ArgumentNullException(nameof(libraryManager));
            }

            if (applicationInfo == null)
            {
                throw new ArgumentNullException(nameof(applicationInfo));
            }

            if (modelTypesLocator == null)
            {
                throw new ArgumentNullException(nameof(modelTypesLocator));
            }

            if (entityFrameworkService == null)
            {
                throw new ArgumentNullException(nameof(entityFrameworkService));
            }

            if (codeGeneratorActionsService == null)
            {
                throw new ArgumentNullException(nameof(codeGeneratorActionsService));
            }

            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            ModelTypesLocator      = modelTypesLocator;
            EntityFrameworkService = entityFrameworkService;
        }
Beispiel #20
0
        internal static async Task <ModelTypeAndContextModel> ValidateModelAndGetCodeModelMetadata(
            CommonCommandLineModel commandLineModel,
            IEntityFrameworkService entityFrameworkService,
            IModelTypesLocator modelTypesLocator)
        {
            ModelType model = ValidationUtil.ValidateType(commandLineModel.ModelClass, "model", modelTypesLocator);

            Contract.Assert(model != null, MessageStrings.ValidationSuccessfull_modelUnset);
            var result = await entityFrameworkService.GetModelMetadata(model);

            return(new ModelTypeAndContextModel()
            {
                ModelType = model,
                ContextProcessingResult = result
            });
        }
Beispiel #21
0
 // Todo: Instead of each generator taking services, provide them in some base class?
 // However for it to be effective, it should be property dependecy injection rather
 // than constructor injection.
 public ViewGenerator(
     [NotNull]ILibraryManager libraryManager,
     [NotNull]IApplicationEnvironment environment,
     [NotNull]IModelTypesLocator modelTypesLocator,
     [NotNull]IEntityFrameworkService entityFrameworkService,
     [NotNull]ICodeGeneratorActionsService codeGeneratorActionsService,
     [NotNull]IServiceProvider serviceProvider,
     [NotNull]ILogger logger)
 {
     _libraryManager = libraryManager;
     _applicationEnvironment = environment;
     _codeGeneratorActionsService = codeGeneratorActionsService;
     _modelTypesLocator = modelTypesLocator;
     _entityFrameworkService = entityFrameworkService;
     _serviceProvider = serviceProvider;
     _logger = logger;
 }
Beispiel #22
0
 // Todo: Instead of each generator taking services, provide them in some base class?
 // However for it to be effective, it should be property dependecy injection rather
 // than constructor injection.
 public ViewGenerator(
     [NotNull] ILibraryManager libraryManager,
     [NotNull] IApplicationEnvironment environment,
     [NotNull] IModelTypesLocator modelTypesLocator,
     [NotNull] IEntityFrameworkService entityFrameworkService,
     [NotNull] ICodeGeneratorActionsService codeGeneratorActionsService,
     [NotNull] IServiceProvider serviceProvider,
     [NotNull] ILogger logger)
     : base(environment)
 {
     _libraryManager = libraryManager;
     _codeGeneratorActionsService = codeGeneratorActionsService;
     _modelTypesLocator           = modelTypesLocator;
     _entityFrameworkService      = entityFrameworkService;
     _serviceProvider             = serviceProvider;
     _logger = logger;
 }
Beispiel #23
0
        public string GenerateControllerName(string modelClassName)
        {
            if (String.IsNullOrWhiteSpace(modelClassName))
            {
                return(null);
            }

            IEntityFrameworkService efService = Context.ServiceProvider.GetService <IEntityFrameworkService>();
            string controllerRootName         = efService.GetPluralizedWord(modelClassName, CultureInfo.GetCultureInfo(1033));

            if (controllerRootName == null)
            {
                controllerRootName = modelClassName;
            }

            return(GetGeneratedName(controllerRootName + "{0}" + MvcProjectUtil.ControllerSuffix, CodeFileExtension));
        }
Beispiel #24
0
        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);
        }
 public ControllerGenerator(
     [NotNull] ILibraryManager libraryManager,
     [NotNull] IApplicationEnvironment environment,
     [NotNull] IModelTypesLocator modelTypesLocator,
     [NotNull] IEntityFrameworkService entityFrameworkService,
     [NotNull] ICodeGeneratorActionsService codeGeneratorActionsService,
     [NotNull] ITypeActivator typeActivator,
     [NotNull] IServiceProvider serviceProvider,
     [NotNull] ILogger logger)
 {
     _libraryManager              = libraryManager;
     _applicationEnvironment      = environment;
     _codeGeneratorActionsService = codeGeneratorActionsService;
     _modelTypesLocator           = modelTypesLocator;
     _entityFrameworkService      = entityFrameworkService;
     _typeActivator   = typeActivator;
     _serviceProvider = serviceProvider;
     _logger          = logger;
 }
Beispiel #26
0
        protected override void AddTemplateParameters(IDictionary <string, object> templateParameters)
        {
            base.AddTemplateParameters(templateParameters);

            CodeType      codeType = Model.ModelType.CodeType;
            ModelMetadata metadata = new CodeModelModelMetadata(codeType);

            if (metadata.PrimaryKeys.Length == 0)
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.NoKeyDefinedError, codeType.Name));
            }
            templateParameters.Add("ModelMetadata", metadata);

            HashSet <string> requiredNamespaces = GetRequiredNamespaces(new List <CodeType>()
            {
                codeType
            });

            templateParameters.Add("RequiredNamespaces", requiredNamespaces);

            string modelTypeNamespace = codeType.Namespace != null ? codeType.Namespace.FullName : String.Empty;

            templateParameters.Add("ModelTypeNamespace", modelTypeNamespace);
            templateParameters.Add("ModelTypeName", codeType.Name);
            templateParameters.Add("UseAsync", Model.IsAsyncSelected);

            IEntityFrameworkService efService = Context.ServiceProvider.GetService <IEntityFrameworkService>();
            string entitySetName = efService.GetPluralizedWord(codeType.Name, CultureInfo.InvariantCulture);

            templateParameters.Add("EntitySetName", entitySetName);

            CodeDomProvider provider          = ValidationUtil.GenerateCodeDomProvider(Model.ActiveProject.GetCodeLanguage());
            string          modelVariable     = provider.CreateEscapedIdentifier(codeType.Name.ToLowerInvariantFirstChar());
            string          entitySetVariable = provider.CreateEscapedIdentifier(entitySetName.ToLowerInvariantFirstChar());

            templateParameters.Add("ModelVariable", modelVariable);
            templateParameters.Add("EntitySetVariable", entitySetVariable);

            templateParameters.Add("ODataModificationMessage", Resources.ScaffoldODataModificationMessage);
            templateParameters.Add("IsLegacyOdataVersion", Framework.IsODataLegacy(Context));
        }
Beispiel #27
0
        public ModelBasedViewScaffolder(
            IProjectContext projectContext,
            IApplicationInfo applicationInfo,
            IModelTypesLocator modelTypesLocator,
            IEntityFrameworkService entityFrameworkService,
            ICodeGeneratorActionsService codeGeneratorActionsService,
            IServiceProvider serviceProvider,
            ILogger logger)
            : base(projectContext, applicationInfo, codeGeneratorActionsService, serviceProvider, logger)
        {
            if (modelTypesLocator == null)
            {
                throw new ArgumentNullException(nameof(modelTypesLocator));
            }

            if (entityFrameworkService == null)
            {
                throw new ArgumentNullException(nameof(entityFrameworkService));
            }
            _modelTypesLocator      = modelTypesLocator;
            _entityFrameworkService = entityFrameworkService;
        }
Beispiel #28
0
        /// <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);
        }
Beispiel #29
0
        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);
        }
Beispiel #30
0
        // 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
        }
        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);
            }
        }
 public EntityFrameworkBuilder(IEntityFrameworkService service, IPlugin plugin)
 {
     _service = service;
     _plugin  = plugin;
     _logger  = _plugin.Container.Resolve <ILogger>();
 }
Beispiel #33
0
        // 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
                        );
            }
        }