コード例 #1
0
        // Returns the set of template folders appropriate for templateModel.ContentVersion
        private IEnumerable <string> GetTemplateFoldersForContentVersion(IdentityGeneratorTemplateModel templateModel)
        {
            if (!(templateModel is IdentityGeneratorTemplateModel2 templateModel2))
            {   // for back-compat
                return(TemplateFolders);
            }

            // The default content is packaged under the default location "Identity\*" (no subfolder).
            if (string.Equals(templateModel2.ContentVersion, ContentVersionDefault, StringComparison.Ordinal))
            {
                return(TemplateFolders);
            }

            // For non-default bootstrap versions, the content is packaged under "Identity_Versioned\[Version_Identifier]\*"
            // Note: In the future, if content gets pivoted on things other than bootstrap, this logic will need enhancement.
            if (string.Equals(templateModel2.ContentVersion, ContentVersionBootstrap3, StringComparison.Ordinal))
            {
                return(TemplateFoldersUtilities.GetTemplateFolders(
                           Constants.ThisAssemblyName,
                           _applicationInfo.ApplicationBasePath,
                           new[] {
                    Path.Combine(VersionedContentRelativeBaseDir, $"Bootstrap{templateModel2.BootstrapVersion}")
                },
                           _projectContext));
            }

            // This should get caught by IdentityGeneratorTemplateModelBuilder.ValidateCommandLine() and emit the same error.
            // But best to be safe here.
            // Note: If we start pivoting content on things other than bootstrap version, this error message will need to be reworked.
            throw new InvalidOperationException(string.Format(MessageStrings.InvalidBootstrapVersionForScaffolding, templateModel2.BootstrapVersion, string.Join(", ", ValidBootstrapVersions)));
        }
コード例 #2
0
        private static List <IdentityGeneratorFile> GetDataModelFiles(IdentityGeneratorTemplateModel templateModel)
        {
            var filesToGenerate = new List <IdentityGeneratorFile>();

            if (!templateModel.IsUsingExistingDbContext)
            {
                // Add DbContext template.
                filesToGenerate.Add(new IdentityGeneratorFile()
                {
                    IsTemplate      = true,
                    Name            = "ApplicationDbContext",
                    SourcePath      = "ApplicationDbContext.cshtml",
                    OutputPath      = Path.Combine("Areas", "Identity", "Data", $"{templateModel.DbContextClass}.cs"),
                    ShowInListFiles = false
                });

                if (templateModel.IsGenerateCustomUser)
                {
                    // Add custom user class template.
                    filesToGenerate.Add(new IdentityGeneratorFile()
                    {
                        IsTemplate      = true,
                        Name            = "ApplicationUser",
                        SourcePath      = "ApplicationUser.cshtml",
                        OutputPath      = Path.Combine("Areas", "Identity", "Data", $"{templateModel.UserClass}.cs"),
                        ShowInListFiles = false
                    });
                }
            }

            return(filesToGenerate);
        }
コード例 #3
0
        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);
            }
        }
コード例 #4
0
        private void ValidateFilesOption(IdentityGeneratorTemplateModel templateModel)
        {
            var errors = new List <string>();

            string contentVersion;

            if (templateModel is IdentityGeneratorTemplateModel2 templateModel2)
            {
                contentVersion = templateModel2.ContentVersion;
            }
            else
            {
                contentVersion = IdentityGenerator.ContentVersionDefault;
            }

            var invalidFiles = NamedFiles.Where(f => !IdentityGeneratorFilesConfig.GetFilesToList(contentVersion).Contains(f));

            if (invalidFiles.Any())
            {
                errors.Add(MessageStrings.InvalidFilesListMessage);
                errors.AddRange(invalidFiles);
            }

            if (errors.Any())
            {
                throw new InvalidOperationException(string.Join(Environment.NewLine, errors));
            }
        }
コード例 #5
0
        /// <summary>
        /// Creates a folder hierarchy:
        ///     ProjectDir
        ///        \ Areas
        ///            \ IdentityAreaName
        ///                \ Data
        ///                \ Pages
        ///                \ Services
        /// </summary>
        private void EnsureFolderLayout(string identityAreaName, IdentityGeneratorTemplateModel templateModel)
        {
            var areaBasePath = Path.Combine(_applicationInfo.ApplicationBasePath, "Areas");

            if (!_fileSystem.DirectoryExists(areaBasePath))
            {
                _fileSystem.CreateDirectory(areaBasePath);
            }

            var areaPath = Path.Combine(areaBasePath, identityAreaName);

            if (!_fileSystem.DirectoryExists(areaPath))
            {
                _fileSystem.CreateDirectory(areaPath);
            }

            var areaFolders = IdentityGeneratorFilesConfig.GetAreaFolders(
                !templateModel.IsUsingExistingDbContext);

            foreach (var areaFolder in areaFolders)
            {
                var path = Path.Combine(areaPath, areaFolder);
                if (!_fileSystem.DirectoryExists(path))
                {
                    _logger.LogMessage($"Adding folder: {path}", LogMessageLevel.Trace);
                    _fileSystem.CreateDirectory(path);
                }
            }
        }
コード例 #6
0
        private IdentityGeneratorFile[] DetermineFilesToGenerate(IdentityGeneratorTemplateModel templateModel)
        {
            var filesToGenerate = new List <IdentityGeneratorFile>(IdentityGeneratorFilesConfig.GetFilesToGenerate(NamedFiles, templateModel));

            // Check if we need to add ViewImports and which ones.
            if (!_commandlineModel.UseDefaultUI)
            {
                filesToGenerate.AddRange(IdentityGeneratorFilesConfig.GetViewImports(filesToGenerate, _fileSystem, _applicationInfo.ApplicationBasePath));
            }

            if (IdentityGeneratorFilesConfig.TryGetLayoutPeerFiles(_fileSystem, _applicationInfo.ApplicationBasePath, templateModel, out IReadOnlyList <IdentityGeneratorFile> layoutPeerFiles))
            {
                filesToGenerate.AddRange(layoutPeerFiles);
            }

            if (IdentityGeneratorFilesConfig.TryGetCookieConsentPartialFile(_fileSystem, _applicationInfo.ApplicationBasePath, templateModel, out IdentityGeneratorFile cookieConsentPartialConfig))
            {
                filesToGenerate.Add(cookieConsentPartialConfig);
            }

            var filesToGenerateArray = filesToGenerate.ToArray();

            ValidateFilesToGenerate(filesToGenerateArray);

            return(filesToGenerateArray);
        }
コード例 #7
0
        private static List <IdentityGeneratorFile> GetDataModelFiles(IdentityGeneratorTemplateModel templateModel)
        {
            var filesToGenerate = new List <IdentityGeneratorFile>();

            if (!templateModel.IsUsingExistingDbContext)
            {
                // Add DbContext template.
                filesToGenerate.Add(new IdentityGeneratorFile()
                {
                    IsTemplate      = true,
                    Name            = "ApplicationDbContext",
                    SourcePath      = "ApplicationDbContext.cshtml",
                    OutputPath      = Path.Combine("Areas", "Identity", "Data", $"{templateModel.DbContextClass}.cs"),
                    ShowInListFiles = false
                });

                if (templateModel.IsGenerateCustomUser)
                {
                    // Add custom user class template.
                    filesToGenerate.Add(new IdentityGeneratorFile()
                    {
                        IsTemplate      = true,
                        Name            = "ApplicationUser",
                        SourcePath      = "ApplicationUser.cshtml",
                        OutputPath      = Path.Combine("Areas", "Identity", "Data", $"{templateModel.UserClass}.cs"),
                        ShowInListFiles = false
                    });
                }
            }

            // add the _LoginPartial file. Its config will cause it to not be created if it already exists.
            filesToGenerate.Add(new IdentityGeneratorFile()
            {
                IsTemplate = true,
                Name       = "_LoginPartial",
                SourcePath = "_LoginPartial.cshtml",
                OutputPath = "Pages/Shared/_LoginPartial.cshtml",
                AltPaths   = new List <string>()
                {
                    "Pages/_LoginPartial.cshtml"
                },
                ShouldOverWrite = OverWriteCondition.Never,
                ShowInListFiles = false
            });

            return(filesToGenerate);
        }
コード例 #8
0
        private async Task AddStaticFiles(IdentityGeneratorTemplateModel templateModel)
        {
            var projectDir = Path.GetDirectoryName(_projectContext.ProjectFullPath);

            foreach (var staticFile  in templateModel.FilesToGenerate.Where(f => !f.IsTemplate))
            {
                var outputPath = Path.Combine(projectDir, staticFile.OutputPath);
                if (staticFile.ShouldOverWrite != OverWriteCondition.Never || !_fileSystem.FileExists(outputPath))
                {
                    // We never overwrite some files like _ViewImports.cshtml.
                    _logger.LogMessage($"Adding static file: {staticFile.Name}", LogMessageLevel.Trace);

                    await _codegeneratorActionService.AddFileAsync(
                        outputPath,
                        Path.Combine(TemplateFolderRoot, staticFile.SourcePath)
                        );
                }
            }
        }
コード例 #9
0
        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);
        }
コード例 #10
0
        private void ShowFileList(IdentityGeneratorTemplateModel templateModel)
        {
            _logger.LogMessage("File List:");

            string contentVersion;

            // For back-compat
            if (templateModel is IdentityGeneratorTemplateModel2 templateModel2)
            {
                contentVersion = templateModel2.ContentVersion;
            }
            else
            {
                contentVersion = ContentVersionDefault;
            }

            var files = IdentityGeneratorFilesConfig.GetFilesToList(contentVersion);

            _logger.LogMessage(string.Join(Environment.NewLine, files));
        }
コード例 #11
0
        public static Dictionary <string, string> GetTemplateFiles(IdentityGeneratorTemplateModel templateModel)
        {
            if (templateModel == null)
            {
                throw new ArgumentNullException(nameof(templateModel));
            }

            var templates = new Dictionary <string, string>(Templates);

            if (!templateModel.IsUsingExistingDbContext)
            {
                templates.Add("ApplicationDbContext.cshtml", Path.Combine("Areas", "Identity", "Data", $"{templateModel.DbContextClass}.cs"));

                if (templateModel.IsGenerateCustomUser)
                {
                    templates.Add("ApplicationUser.cshtml", Path.Combine("Areas", "Identity", "Data", $"{templateModel.UserClass}.cs"));
                }
            }

            return(templates);
        }
コード例 #12
0
        // Returns the root directory of the template folders appropriate for templateModel.ContentVersion
        private string GetTemplateFolderRootForContentVersion(IdentityGeneratorTemplateModel templateModel)
        {
            string relativePath = null;

            if (templateModel is IdentityGeneratorTemplateModel2 templateModel2)
            {
                if (string.Equals(templateModel2.ContentVersion, ContentVersionDefault, StringComparison.Ordinal))
                {
                    relativePath = DefaultContentRelativeBaseDir;
                }
                else if (string.Equals(templateModel2.ContentVersion, ContentVersionBootstrap3, StringComparison.Ordinal))
                {
                    // Note: In the future, if content gets pivoted on things other than bootstrap, this logic will need enhancement.
                    relativePath = Path.Combine(VersionedContentRelativeBaseDir, $"Bootstrap{templateModel2.BootstrapVersion}");
                }

                if (string.IsNullOrEmpty(relativePath))
                {
                    // This should get caught by IdentityGeneratorTemplateModelBuilder.ValidateCommandLine() and emit the same error.
                    // But best to be safe here.
                    // Note: If we start pivoting content on things other than bootstrap version, this error message will need to be reworked.
                    throw new InvalidOperationException(string.Format(MessageStrings.InvalidBootstrapVersionForScaffolding, templateModel2.BootstrapVersion, string.Join(", ", ValidBootstrapVersions)));
                }
            }
            else
            {
                relativePath = DefaultContentRelativeBaseDir;
            }

            return(TemplateFoldersUtilities.GetTemplateFolders(
                       Constants.ThisAssemblyName,
                       _applicationInfo.ApplicationBasePath,
                       new[] {
                relativePath
            },
                       _projectContext
                       ).First());
        }
コード例 #13
0
 // Returns a string indicating which Identity content to use.
 // Currently only pivots on the bootstrap version, but could pivot on anything.
 private string DetermineContentVersion(IdentityGeneratorTemplateModel templateModel)
 {
     if (templateModel is IdentityGeneratorTemplateModel2 templateModel2)
     {
         if (string.Equals(templateModel2.BootstrapVersion, IdentityGenerator.DefaultBootstrapVersion, StringComparison.Ordinal))
         {
             return(IdentityGenerator.ContentVersionDefault);
         }
         else if (string.Equals(templateModel2.BootstrapVersion, "3", StringComparison.Ordinal))
         {
             return(IdentityGenerator.ContentVersionBootstrap3);
         }
         else
         {
             // This should get caught by ValidateCommandLine() and emit the same error.
             // But best to be safe here.
             throw new InvalidOperationException(string.Format(MessageStrings.InvalidBootstrapVersionForScaffolding, templateModel2.BootstrapVersion, string.Join(", ", IdentityGenerator.ValidBootstrapVersions)));
         }
     }
     else
     {
         return(IdentityGenerator.ContentVersionDefault);
     }
 }
コード例 #14
0
        internal static IdentityGeneratorFile[] GetFilesToGenerate(IEnumerable <string> names, IdentityGeneratorTemplateModel templateModel)
        {
            if (templateModel == null)
            {
                throw new ArgumentNullException(nameof(templateModel));
            }

            List <IdentityGeneratorFile> filesToGenerate = GetDataModelFiles(templateModel);

            if (templateModel.GenerateLayout)
            {
                filesToGenerate.Add(Layout);
            }

            if (!string.IsNullOrEmpty(templateModel.Layout))
            {
                filesToGenerate.Add(ViewStart);
            }

            if (!templateModel.UseDefaultUI)
            {
                if (names != null && names.Any())
                {
                    foreach (var name in names)
                    {
                        filesToGenerate.AddRange(_config.NamedFileConfig[name]);
                    }
                }
                else
                {
                    filesToGenerate.AddRange(_config.NamedFileConfig.SelectMany(f => f.Value));
                }
            }

            filesToGenerate.Add(IdentityHostingStartup);
            filesToGenerate.Add(ReadMe);

            return(filesToGenerate.Distinct(new IdentityGeneratorFileComparer()).ToArray());
        }
コード例 #15
0
        public async Task <IdentityGeneratorTemplateModel> ValidateAndBuild()
        {
            ValidateCommandLine(_commandlineModel);
            RootNamespace = string.IsNullOrEmpty(_commandlineModel.RootNamespace)
                ? _projectContext.RootNamespace
                : _commandlineModel.RootNamespace;

            ValidateRequiredDependencies(_commandlineModel.UseSQLite);

            var defaultDbContextNamespace = $"{RootNamespace}.Areas.Identity.Data";

            IsUsingExistingDbContext = false;
            if (IsDbContextSpecified)
            {
                var existingDbContext = await FindExistingType(_commandlineModel.DbContext);

                if (existingDbContext == null)
                {
                    // We need to create one with what the user specified.
                    DbContextClass     = GetClassNameFromTypeName(_commandlineModel.DbContext);
                    DbContextNamespace = GetNamespaceFromTypeName(_commandlineModel.DbContext)
                                         ?? defaultDbContextNamespace;
                }
                else
                {
                    ValidateExistingDbContext(existingDbContext);
                    IsGenerateCustomUser     = false;
                    IsUsingExistingDbContext = true;
                    UserType           = FindUserTypeFromDbContext(existingDbContext);
                    DbContextClass     = existingDbContext.Name;
                    DbContextNamespace = existingDbContext.Namespace;
                }
            }
            else
            {
                // --dbContext paramter was not specified. So we need to generate one using convention.
                DbContextClass     = GetDefaultDbContextName();
                DbContextNamespace = defaultDbContextNamespace;
            }

            // if an existing user class was determined from the DbContext, don't try to get it from here.
            // Identity scaffolding must use the user class tied to the existing DbContext (when there is one).
            if (string.IsNullOrEmpty(UserClass))
            {
                if (string.IsNullOrEmpty(_commandlineModel.UserClass))
                {
                    IsGenerateCustomUser = false;
                    UserClass            = "IdentityUser";
                    UserClassNamespace   = "Microsoft.AspNetCore.Identity";
                }
                else
                {
                    var existingUser = await FindExistingType(_commandlineModel.UserClass);

                    if (existingUser != null)
                    {
                        ValidateExistingUserType(existingUser);
                        IsGenerateCustomUser = false;
                        UserType             = existingUser;
                    }
                    else
                    {
                        IsGenerateCustomUser = true;
                        UserClass            = GetClassNameFromTypeName(_commandlineModel.UserClass);
                        UserClassNamespace   = GetNamespaceFromTypeName(_commandlineModel.UserClass)
                                               ?? defaultDbContextNamespace;
                    }
                }
            }

            if (_commandlineModel.UseDefaultUI)
            {
                ValidateDefaultUIOption();
            }

            if (IsFilesSpecified)
            {
                ValidateFilesOption();
            }

            bool hasExistingLayout = DetermineSupportFileLocation(out string supportFileLocation, out string layout);

            var templateModel = new IdentityGeneratorTemplateModel()
            {
                ApplicationName             = _applicationInfo.ApplicationName,
                DbContextClass              = DbContextClass,
                DbContextNamespace          = DbContextNamespace,
                UserClass                   = UserClass,
                UserClassNamespace          = UserClassNamespace,
                UseSQLite                   = _commandlineModel.UseSQLite,
                IsUsingExistingDbContext    = IsUsingExistingDbContext,
                Namespace                   = RootNamespace,
                IsGenerateCustomUser        = IsGenerateCustomUser,
                IsGeneratingIndividualFiles = IsFilesSpecified,
                UseDefaultUI                = _commandlineModel.UseDefaultUI,
                GenerateLayout              = !hasExistingLayout,
                Layout = layout,
                LayoutPageNoExtension      = Path.GetFileNameWithoutExtension(layout),
                SupportFileLocation        = supportFileLocation,
                HasExistingNonEmptyWwwRoot = HasExistingNonEmptyWwwRootDirectory
            };

            var filesToGenerate = new List <IdentityGeneratorFile>(IdentityGeneratorFilesConfig.GetFilesToGenerate(NamedFiles, templateModel));

            // Check if we need to add ViewImports and which ones.
            if (!_commandlineModel.UseDefaultUI)
            {
                filesToGenerate.AddRange(IdentityGeneratorFilesConfig.GetViewImports(filesToGenerate, _fileSystem, _applicationInfo.ApplicationBasePath));
            }

            if (IdentityGeneratorFilesConfig.TryGetLayoutPeerFiles(_fileSystem, _applicationInfo.ApplicationBasePath, templateModel, out IReadOnlyList <IdentityGeneratorFile> layoutPeerFiles))
            {
                filesToGenerate.AddRange(layoutPeerFiles);
            }

            if (IdentityGeneratorFilesConfig.TryGetCookieConsentPartialFile(_fileSystem, _applicationInfo.ApplicationBasePath, templateModel, out IdentityGeneratorFile cookieConsentPartialConfig))
            {
                filesToGenerate.Add(cookieConsentPartialConfig);
            }

            templateModel.FilesToGenerate = filesToGenerate.ToArray();

            ValidateFilesToGenerate(templateModel.FilesToGenerate);

            return(templateModel);
        }
コード例 #16
0
        // Note: "peer" is somewhat of a misnomer, not all of the "peer" files are in the same directory as the layout file.
        internal static bool TryGetLayoutPeerFiles(IFileSystem fileSystem, string rootPath, IdentityGeneratorTemplateModel templateModel, out IReadOnlyList <IdentityGeneratorFile> layoutPeerFiles)
        {
            string viewImportsFileNameWithExtension = string.Concat(_ViewImportFileName, ".cshtml");

            if (fileSystem.FileExists(Path.Combine(rootPath, templateModel.SupportFileLocation, viewImportsFileNameWithExtension)))
            {
                layoutPeerFiles = null;
                return(false);
            }

            const string sharedDirName = "Shared";
            string       outputDirectory;

            string checkSupportFileLocation = templateModel.SupportFileLocation;

            if (checkSupportFileLocation.EndsWith("\\") || checkSupportFileLocation.EndsWith("/"))
            {
                checkSupportFileLocation = checkSupportFileLocation.Substring(0, checkSupportFileLocation.Length - 1);
            }

            //if (templateModel.SupportFileLocation.EndsWith(sharedDirName))
            //{
            //    int directoryLengthWithoutShared = templateModel.SupportFileLocation.Length - sharedDirName.Length;
            //    outputDirectory = templateModel.SupportFileLocation.Substring(0, directoryLengthWithoutShared);
            //}

            if (checkSupportFileLocation.EndsWith(sharedDirName))
            {
                int directoryLengthWithoutShared = checkSupportFileLocation.Length - sharedDirName.Length;
                outputDirectory = checkSupportFileLocation.Substring(0, directoryLengthWithoutShared);
            }
            else
            {
                outputDirectory = templateModel.SupportFileLocation;
            }

            List <IdentityGeneratorFile> peerFiles = new List <IdentityGeneratorFile>();

            IdentityGeneratorFile layoutPeerViewImportsFile = new IdentityGeneratorFile()
            {
                Name            = "_ViewImports",
                SourcePath      = "SupportPages._ViewImports.cshtml",
                OutputPath      = Path.Combine(outputDirectory, viewImportsFileNameWithExtension),
                IsTemplate      = true,
                ShouldOverWrite = OverWriteCondition.Never
            };

            peerFiles.Add(layoutPeerViewImportsFile);

            IdentityGeneratorFile layoutPeerViewStart = new IdentityGeneratorFile()
            {
                Name            = "_ViewStart",
                SourcePath      = "SupportPages._ViewStart.cshtml",
                OutputPath      = Path.Combine(outputDirectory, "_ViewStart.cshtml"),
                IsTemplate      = true,
                ShowInListFiles = false,
                ShouldOverWrite = OverWriteCondition.Never
            };

            peerFiles.Add(layoutPeerViewStart);

            layoutPeerFiles = peerFiles;
            return(true);
        }
コード例 #17
0
        // Look for a cookie consent file in the same location as the layout file. If there isn't one, setup the config to add one there.
        internal static bool TryGetCookieConsentPartialFile(IFileSystem fileSystem, string rootPath, IdentityGeneratorTemplateModel templateModel, out IdentityGeneratorFile cookieConsentPartialConfig)
        {
            string layoutDir = Path.GetDirectoryName(templateModel.Layout);

            string cookieConsentCheckLocation = Path.Combine(layoutDir, _CookieConsentPartialFileName);

            if (fileSystem.FileExists(cookieConsentCheckLocation))
            {
                cookieConsentPartialConfig = null;
                return(false);
            }

            cookieConsentPartialConfig = new IdentityGeneratorFile()
            {
                Name            = "_CookieConsentPartial",
                SourcePath      = "SupportPages._CookieConsentPartial.cshtml",
                OutputPath      = Path.Combine(layoutDir, _CookieConsentPartialFileName),
                IsTemplate      = false,
                ShowInListFiles = false,
                ShouldOverWrite = OverWriteCondition.Never
            };
            return(true);
        }
コード例 #18
0
        internal static IdentityGeneratorFile[] GetFilesToGenerate(IEnumerable <string> names, IdentityGeneratorTemplateModel templateModel)
        {
            if (templateModel == null)
            {
                throw new ArgumentNullException(nameof(templateModel));
            }

            List <IdentityGeneratorFile> filesToGenerate = GetDataModelFiles(templateModel);

            if (templateModel.GenerateLayout)
            {
                IdentityGeneratorFile layout = new IdentityGeneratorFile()
                {
                    Name            = "_Layout",
                    SourcePath      = "_Layout.cshtml",
                    OutputPath      = Path.Combine(templateModel.SupportFileLocation, "_Layout.cshtml"),
                    IsTemplate      = true,
                    ShowInListFiles = false
                };
                filesToGenerate.Add(layout);
            }
            else
            {
                IdentityGeneratorFile validationScriptsPartial = new IdentityGeneratorFile()
                {
                    Name            = "_ValidationScriptsPartial",
                    SourcePath      = "Pages/_ValidationScriptsPartial.cshtml",
                    OutputPath      = "Areas/Identity/Pages/_ValidationScriptsPartial.cshtml",
                    IsTemplate      = false,
                    ShouldOverWrite = OverWriteCondition.Never
                };
                filesToGenerate.Add(validationScriptsPartial);
            }

            if (!string.IsNullOrEmpty(templateModel.Layout))
            {
                filesToGenerate.Add(ViewStart);

                // if there's a layout file, generate a _ValidationScriptsPartial.cshtml in the same place.
                IdentityGeneratorFile layoutPeerValidationScriptsPartial = new IdentityGeneratorFile()
                {
                    Name            = "_ValidationScriptsPartial",
                    SourcePath      = "Pages/_ValidationScriptsPartial.cshtml",
                    OutputPath      = Path.Combine(templateModel.SupportFileLocation, "_ValidationScriptsPartial.cshtml"),
                    IsTemplate      = false,
                    ShouldOverWrite = OverWriteCondition.Never
                };
                filesToGenerate.Add(layoutPeerValidationScriptsPartial);
            }

            if (!templateModel.UseDefaultUI)
            {
                if (names != null && names.Any())
                {
                    foreach (var name in names)
                    {
                        filesToGenerate.AddRange(_config.NamedFileConfig[name]);
                    }
                }
                else
                {
                    filesToGenerate.AddRange(_config.NamedFileConfig.SelectMany(f => f.Value));
                }
            }

            if (!templateModel.HasExistingNonEmptyWwwRoot)
            {
                filesToGenerate.AddRange(_config.NamedFileConfig["WwwRoot"]);
            }

            filesToGenerate.Add(IdentityHostingStartup);
            filesToGenerate.Add(ReadMe);

            return(filesToGenerate.Distinct(new IdentityGeneratorFileComparer()).ToArray());
        }
        public async Task <IdentityGeneratorTemplateModel> ValidateAndBuild()
        {
            ValidateCommandLine(_commandlineModel);
            RootNamespace = string.IsNullOrEmpty(_commandlineModel.RootNamespace)
                ? _projectContext.RootNamespace
                : _commandlineModel.RootNamespace;

            ValidateRequiredDependencies(_commandlineModel.UseSQLite);

            var defaultDbContextNamespace = $"{RootNamespace}.Areas.Identity.Data";

            IsUsingExistingDbContext = false;
            if (IsDbContextSpecified)
            {
                var existingDbContext = await FindExistingType(_commandlineModel.DbContext);

                if (existingDbContext == null)
                {
                    // We need to create one with what the user specified.
                    DbContextClass     = GetClassNameFromTypeName(_commandlineModel.DbContext);
                    DbContextNamespace = GetNamespaceFromTypeName(_commandlineModel.DbContext)
                                         ?? defaultDbContextNamespace;
                }
                else
                {
                    ValidateExistingDbContext(existingDbContext);
                    IsGenerateCustomUser     = false;
                    IsUsingExistingDbContext = true;
                    UserType           = FindUserTypeFromDbContext(existingDbContext);
                    DbContextClass     = existingDbContext.Name;
                    DbContextNamespace = existingDbContext.Namespace;
                }
            }
            else
            {
                // --dbContext paramter was not specified. So we need to generate one using convention.
                DbContextClass     = GetDefaultDbContextName();
                DbContextNamespace = defaultDbContextNamespace;
            }

            if (string.IsNullOrEmpty(_commandlineModel.UserClass))
            {
                IsGenerateCustomUser = false;
                UserClass            = "IdentityUser";
                UserClassNamespace   = "Microsoft.AspNetCore.Identity";
            }
            else
            {
                var existingUser = await FindExistingType(_commandlineModel.UserClass);

                if (existingUser != null)
                {
                    ValidateExistingUserType(existingUser);
                    IsGenerateCustomUser = false;
                    UserType             = existingUser;
                }
                else
                {
                    IsGenerateCustomUser = true;
                    UserClass            = GetClassNameFromTypeName(_commandlineModel.UserClass);
                    UserClassNamespace   = GetNamespaceFromTypeName(_commandlineModel.UserClass)
                                           ?? defaultDbContextNamespace;
                }
            }

            if (_commandlineModel.UseDefaultUI)
            {
                ValidateDefaultUIOption();
            }

            if (IsFilesSpecified)
            {
                ValidateFilesOption();
            }

            var layout = _commandlineModel.Layout;

            if (_commandlineModel.GenerateLayout)
            {
                layout = "~/Pages/Shared/_Layout.chstml";
            }


            var templateModel = new IdentityGeneratorTemplateModel()
            {
                ApplicationName             = _applicationInfo.ApplicationName,
                DbContextClass              = DbContextClass,
                DbContextNamespace          = DbContextNamespace,
                UserClass                   = UserClass,
                UserClassNamespace          = UserClassNamespace,
                UseSQLite                   = _commandlineModel.UseSQLite,
                IsUsingExistingDbContext    = IsUsingExistingDbContext,
                Namespace                   = RootNamespace,
                IsGenerateCustomUser        = IsGenerateCustomUser,
                IsGeneratingIndividualFiles = IsFilesSpecified,
                UseDefaultUI                = _commandlineModel.UseDefaultUI,
                GenerateLayout              = _commandlineModel.GenerateLayout,
                Layout = layout
            };

            var filesToGenerate = new List <IdentityGeneratorFile>(IdentityGeneratorFilesConfig.GetFilesToGenerate(NamedFiles, templateModel));

            // Check if we need to add ViewImports and which ones.
            if (!_commandlineModel.UseDefaultUI)
            {
                filesToGenerate.AddRange(IdentityGeneratorFilesConfig.GetViewImports(filesToGenerate, _fileSystem, _applicationInfo.ApplicationBasePath));
            }

            templateModel.FilesToGenerate = filesToGenerate.ToArray();

            ValidateFilesToGenerate(templateModel.FilesToGenerate);

            return(templateModel);
        }
コード例 #20
0
        public async Task <IdentityGeneratorTemplateModel> ValidateAndBuild()
        {
            ValidateCommandLine(_commandlineModel);
            RootNamespace = string.IsNullOrEmpty(_commandlineModel.RootNamespace)
                ? _projectContext.RootNamespace
                : _commandlineModel.RootNamespace;

            var defaultDbContextNamespace = $"{RootNamespace}.Areas.Identity.Data";

            if (string.IsNullOrEmpty(_commandlineModel.UserClass))
            {
                IsGenerateCustomUser = false;
                UserClass            = "IdentityUser";
                UserClassNamespace   = "Microsoft.AspNetCore.Identity";
            }
            else
            {
                IsGenerateCustomUser = true;
                UserClass            = _commandlineModel.UserClass;
                UserClassNamespace   = defaultDbContextNamespace;
            }

            var usingExistingDbContext = false;

            if (IsDbContextSpecified)
            {
                var existingDbContext = await FindExistingType(_commandlineModel.DbContext);

                if (existingDbContext == null)
                {
                    // We need to create one with what the user specified.
                    DbContextClass     = GetClassNameFromTypeName(_commandlineModel.DbContext);
                    DbContextNamespace = GetNamespaceFromTypeName(_commandlineModel.DbContext)
                                         ?? defaultDbContextNamespace;
                }
                else
                {
                    ValidateExistingDbContext(existingDbContext);
                    IsGenerateCustomUser   = false;
                    usingExistingDbContext = true;
                    UserType           = FindUserTypeFromDbContext(existingDbContext);
                    DbContextClass     = existingDbContext.Name;
                    DbContextNamespace = existingDbContext.Namespace;
                }
            }
            else
            {
                // --dbContext paramter was not specified. So we need to generate one using convention.
                DbContextClass     = GetDfaultDbContextName();
                DbContextNamespace = defaultDbContextNamespace;
            }

            var templateModel = new IdentityGeneratorTemplateModel()
            {
                ApplicationName          = _applicationInfo.ApplicationName,
                DbContextClass           = DbContextClass,
                DbContextNamespace       = DbContextNamespace,
                UserClass                = UserClass,
                UserClassNamespace       = UserClassNamespace,
                UseSQLite                = _commandlineModel.UseSQLite,
                IsUsingExistingDbContext = usingExistingDbContext,
                Namespace                = RootNamespace,
                IsGenerateCustomUser     = IsGenerateCustomUser
            };

            return(templateModel);
        }