public void GenerateServerDgmlFiles()
        {
            try
            {
                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                // Show dialog with SqlClient selected by default
                var dialogFactory = _package.GetService <IVsDataConnectionDialogFactory>();
                var dialog        = dialogFactory.CreateConnectionDialog();
                dialog.AddAllSources();
                dialog.SelectedSource = new Guid("067ea0d9-ba62-43f7-9106-34930c60c528");
                var dialogResult = dialog.ShowDialog(connect: true);

                if (dialogResult == null)
                {
                    return;
                }

                _package.Dte2.StatusBar.Text = "Loading schema information...";

                var dbInfo = GetDatabaseInfo(dialogResult, DataProtection.DecryptString(dialog.EncryptedConnectionString));

                if (dbInfo.DatabaseType == DatabaseType.SQLCE35)
                {
                    EnvDteHelper.ShowError($"Unsupported provider: {dbInfo.ServerVersion}");
                    return;
                }

                var ptd = new PickTablesDialog();
                using (var repository = RepositoryHelper.CreateRepository(dbInfo))
                {
                    ptd.Tables = repository.GetAllTableNamesForExclusion();
                }

                var res = ptd.ShowModal();
                if (!res.HasValue || !res.Value)
                {
                    return;
                }

                var path = Path.GetTempFileName() + ".dgml";

                using (var repository = RepositoryHelper.CreateRepository(dbInfo))
                {
                    var generator = RepositoryHelper.CreateGenerator(repository, path, dbInfo.DatabaseType);
                    generator.GenerateSchemaGraph(dbInfo.ConnectionString, ptd.Tables);
                    _package.Dte2.ItemOperations.OpenFile(path);
                    _package.Dte2.ActiveDocument.Activate();
                }
            }
            catch (Exception ex)
            {
                _package.LogError(new List <string>(), ex);
            }
        }
        public void GenerateServerDgmlFiles()
        {
            try
            {
                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                var databaseList = EnvDteHelper.GetDataConnections(_package);

                var psd     = new PickServerDatabaseDialog(databaseList, _package);
                var diagRes = psd.ShowModal();
                if (!diagRes.HasValue || !diagRes.Value)
                {
                    return;
                }

                _package.Dte2.StatusBar.Text = "Loading schema information...";

                var dbInfo = psd.SelectedDatabase.Value;

                if (dbInfo.DatabaseType == DatabaseType.SQLCE35)
                {
                    EnvDteHelper.ShowError($"Unsupported provider: {dbInfo.ServerVersion}");
                    return;
                }

                var ptd = new PickTablesDialog();
                using (var repository = RepositoryHelper.CreateRepository(dbInfo))
                {
                    ptd.Tables = repository.GetAllTableNamesForExclusion();
                }

                var res = ptd.ShowModal();
                if (!res.HasValue || !res.Value)
                {
                    return;
                }

                var path = Path.GetTempFileName() + ".dgml";

                using (var repository = RepositoryHelper.CreateRepository(dbInfo))
                {
                    var generator = RepositoryHelper.CreateGenerator(repository, path, dbInfo.DatabaseType);
                    generator.GenerateSchemaGraph(dbInfo.ConnectionString, ptd.Tables);
                    _package.Dte2.ItemOperations.OpenFile(path);
                    _package.Dte2.ActiveDocument.Activate();
                }
                Telemetry.TrackEvent("PowerTools.GenerateSchemaDgml");
            }
            catch (Exception ex)
            {
                _package.LogError(new List <string>(), ex);
            }
        }
        public async System.Threading.Tasks.Task ManageMigrationsAsync(string outputPath, Project project)
        {
            try
            {
                if (string.IsNullOrEmpty(outputPath))
                {
                    throw new ArgumentException(outputPath, nameof(outputPath));
                }

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

                if (project.Properties.Item("TargetFrameworkMoniker") == null)
                {
                    EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker");
                    return;
                }

                if (!project.IsNetCore30OrHigher())
                {
                    EnvDteHelper.ShowError("Only .NET Core 3.0+ projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                    return;
                }

                var outputFolder = Path.GetDirectoryName(outputPath);

                var result = await project.ContainsEfCoreDesignReferenceAsync();

                if (string.IsNullOrEmpty(result.Item2))
                {
                    EnvDteHelper.ShowError("EF Core 3.1 or later not found in project");
                    return;
                }

                if (!result.Item1)
                {
                    if (!Version.TryParse(result.Item2, out Version version))
                    {
                        EnvDteHelper.ShowError($"Cannot support version {version}, notice that previews are not supported.");
                        return;
                    }
                    var nugetHelper = new NuGetHelper();
                    nugetHelper.InstallPackage("Microsoft.EntityFrameworkCore.Design", project, version);
                    EnvDteHelper.ShowError($"Installing EFCore.Design version {version}, please retry the command");
                    return;
                }

                var migrationsDialog = _package.GetView <IMigrationOptionsDialog>();
                migrationsDialog.UseProjectForMigration(project)
                .UseOutputPath(outputPath);

                migrationsDialog.ShowAndAwaitUserResponse(true);
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
        public async System.Threading.Tasks.Task ManageMigrationsAsync(string outputPath, Project project)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            try
            {
                if (string.IsNullOrEmpty(outputPath))
                {
                    throw new ArgumentException(outputPath, nameof(outputPath));
                }

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

                if (project.Properties.Item("TargetFrameworkMoniker") == null)
                {
                    EnvDteHelper.ShowError(SharedLocale.SelectedProjectTypeNoTargetFrameworkMoniker);
                    return;
                }

                if (!project.IsNetCore30OrHigher())
                {
                    EnvDteHelper.ShowError($"{SharedLocale.SupportedFramework}: {project.Properties.Item("TargetFrameworkMoniker").Value}");
                    return;
                }

                var result = await project.ContainsEfCoreDesignReferenceAsync();

                if (string.IsNullOrEmpty(result.Item2))
                {
                    EnvDteHelper.ShowError(SharedLocale.EFCoreVersionNotFound);
                    return;
                }

                if (!result.Item1)
                {
                    if (!Version.TryParse(result.Item2, out Version version))
                    {
                        EnvDteHelper.ShowError(string.Format(MigrationsLocale.CannotSupportVersion, version));
                        return;
                    }
                    var nugetHelper = new NuGetHelper();
                    nugetHelper.InstallPackage("Microsoft.EntityFrameworkCore.Design", project, version);
                    EnvDteHelper.ShowError(string.Format(SharedLocale.InstallingEfCoreDesignPackage, version));
                    return;
                }

                var migrationsDialog = _package.GetView <IMigrationOptionsDialog>();
                migrationsDialog.UseProjectForMigration(project)
                .UseOutputPath(outputPath);

                migrationsDialog.ShowAndAwaitUserResponse(true);
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
 public void GenerateDebugView(dynamic contextType)
 {
     try
     {
         var modelText = _modelAnalyzer.GenerateDebugView(contextType);
         var path      = Path.GetTempFileName() + ".txt";
         File.WriteAllText(path, modelText, Encoding.UTF8);
         File.SetAttributes(path, FileAttributes.ReadOnly);
         var window = _package.Dte2.ItemOperations.OpenFile(path);
         window.Document.Activate();
     }
     catch (Exception exception)
     {
         _package.LogError(new List <string>(), exception);
     }
 }
        public void Generate(string outputPath, Project project, GenerationType generationType)
        {
            try
            {
                if (string.IsNullOrEmpty(outputPath))
                {
                    throw new ArgumentException(outputPath, nameof(outputPath));
                }

                if (project.Properties.Item("TargetFrameworkMoniker") == null)
                {
                    EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker");
                    return;
                }

                if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework") &&
                    !project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2.0"))
                {
                    EnvDteHelper.ShowError("Currently only .NET Framework and .NET Core 2.0 projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                    return;
                }

                bool isNetCore = project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2.0");

                var processResult = _processLauncher.GetOutput(outputPath, isNetCore, generationType);

                if (processResult.StartsWith("Error:"))
                {
                    throw new ArgumentException(processResult, nameof(processResult));
                }

                switch (generationType)
                {
                case GenerationType.Dgml:
                    GenerateDgml(processResult, project);
                    Telemetry.TrackEvent("PowerTools.GenerateModelDgml");
                    break;

                case GenerationType.Ddl:
                    GenerateFiles(processResult, project, ".sql");
                    Telemetry.TrackEvent("PowerTools.GenerateSqlCreate");
                    break;

                case GenerationType.DebugView:
                    GenerateFiles(processResult, project, ".txt");
                    Telemetry.TrackEvent("PowerTools.GenerateDebugView");
                    break;

                default:
                    break;
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
Beispiel #7
0
 public void ShowDialog()
 {
     try
     {
         var dialog = new AboutDialog(_package);
         dialog.ShowDialog();
     }
     catch (Exception exception)
     {
         _package.LogError(new List <string>(), exception);
     }
 }
 public void ShowDialog()
 {
     try
     {
         var dialog = _package.GetView <IAboutDialog>();
         dialog.ShowAndAwaitUserResponse(false);
         Telemetry.TrackEvent("PowerTools.About");
     }
     catch (Exception exception)
     {
         _package.LogError(new List <string>(), exception);
     }
 }
Beispiel #9
0
 public void ShowDialog()
 {
     try
     {
         var dialog = new AboutDialog(_package);
         dialog.ShowDialog();
         Telemetry.TrackEvent("PowerTools.About");
     }
     catch (Exception exception)
     {
         _package.LogError(new List <string>(), exception);
     }
 }
        public void ManageMigrations(string outputPath, Project project)
        {
            try
            {
                if (string.IsNullOrEmpty(outputPath))
                {
                    throw new ArgumentException(outputPath, nameof(outputPath));
                }

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

                if (project.Properties.Item("TargetFrameworkMoniker") == null)
                {
                    EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker");
                    return;
                }

                if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework") &&
                    !project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2.0"))
                {
                    EnvDteHelper.ShowError("Currently only .NET Framework and .NET Core 2.0 projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                    return;
                }

                var outputFolder = Path.GetDirectoryName(outputPath);

                bool isNetCore = project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2.");

                if (!isNetCore && !File.Exists(Path.Combine(outputFolder, "Microsoft.EntityFrameworkCore.dll")))
                {
                    EnvDteHelper.ShowError("EF Core is not installed in the current project");
                    return;
                }

                var msd = new EfCoreMigrationsDialog(_package, outputPath, isNetCore, project)
                {
                    ProjectName = project.Name
                };

                msd.ShowModal();
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
Beispiel #11
0
        public void Generate(string outputPath, Project project, bool generateDdl = false)
        {
            try
            {
                if (project.Properties.Item("TargetFrameworkMoniker") == null)
                {
                    EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker");
                    return;
                }

                if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework") &&
                    !project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2.0"))
                {
                    EnvDteHelper.ShowError("Currently only .NET Framework and .NET Core 2.0 projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                    return;
                }

                bool isNetCore = project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2.0");

                var processResult = _processLauncher.GetOutput(outputPath, isNetCore, generateDdl);

                if (processResult.StartsWith("Error:"))
                {
                    throw new ArgumentException(processResult);
                }

                if (generateDdl)
                {
                    GenerateDatabaseScripts(processResult, project);
                    Telemetry.TrackEvent("PowerTools.GenerateSqlCreate");
                }
                else
                {
                    GenerateDgml(processResult, project);
                    Telemetry.TrackEvent("PowerTools.GenerateModelDgml");
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
        public async System.Threading.Tasks.Task ReverseEngineerCodeFirstAsync(Project project)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            try
            {
                if (await VSHelper.IsDebugModeAsync())
                {
                    VSHelper.ShowError(ReverseEngineerLocale.CannotGenerateCodeWhileDebugging);
                    return;
                }

                var projectPath  = project.FullPath;
                var optionsPaths = project.GetConfigFiles();
                var optionsPath  = optionsPaths.First();

                if (optionsPaths.Count > 1)
                {
                    var pcd = _package.GetView <IPickConfigDialog>();
                    pcd.PublishConfigurations(optionsPaths.Select(m => new ConfigModel
                    {
                        ConfigPath  = m,
                        ProjectPath = projectPath
                    }));

                    var pickConfigResult = pcd.ShowAndAwaitUserResponse(true);
                    if (!pickConfigResult.ClosedByOK)
                    {
                        return;
                    }

                    optionsPath = pickConfigResult.Payload.ConfigPath;
                }

                await ReverseEngineerCodeFirstAsync(project, optionsPath, false);
            }
            catch (AggregateException ae)
            {
                foreach (var innerException in ae.Flatten().InnerExceptions)
                {
                    _package.LogError(new List <string>(), innerException);
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
Beispiel #13
0
        public void ManageMigrations(string outputPath, Project project)
        {
            try
            {
                if (string.IsNullOrEmpty(outputPath))
                {
                    throw new ArgumentException(outputPath, nameof(outputPath));
                }

                if (project.Properties.Item("TargetFrameworkMoniker") == null)
                {
                    EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker");
                    return;
                }

                if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework") &&
                    !project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2.0"))
                {
                    EnvDteHelper.ShowError("Currently only .NET Framework and .NET Core 2.0 projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                    return;
                }

                bool isNetCore = project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2.");

                //TODO 3 different actions from dialog
                var processResult = _processLauncher.GetOutput(outputPath, isNetCore, GenerationType.MigrationStatus, null, null);

                if (processResult.StartsWith("Error:"))
                {
                    throw new ArgumentException(processResult, nameof(processResult));
                }

                //TODO Show status somewhere? - Dialog/ToolWindow ?
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
Beispiel #14
0
        public async void ReverseEngineerCodeFirst(Project project)
        {
            try
            {
                var    dteH         = new EnvDteHelper();
                var    revEng       = new EfCoreReverseEngineer();
                string dacpacSchema = null;

                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                var startTime   = DateTime.Now;
                var projectPath = project.Properties.Item("FullPath").Value.ToString();
                var optionsPath = Path.Combine(projectPath, "efpt.config.json");

                var databaseList = EnvDteHelper.GetDataConnections(_package);
                var dacpacList   = _package.Dte2.DTE.GetDacpacFilesInActiveSolution();

                var psd = new PickServerDatabaseDialog(databaseList, _package, dacpacList);
                if (psd.ShowModal() != true)
                {
                    return;
                }

                _package.Dte2.StatusBar.Text = "Loading schema information...";

                var dbInfo     = psd.SelectedDatabase.Value;
                var dacpacPath = psd.DacpacPath;

                if (dbInfo == null)
                {
                    dbInfo = new DatabaseInfo();
                }

                if (!string.IsNullOrEmpty(dacpacPath))
                {
                    dbInfo.DatabaseType     = DatabaseType.SQLServer;
                    dbInfo.ConnectionString = "Data Source=.;Initial Catalog=" + Path.GetFileNameWithoutExtension(dacpacPath);
                    dacpacPath = _package.Dte2.DTE.BuildSqlProj(dacpacPath);
                    if (string.IsNullOrEmpty(dacpacPath))
                    {
                        EnvDteHelper.ShowMessage("Unable to build selected Database Project");
                        return;
                    }
                }

                if (dbInfo.DatabaseType == DatabaseType.SQLCE35)
                {
                    EnvDteHelper.ShowError($"Unsupported provider: {dbInfo.ServerVersion}");
                    return;
                }

                var ptd = new PickTablesDialog {
                    IncludeTables = true
                };
                if (!string.IsNullOrEmpty(dacpacPath))
                {
                    ptd.Tables = revEng.GetDacpacTableNames(dacpacPath);
                }
                else
                {
                    ptd.Tables = GetTablesFromRepository(dbInfo);
                }
                var options = ReverseEngineerOptionsExtensions.TryRead(optionsPath);
                if (options != null)
                {
                    dacpacSchema = options.DefaultDacpacSchema;
                    if (options.Tables.Count > 0)
                    {
                        ptd.SelectedTables = options.Tables;
                    }
                }

                if (ptd.ShowModal() != true)
                {
                    return;
                }

                var classBasis = string.Empty;
                if (dbInfo.DatabaseType == DatabaseType.Npgsql)
                {
                    classBasis = EnvDteHelper.GetNpgsqlDatabaseName(dbInfo.ConnectionString);
                }
                else
                {
                    classBasis = RepositoryHelper.GetClassBasis(dbInfo.ConnectionString, dbInfo.DatabaseType);
                }
                var model         = revEng.GenerateClassName(classBasis) + "Context";
                var packageResult = project.ContainsEfCoreReference(dbInfo.DatabaseType);

                var modelDialog = new EfCoreModelDialog(options)
                {
                    InstallNuGetPackage = !packageResult.Item1,
                    ModelName           = options != null ? options.ContextClassName : model,
                    ProjectName         = project.Name,
                    NameSpace           = options != null ? options.ProjectRootNamespace : project.Properties.Item("DefaultNamespace").Value.ToString(),
                    DacpacPath          = dacpacPath
                };

                _package.Dte2.StatusBar.Text = "Getting options...";
                if (modelDialog.ShowModal() != true)
                {
                    return;
                }

                options = new ReverseEngineerOptions
                {
                    UseFluentApiOnly        = !modelDialog.UseDataAnnotations,
                    ConnectionString        = dbInfo.ConnectionString,
                    ContextClassName        = modelDialog.ModelName,
                    DatabaseType            = (ReverseEngineer20.DatabaseType)dbInfo.DatabaseType,
                    ProjectPath             = projectPath,
                    OutputPath              = modelDialog.OutputPath,
                    ProjectRootNamespace    = modelDialog.NameSpace,
                    UseDatabaseNames        = modelDialog.UseDatabaseNames,
                    UseInflector            = modelDialog.UsePluralizer,
                    IdReplace               = modelDialog.ReplaceId,
                    UseHandleBars           = modelDialog.UseHandelbars,
                    IncludeConnectionString = modelDialog.IncludeConnectionString,
                    SelectedToBeGenerated   = modelDialog.SelectedTobeGenerated,
                    Dacpac = dacpacPath,
                    DefaultDacpacSchema = dacpacSchema,
                    Tables = ptd.Tables
                };

                _package.Dte2.StatusBar.Text = "Generating code...";

                var  tfm           = project.Properties.Item("TargetFrameworkMoniker").Value.ToString();
                bool isNetCore     = tfm.Contains(".NETCoreApp,Version=v2.0");
                bool isNetStandard = tfm.Contains(".NETStandard,Version=v2.0");

                //TODO await update
                //if (modelDialog.UseHandelbars)
                //{
                //    var dropped = (DropTemplates(projectPath));
                //    if (dropped && !isNetCore && !isNetStandard)
                //    {
                //        project.ProjectItems.AddFromDirectory(Path.Combine(projectPath, "CodeTemplates"));
                //    }
                //}

                var revEngResult = revEng.GenerateFiles(options);

                if (modelDialog.SelectedTobeGenerated == 0 || modelDialog.SelectedTobeGenerated == 2)
                {
                    foreach (var filePath in revEngResult.EntityTypeFilePaths)
                    {
                        project.ProjectItems.AddFromFile(filePath);
                    }
                    if (modelDialog.SelectedTobeGenerated == 2)
                    {
                        if (File.Exists(revEngResult.ContextFilePath))
                        {
                            File.Delete(revEngResult.ContextFilePath);
                        }
                    }
                }
                if (modelDialog.SelectedTobeGenerated == 0 || modelDialog.SelectedTobeGenerated == 1)
                {
                    project.ProjectItems.AddFromFile(revEngResult.ContextFilePath);
                    if (!isNetCore && !isNetStandard)
                    {
                        _package.Dte2.ItemOperations.OpenFile(revEngResult.ContextFilePath);
                    }
                    if (modelDialog.SelectedTobeGenerated == 1)
                    {
                        foreach (var filePath in revEngResult.EntityTypeFilePaths)
                        {
                            if (File.Exists(filePath))
                            {
                                File.Delete(filePath);
                            }
                        }
                    }
                }

                var missingProviderPackage = packageResult.Item1 ? null : packageResult.Item2;
                if (modelDialog.InstallNuGetPackage)
                {
                    missingProviderPackage = null;
                }

                _package.Dte2.StatusBar.Text = "Reporting result...";
                var errors = ReportRevEngErrors(revEngResult, missingProviderPackage);

                SaveOptions(project, optionsPath, options);

                if (modelDialog.InstallNuGetPackage)
                {
                    _package.Dte2.StatusBar.Text = "Installing EF Core provider package";
                    var nuGetHelper = new NuGetHelper();
                    await nuGetHelper.InstallPackageAsync(packageResult.Item2, project);
                }
                var duration = DateTime.Now - startTime;
                _package.Dte2.StatusBar.Text = $"Reverse engineer completed in {duration:h\\:mm\\:ss}";

                EnvDteHelper.ShowMessage(errors);

                if (revEngResult.EntityErrors.Count > 0)
                {
                    _package.LogError(revEngResult.EntityErrors, null);
                }
                if (revEngResult.EntityWarnings.Count > 0)
                {
                    _package.LogError(revEngResult.EntityWarnings, null);
                }
                Telemetry.TrackEvent("PowerTools.ReverseEngineer");
            }
            catch (AggregateException ae)
            {
                foreach (var innerException in ae.Flatten().InnerExceptions)
                {
                    _package.LogError(new List <string>(), innerException);
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
Beispiel #15
0
        public void GenerateServerDgmlFiles()
        {
            try
            {
                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                var databaseList = EnvDteHelper.GetDataConnections(_package);

                var psd = _package.GetView <IPickServerDatabaseDialog>();
                psd.PublishConnections(databaseList.Select(m => new DatabaseConnectionModel
                {
                    ConnectionName   = m.Value.Caption,
                    ConnectionString = m.Value.ConnectionString,
                    DatabaseType     = m.Value.DatabaseType
                }));

                var pickDataSourceResult = psd.ShowAndAwaitUserResponse(true);
                if (!pickDataSourceResult.ClosedByOK)
                {
                    return;
                }

                _package.Dte2.StatusBar.Text = "Loading schema information...";

                // Reload the database list, in case the user has added a new database in the dialog
                databaseList = EnvDteHelper.GetDataConnections(_package);

                DatabaseInfo dbInfo = null;
                if (pickDataSourceResult.Payload.Connection != null)
                {
                    dbInfo = databaseList.Single(m => m.Value.ConnectionString == pickDataSourceResult.Payload.Connection?.ConnectionString).Value;
                }

                if (dbInfo == null)
                {
                    // User didn't select a database, should be impossible, though
                    return;
                }

                if (dbInfo.DatabaseType == DatabaseType.SQLCE35 ||
                    dbInfo.DatabaseType == DatabaseType.Mysql ||
                    dbInfo.DatabaseType == DatabaseType.Npgsql)
                {
                    EnvDteHelper.ShowError($"Unsupported provider: {dbInfo.ServerVersion}");
                    return;
                }

                var predefinedTables = new List <TableInformationModel>();
                using (var repository = RepositoryHelper.CreateRepository(dbInfo))
                {
                    var tables = repository.GetAllTableNamesForExclusion();
                    foreach (var table in tables)
                    {
                        predefinedTables.Add(new TableInformationModel(table, true, false));
                    }
                }

                var ptd = _package.GetView <IPickTablesDialog>()
                          .AddTables(predefinedTables);

                var(closedByOk, selectedTables) = ptd.ShowAndAwaitUserResponse(true);
                if (!closedByOk)
                {
                    return;
                }
                var unselectedTables = predefinedTables.Except(selectedTables).Select(m => m.Name).ToList();

                var name = RepositoryHelper.GetClassBasis(dbInfo.ConnectionString, dbInfo.DatabaseType);

                var path = Path.Combine(Path.GetTempPath(),
                                        name + ".schema.dgml");

                if (File.Exists(path))
                {
                    File.SetAttributes(path, FileAttributes.Normal);
                }

                using (var repository = RepositoryHelper.CreateRepository(dbInfo))
                {
                    var generator = RepositoryHelper.CreateGenerator(repository, path, dbInfo.DatabaseType);
                    generator.GenerateSchemaGraph(dbInfo.ConnectionString, unselectedTables);
                    File.SetAttributes(path, FileAttributes.ReadOnly);
                    _package.Dte2.ItemOperations.OpenFile(path);
                    _package.Dte2.ActiveDocument.Activate();
                }
                Telemetry.TrackEvent("PowerTools.GenerateSchemaDgml");
            }
            catch (Exception ex)
            {
                _package.LogError(new List <string>(), ex);
            }
        }
Beispiel #16
0
        public void GenerateDgml(string outputPath, Project project)
        {
            if (project.Properties.Item("TargetFrameworkMoniker") == null)
            {
                EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker");
                return;
            }

            if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework") &&
                !project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2.0"))
            {
                EnvDteHelper.ShowError("Currently only .NET Framework and .NET Core 2.0 projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                return;
            }

            bool isNetCore = project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2.0");

            var dgmlBuilder = new DgmlBuilder.DgmlBuilder();

            try
            {
                string launchPath;
                if (isNetCore)
                {
                    launchPath = DropNetCoreFiles(outputPath);
                }
                else
                {
                    launchPath = DropFiles(outputPath);
                }

                var modelInfo = LaunchProcess(outputPath, launchPath, isNetCore);

                if (modelInfo.StartsWith("Error:"))
                {
                    throw new ArgumentException(modelInfo);
                }

                var result = BuildModelInfo(modelInfo);

                ProjectItem item = null;

                foreach (var info in result)
                {
                    var dgmlText = dgmlBuilder.Build(info.Item2, info.Item1, GetTemplate());

                    var path = Path.GetTempPath() + info.Item1 + ".dgml";
                    File.WriteAllText(path, dgmlText, Encoding.UTF8);
                    item = project.ProjectItems.AddFromFileCopy(path);
                }

                if (item != null)
                {
                    var window = item.Open();
                    window.Document.Activate();
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
        internal Dictionary <string, DatabaseInfo> GetDataConnections(EFCorePowerToolsPackage package)
        {
            // http://www.mztools.com/articles/2007/MZ2007018.aspx
            Dictionary <string, DatabaseInfo> databaseList = new Dictionary <string, DatabaseInfo>();
            var  dataExplorerConnectionManager             = package.GetService <IVsDataExplorerConnectionManager>();
            Guid providerSqLite        = new Guid(EFCorePowerTools.Shared.Resources.SQLiteProvider);
            Guid providerSqlitePrivate = new Guid(EFCorePowerTools.Shared.Resources.SQLitePrivateProvider);
            Guid providerNpgsql        = new Guid(Resources.NpgsqlProvider);
            Guid providerMysql         = new Guid(Resources.MysqlVSProvider);
            Guid providerOracle        = new Guid(Resources.OracleProvider);

            if (dataExplorerConnectionManager?.Connections?.Values != null)
            {
                foreach (var connection in dataExplorerConnectionManager.Connections.Values)
                {
                    try
                    {
                        var sConnectionString = DataProtection.DecryptString(connection.EncryptedConnectionString);
                        var info = new DatabaseInfo()
                        {
                            Caption            = connection.DisplayName,
                            FromServerExplorer = true,
                            DatabaseType       = DatabaseType.SQLCE35,
                            ConnectionString   = sConnectionString,
                            DataConnection     = connection.Connection,
                        };

                        var objProviderGuid = connection.Provider;

                        if (objProviderGuid == providerSqLite ||
                            objProviderGuid == providerSqlitePrivate)
                        {
                            info.DatabaseType = DatabaseType.SQLite;
                        }
                        if (objProviderGuid == new Guid(Resources.SqlServerDotNetProvider) ||
                            objProviderGuid == providerNpgsql)
                        {
                            info.DatabaseType = objProviderGuid == providerNpgsql ? DatabaseType.Npgsql : DatabaseType.SQLServer;
                        }

                        // This provider depends on https://dev.mysql.com/downloads/windows/visualstudio/
                        if (objProviderGuid == providerMysql)
                        {
                            info.DatabaseType = DatabaseType.Mysql;
                        }

                        if (objProviderGuid == providerOracle)
                        {
                            info.DatabaseType = DatabaseType.Oracle;
                        }

                        if (info.DatabaseType != DatabaseType.SQLCE35 &&
                            !databaseList.ContainsKey(sConnectionString))
                        {
                            databaseList.Add(sConnectionString, info);
                        }
                    }
                    catch (Exception ex)
                    {
                        package.LogError(new List <string> {
                            ex.Message
                        }, ex);
                    }
                }
            }
            return(databaseList);
        }
        public async void ReverseEngineerCodeFirst(Project project)
        {
            try
            {
                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                var startTime = DateTime.Now;

                var databaseList = EnvDteHelper.GetDataConnections(_package);

                var psd     = new PickServerDatabaseDialog(databaseList, _package);
                var diagRes = psd.ShowModal();
                if (!diagRes.HasValue || !diagRes.Value)
                {
                    return;
                }

                // Show dialog with SqlClient selected by default
                _package.Dte2.StatusBar.Text = "Loading schema information...";

                var dbInfo = psd.SelectedDatabase.Value;

                if (dbInfo.DatabaseType == DatabaseType.SQLCE35)
                {
                    EnvDteHelper.ShowError($"Unsupported provider: {dbInfo.ServerVersion}");
                    return;
                }

                var ptd = new PickTablesDialog {
                    IncludeTables = true
                };
                using (var repository = RepositoryHelper.CreateRepository(dbInfo))
                {
                    ptd.Tables = repository.GetAllTableNamesForExclusion();
                }

                var res = ptd.ShowModal();
                if (!res.HasValue || !res.Value)
                {
                    return;
                }

                var classBasis = RepositoryHelper.GetClassBasis(dbInfo.ConnectionString, dbInfo.DatabaseType);

                var dteH   = new EnvDteHelper();
                var revEng = new EfCoreReverseEngineer();

                var model         = revEng.GenerateClassName(classBasis) + "Context";
                var packageResult = dteH.ContainsEfCoreReference(project, dbInfo.DatabaseType);

                var modelDialog = new EfCoreModelDialog
                {
                    InstallNuGetPackage = !packageResult.Item1,
                    ModelName           = model,
                    ProjectName         = project.Name,
                    NameSpace           = project.Properties.Item("DefaultNamespace").Value.ToString()
                };

                _package.Dte2.StatusBar.Text = "Getting options...";
                var result = modelDialog.ShowModal();
                if (!result.HasValue || result.Value != true)
                {
                    return;
                }

                var projectPath = project.Properties.Item("FullPath").Value.ToString();

                var options = new ReverseEngineerOptions
                {
                    UseFluentApiOnly     = !modelDialog.UseDataAnnotations,
                    ConnectionString     = dbInfo.ConnectionString,
                    ContextClassName     = modelDialog.ModelName,
                    DatabaseType         = (ReverseEngineer20.DatabaseType)dbInfo.DatabaseType,
                    ProjectPath          = projectPath,
                    OutputPath           = modelDialog.OutputPath,
                    ProjectRootNamespace = modelDialog.NameSpace,
                    UseDatabaseNames     = modelDialog.UseDatabaseNames,
                    UseInflector         = modelDialog.UsePluralizer,
                    IdReplace            = modelDialog.ReplaceId,
                    UseHandleBars        = modelDialog.UseHandelbars,
                    Tables = ptd.Tables
                };

                _package.Dte2.StatusBar.Text = "Generating code...";

                if (modelDialog.UseHandelbars)
                {
                    if (DropTemplates(projectPath))
                    {
                        project.ProjectItems.AddFromDirectory(Path.Combine(projectPath, "CodeTemplates"));
                    }
                }

                var revEngResult = revEng.GenerateFiles(options);

                if (modelDialog.SelectedTobeGenerated == 0 || modelDialog.SelectedTobeGenerated == 2)
                {
                    foreach (var filePath in revEngResult.EntityTypeFilePaths)
                    {
                        project.ProjectItems.AddFromFile(filePath);
                    }
                }
                if (modelDialog.SelectedTobeGenerated == 0 || modelDialog.SelectedTobeGenerated == 1)
                {
                    project.ProjectItems.AddFromFile(revEngResult.ContextFilePath);
                    _package.Dte2.ItemOperations.OpenFile(revEngResult.ContextFilePath);
                }

                packageResult = dteH.ContainsEfCoreReference(project, dbInfo.DatabaseType);

                var missingProviderPackage = packageResult.Item1 ? null : packageResult.Item2;
                if (modelDialog.InstallNuGetPackage)
                {
                    missingProviderPackage = null;
                }

                _package.Dte2.StatusBar.Text = "Reporting result...";
                var errors = ReportRevEngErrors(revEngResult, missingProviderPackage);

                if (modelDialog.InstallNuGetPackage)
                {
                    _package.Dte2.StatusBar.Text = "Installing EF Core provider package";
                    var nuGetHelper = new NuGetHelper();
                    await nuGetHelper.InstallPackageAsync(packageResult.Item2, project);
                }
                var duration = DateTime.Now - startTime;
                _package.Dte2.StatusBar.Text = $"Reverse engineer completed in {duration:h\\:mm\\:ss}";

                EnvDteHelper.ShowMessage(errors);

                if (revEngResult.EntityErrors.Count > 0)
                {
                    _package.LogError(revEngResult.EntityErrors, null);
                }
                if (revEngResult.EntityWarnings.Count > 0)
                {
                    _package.LogError(revEngResult.EntityWarnings, null);
                }
                Telemetry.TrackEvent("PowerTools.ReverseEngineer");
            }
            catch (AggregateException ae)
            {
                foreach (var innerException in ae.Flatten().InnerExceptions)
                {
                    _package.LogError(new List <string>(), innerException);
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
        public void ManageMigrations(string outputPath, Project project)
        {
            try
            {
                if (string.IsNullOrEmpty(outputPath))
                {
                    throw new ArgumentException(outputPath, nameof(outputPath));
                }

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

                if (project.Properties.Item("TargetFrameworkMoniker") == null)
                {
                    EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker");
                    return;
                }

                if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework") &&
                    !project.IsNetCore())
                {
                    EnvDteHelper.ShowError("Currently only .NET Framework and .NET Core 2.0 projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                    return;
                }

                var outputFolder = Path.GetDirectoryName(outputPath);

                if (!project.IsNetCore() && !File.Exists(Path.Combine(outputFolder, "Microsoft.EntityFrameworkCore.dll")))
                {
                    EnvDteHelper.ShowError("EF Core is not installed in the current project");
                    return;
                }

                if (project.IsNetCore())
                {
                    var result = project.ContainsEfCoreDesignReference();

                    if (string.IsNullOrEmpty(result.Item2))
                    {
                        EnvDteHelper.ShowError("EF Core 2.1 or 2.2 not found in project");
                        return;
                    }

                    if (!result.Item1)
                    {
                        var version     = new Version(result.Item2);
                        var nugetHelper = new NuGetHelper();
                        nugetHelper.InstallPackage("Microsoft.EntityFrameworkCore.Design", project, version);
                        EnvDteHelper.ShowError($"Installing EFCore.Design version {version}, please retry the command");
                        return;
                    }
                }

                var migrationsDialog = _package.GetView <IMigrationOptionsDialog>();
                migrationsDialog.UseProjectForMigration(project)
                .UseOutputPath(outputPath);

                migrationsDialog.ShowAndAwaitUserResponse(true);
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
Beispiel #20
0
        public void Generate(string outputPath, Project project, GenerationType generationType)
        {
            try
            {
                if (string.IsNullOrEmpty(outputPath))
                {
                    throw new ArgumentException(outputPath, nameof(outputPath));
                }

                if (project.Properties.Item("TargetFrameworkMoniker") == null)
                {
                    EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker");
                    return;
                }

                if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework") &&
                    !project.IsNetCore())
                {
                    EnvDteHelper.ShowError("Currently only .NET Framework and .NET Core 2.0 projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                    return;
                }

                if (project.IsNetCore())
                {
                    var result = project.ContainsEfCoreDesignReference();
                    if (string.IsNullOrEmpty(result.Item2))
                    {
                        EnvDteHelper.ShowError("EF Core 2.1 or 2.2 not found in project");
                        return;
                    }

                    if (!result.Item1)
                    {
                        var version     = new Version(result.Item2);
                        var nugetHelper = new NuGetHelper();
                        nugetHelper.InstallPackage("Microsoft.EntityFrameworkCore.Design", project, version);
                        EnvDteHelper.ShowError($"Installing EFCore.Design version {version}, please retry the command");
                        return;
                    }
                }

                var processLauncher = new ProcessLauncher(project);

                var processResult = processLauncher.GetOutput(outputPath, generationType, null);

                if (processResult.StartsWith("Error:"))
                {
                    throw new ArgumentException(processResult, nameof(processResult));
                }

                var modelResult = processLauncher.BuildModelResult(processResult);

                switch (generationType)
                {
                case GenerationType.Dgml:
                    GenerateDgml(processResult, project);
                    Telemetry.TrackEvent("PowerTools.GenerateModelDgml");
                    break;

                case GenerationType.Ddl:
                    var files = project.GenerateFiles(modelResult, ".sql");
                    foreach (var file in files)
                    {
                        _package.Dte2.ItemOperations.OpenFile(file);
                    }
                    Telemetry.TrackEvent("PowerTools.GenerateSqlCreate");
                    break;

                case GenerationType.DebugView:
                    var views = project.GenerateFiles(modelResult, ".txt");
                    foreach (var file in views)
                    {
                        _package.Dte2.ItemOperations.OpenFile(file);
                    }
                    Telemetry.TrackEvent("PowerTools.GenerateDebugView");
                    break;

                default:
                    break;
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
        public async System.Threading.Tasks.Task GenerateAsync(string outputPath, Project project, GenerationType generationType)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            try
            {
                if (string.IsNullOrEmpty(outputPath))
                {
                    throw new ArgumentException(outputPath, nameof(outputPath));
                }

                if (await project.GetAttributeAsync("TargetFrameworkMoniker") == null)
                {
                    VSHelper.ShowError(SharedLocale.SelectedProjectTypeNoTargetFrameworkMoniker);
                    return;
                }

                if (!await project.IsNetCore31OrHigherAsync())
                {
                    VSHelper.ShowError($"{SharedLocale.SupportedFramework}: {await project.GetAttributeAsync("TargetFrameworkMoniker")}");
                    return;
                }

                var result = await project.ContainsEfCoreDesignReferenceAsync();

                if (string.IsNullOrEmpty(result.Item2))
                {
                    VSHelper.ShowError(SharedLocale.EFCoreVersionNotFound);
                    return;
                }

                if (!Version.TryParse(result.Item2, out Version version))
                {
                    VSHelper.ShowError(string.Format(ModelAnalyzerLocale.CurrentEFCoreVersion, result.Item2));
                }

                if (!result.Item1)
                {
                    var nugetHelper = new NuGetHelper();
                    await nugetHelper.InstallPackageAsync("Microsoft.EntityFrameworkCore.Design", project, version);

                    VSHelper.ShowError(string.Format(SharedLocale.InstallingEfCoreDesignPackage, version));
                    return;
                }

                var processLauncher = new ProcessLauncher(project);

                var processResult = await processLauncher.GetOutputAsync(outputPath, generationType, null);

                if (string.IsNullOrEmpty(processResult))
                {
                    throw new ArgumentException(ModelAnalyzerLocale.UnableToCollectModelInformation, nameof(processResult));
                }

                if (processResult.Contains("Error:"))
                {
                    throw new ArgumentException(processResult, nameof(processResult));
                }

                var modelResult = processLauncher.BuildModelResult(processResult);

                switch (generationType)
                {
                case GenerationType.Dgml:
                    await GenerateDgmlAsync(modelResult, project);

                    Telemetry.TrackEvent("PowerTools.GenerateModelDgml");
                    break;

                case GenerationType.Ddl:
                    var files = project.GenerateFiles(modelResult, ".sql");
                    foreach (var file in files)
                    {
                        await VS.Documents.OpenAsync(file);
                    }
                    Telemetry.TrackEvent("PowerTools.GenerateSqlCreate");
                    break;

                case GenerationType.DebugView:
                    var views = project.GenerateFiles(modelResult, ".txt");
                    foreach (var file in views)
                    {
                        await VS.Documents.OpenAsync(file);
                    }
                    Telemetry.TrackEvent("PowerTools.GenerateDebugView");
                    break;

                default:
                    break;
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
        public void GenerateServerDgmlFiles()
        {
            try
            {
                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                var databaseList = EnvDteHelper.GetDataConnections(_package);

                var psd     = new PickServerDatabaseDialog(databaseList, _package, new Dictionary <string, string>());
                var diagRes = psd.ShowModal();
                if (!diagRes.HasValue || !diagRes.Value)
                {
                    return;
                }

                _package.Dte2.StatusBar.Text = "Loading schema information...";

                var dbInfo = psd.SelectedDatabase.Value;

                if (dbInfo.DatabaseType == DatabaseType.SQLCE35)
                {
                    EnvDteHelper.ShowError($"Unsupported provider: {dbInfo.ServerVersion}");
                    return;
                }

                var ptd = new PickTablesDialog();
                using (var repository = RepositoryHelper.CreateRepository(dbInfo))
                {
                    var ti     = new List <TableInformation>();
                    var tables = repository.GetAllTableNamesForExclusion();
                    foreach (var table in tables)
                    {
                        ti.Add(TableInformation.Parse(table));
                    }
                    ptd.Tables = ti;
                }

                var res = ptd.ShowModal();
                if (!res.HasValue || !res.Value)
                {
                    return;
                }

                var name = RepositoryHelper.GetClassBasis(dbInfo.ConnectionString, dbInfo.DatabaseType);

                var path = Path.Combine(Path.GetTempPath(),
                                        name + ".schema.dgml");

                if (File.Exists(path))
                {
                    File.SetAttributes(path, FileAttributes.Normal);
                }

                using (var repository = RepositoryHelper.CreateRepository(dbInfo))
                {
                    var generator = RepositoryHelper.CreateGenerator(repository, path, dbInfo.DatabaseType);
                    generator.GenerateSchemaGraph(dbInfo.ConnectionString, ptd.Tables.Select(m => m.UnsafeFullName).ToList());
                    File.SetAttributes(path, FileAttributes.ReadOnly);
                    _package.Dte2.ItemOperations.OpenFile(path);
                    _package.Dte2.ActiveDocument.Activate();
                }
                Telemetry.TrackEvent("PowerTools.GenerateSchemaDgml");
            }
            catch (Exception ex)
            {
                _package.LogError(new List <string>(), ex);
            }
        }
Beispiel #23
0
        public async System.Threading.Tasks.Task ReverseEngineerCodeFirstAsync(Project project)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            try
            {
                var    dteH         = new EnvDteHelper();
                string dacpacSchema = null;

                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                var projectPath  = project.Properties.Item("FullPath")?.Value.ToString();
                var optionsPaths = project.GetConfigFiles();
                var optionsPath  = optionsPaths.First();
                var renamingPath = project.GetRenamingPath();

                if (optionsPaths.Count > 1)
                {
                    var pcd = _package.GetView <IPickConfigDialog>();
                    pcd.PublishConfigurations(optionsPaths.Select(m => new ConfigModel
                    {
                        ConfigPath = m,
                    }));

                    var pickConfigResult = pcd.ShowAndAwaitUserResponse(true);
                    if (!pickConfigResult.ClosedByOK)
                    {
                        return;
                    }

                    optionsPath = pickConfigResult.Payload.ConfigPath;
                }

                var databaseList = VsDataHelper.GetDataConnections(_package);
                var dacpacList   = _package.Dte2.DTE.GetDacpacFilesInActiveSolution(EnvDteHelper.GetProjectFilesInSolution(_package));
                var options      = ReverseEngineerOptionsExtensions.TryRead(optionsPath);

                var psd = _package.GetView <IPickServerDatabaseDialog>();

                if (databaseList != null && databaseList.Any())
                {
                    psd.PublishConnections(databaseList.Select(m => new DatabaseConnectionModel
                    {
                        ConnectionName   = m.Value.Caption,
                        ConnectionString = m.Value.ConnectionString,
                        DatabaseType     = m.Value.DatabaseType,
                        DataConnection   = m.Value.DataConnection,
                    }));
                }

                if (dacpacList != null && dacpacList.Any())
                {
                    psd.PublishDefinitions(dacpacList.Select(m => new DatabaseDefinitionModel
                    {
                        FilePath = m
                    }));
                }

                if (options != null && options.FilterSchemas && options.Schemas != null && options.Schemas.Any())
                {
                    psd.PublishSchemas(options.Schemas);
                }

                if (options != null)
                {
                    psd.PublishCodeGenerationMode(options.CodeGenerationMode);
                }

                var pickDataSourceResult = psd.ShowAndAwaitUserResponse(true);
                if (!pickDataSourceResult.ClosedByOK)
                {
                    return;
                }

                var useEFCore5    = pickDataSourceResult.Payload.IncludeViews;
                var filterSchemas = pickDataSourceResult.Payload.FilterSchemas;
                var schemas       = filterSchemas ? pickDataSourceResult.Payload.Schemas : null;

                _package.Dte2.StatusBar.Text = "Getting ready to connect...";

                // Reload the database list, in case the user has added a new database in the dialog
                databaseList = VsDataHelper.GetDataConnections(_package);

                DatabaseInfo dbInfo = null;
                if (pickDataSourceResult.Payload.Connection != null)
                {
                    dbInfo = databaseList.Single(m => m.Value.ConnectionString == pickDataSourceResult.Payload.Connection?.ConnectionString).Value;
                }
                var dacpacPath = pickDataSourceResult.Payload.Definition?.FilePath;

                if (dbInfo == null)
                {
                    dbInfo = new DatabaseInfo();
                }

                if (!string.IsNullOrEmpty(dacpacPath))
                {
                    dbInfo.DatabaseType     = DatabaseType.SQLServerDacpac;
                    dbInfo.ConnectionString = $"Data Source=(local);Initial Catalog={Path.GetFileNameWithoutExtension(dacpacPath)};Integrated Security=true;";
                    dacpacPath = _package.Dte2.DTE.BuildSqlProj(dacpacPath);
                    if (string.IsNullOrEmpty(dacpacPath))
                    {
                        EnvDteHelper.ShowMessage("Unable to build selected Database Project");
                        return;
                    }
                }

                if (dbInfo.DatabaseType == DatabaseType.SQLCE35 ||
                    dbInfo.DatabaseType == DatabaseType.SQLCE40 ||
                    dbInfo.DatabaseType == DatabaseType.Undefined)
                {
                    EnvDteHelper.ShowError($"Unsupported provider: {dbInfo.ServerVersion}");
                    return;
                }

                //TODO Enable when Oracle EF Core 5 provider is released
                if (useEFCore5 && (dbInfo.DatabaseType == DatabaseType.Oracle))
                {
                    EnvDteHelper.ShowError($"Unsupported provider with EF Core 5.0: {dbInfo.DatabaseType}");
                    return;
                }

                _package.Dte2.StatusBar.Text = "Loading database objects...";
                object icon = (short)Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_Build;
                _package.Dte2.StatusBar.Animate(true, icon);
                var predefinedTables = !string.IsNullOrEmpty(dacpacPath)
                                           ? await GetDacpacTablesAsync(dacpacPath, useEFCore5)
                                           : await GetTablesAsync(dbInfo, useEFCore5, schemas);

                _package.Dte2.StatusBar.Animate(false, icon);

                var preselectedTables = new List <SerializationTableModel>();
                if (options != null)
                {
                    dacpacSchema = options.DefaultDacpacSchema;
                    if (options.Tables.Count > 0)
                    {
                        var normalizedTables = reverseEngineerHelper.NormalizeTables(options.Tables, dbInfo.DatabaseType == DatabaseType.SQLServer);
                        preselectedTables.AddRange(normalizedTables);
                    }
                }

                var namingOptionsAndPath = CustomNameOptionsExtensions.TryRead(renamingPath, optionsPath);

                _package.Dte2.StatusBar.Clear();

                var ptd = _package.GetView <IPickTablesDialog>()
                          .AddTables(predefinedTables, namingOptionsAndPath.Item1)
                          .PreselectTables(preselectedTables);

                var pickTablesResult = ptd.ShowAndAwaitUserResponse(true);
                if (!pickTablesResult.ClosedByOK)
                {
                    return;
                }

                _package.Dte2.StatusBar.Text = "Loading options...";

                var classBasis    = VsDataHelper.GetDatabaseName(dbInfo.ConnectionString, dbInfo.DatabaseType);
                var model         = reverseEngineerHelper.GenerateClassName(classBasis) + "Context";
                var packageResult = project.ContainsEfCoreReference(dbInfo.DatabaseType);

                var presets = new ModelingOptionsModel
                {
                    InstallNuGetPackage = !packageResult.Item1,
                    ModelName           = options != null ? options.ContextClassName : model,
                    ProjectName         = project.Name,
                    Namespace           = options != null ? options.ProjectRootNamespace : project.Properties.Item("DefaultNamespace").Value.ToString(),
                    DacpacPath          = dacpacPath,
                };
                if (options != null)
                {
                    presets.UseDataAnnotations         = !options.UseFluentApiOnly;
                    presets.UseDatabaseNames           = options.UseDatabaseNames;
                    presets.UsePluralizer              = options.UseInflector;
                    presets.UseDbContextSplitting      = options.UseDbContextSplitting;
                    presets.UseHandlebars              = options.UseHandleBars;
                    presets.SelectedHandlebarsLanguage = options.SelectedHandlebarsLanguage;
                    presets.IncludeConnectionString    = options.IncludeConnectionString;
                    presets.ModelName             = options.ContextClassName;
                    presets.Namespace             = options.ProjectRootNamespace;
                    presets.OutputPath            = options.OutputPath;
                    presets.OutputContextPath     = options.OutputContextPath;
                    presets.ModelNamespace        = options.ModelNamespace;
                    presets.ContextNamespace      = options.ContextNamespace;
                    presets.SelectedToBeGenerated = options.SelectedToBeGenerated;
                    presets.DacpacPath            = options.Dacpac;
                    presets.UseEf6Pluralizer      = options.UseLegacyPluralizer;
                    presets.MapSpatialTypes       = options.UseSpatial;
                    presets.MapNodaTimeTypes      = options.UseNodaTime;
                    presets.UseBoolPropertiesWithoutDefaultSql = options.UseBoolPropertiesWithoutDefaultSql;
                    presets.UseNoConstructor      = options.UseNoConstructor;
                    presets.UseNoNavigations      = options.UseNoNavigations;
                    presets.UseNullableReferences = options.UseNullableReferences;
                }

                var modelDialog = _package.GetView <IModelingOptionsDialog>()
                                  .ApplyPresets(presets);

                _package.Dte2.StatusBar.Clear();

                var modelingOptionsResult = modelDialog.ShowAndAwaitUserResponse(true);
                if (!modelingOptionsResult.ClosedByOK)
                {
                    return;
                }

                options = new ReverseEngineerOptions
                {
                    UseFluentApiOnly                   = !modelingOptionsResult.Payload.UseDataAnnotations,
                    ConnectionString                   = dbInfo.ConnectionString,
                    ContextClassName                   = modelingOptionsResult.Payload.ModelName,
                    DatabaseType                       = dbInfo.DatabaseType,
                    ProjectPath                        = projectPath,
                    OutputPath                         = modelingOptionsResult.Payload.OutputPath,
                    OutputContextPath                  = modelingOptionsResult.Payload.OutputContextPath,
                    ContextNamespace                   = modelingOptionsResult.Payload.ContextNamespace,
                    ModelNamespace                     = modelingOptionsResult.Payload.ModelNamespace,
                    ProjectRootNamespace               = modelingOptionsResult.Payload.Namespace,
                    UseDatabaseNames                   = modelingOptionsResult.Payload.UseDatabaseNames,
                    UseInflector                       = modelingOptionsResult.Payload.UsePluralizer,
                    UseLegacyPluralizer                = modelingOptionsResult.Payload.UseEf6Pluralizer,
                    UseSpatial                         = modelingOptionsResult.Payload.MapSpatialTypes,
                    UseNodaTime                        = modelingOptionsResult.Payload.MapNodaTimeTypes,
                    UseDbContextSplitting              = modelingOptionsResult.Payload.UseDbContextSplitting,
                    UseHandleBars                      = modelingOptionsResult.Payload.UseHandlebars,
                    SelectedHandlebarsLanguage         = modelingOptionsResult.Payload.SelectedHandlebarsLanguage,
                    IncludeConnectionString            = modelingOptionsResult.Payload.IncludeConnectionString,
                    SelectedToBeGenerated              = modelingOptionsResult.Payload.SelectedToBeGenerated,
                    UseBoolPropertiesWithoutDefaultSql = modelingOptionsResult.Payload.UseBoolPropertiesWithoutDefaultSql,
                    UseNullableReferences              = modelingOptionsResult.Payload.UseNullableReferences,
                    UseNoConstructor                   = modelingOptionsResult.Payload.UseNoConstructor,
                    UseNoNavigations                   = modelingOptionsResult.Payload.UseNoNavigations,
                    Dacpac = dacpacPath,
                    DefaultDacpacSchema = dacpacSchema,
                    Tables             = pickTablesResult.Payload.Objects.ToList(),
                    CustomReplacers    = pickTablesResult.Payload.CustomReplacers.ToList(),
                    FilterSchemas      = filterSchemas,
                    Schemas            = schemas?.ToList(),
                    CodeGenerationMode = pickDataSourceResult.Payload.IncludeViews ? CodeGenerationMode.EFCore5 : CodeGenerationMode.EFCore3,
                };

                if (options.DatabaseType == DatabaseType.SQLServer &&
                    string.IsNullOrEmpty(options.Dacpac))
                {
                    var rightsAndVersion = reverseEngineerHelper.HasSqlServerViewDefinitionRightsAndVersion(options.ConnectionString);

                    if (rightsAndVersion.Item1 == false)
                    {
                        EnvDteHelper.ShowMessage("The SQL Server user does not have 'VIEW DEFINITION' rights, default constraints may not be available.");
                    }

                    if (rightsAndVersion.Item2.Major < 11)
                    {
                        EnvDteHelper.ShowMessage($"SQL Server version {rightsAndVersion.Item2} may not be supported.");
                    }
                }

                var  tfm           = project.Properties.Item("TargetFrameworkMoniker").Value.ToString();
                bool isNetStandard = tfm.Contains(".NETStandard,Version=v2.");

                if (modelingOptionsResult.Payload.UseHandlebars)
                {
                    var dropped = (DropTemplates(projectPath, useEFCore5));
                    if (dropped && !project.IsNetCore() && !isNetStandard)
                    {
                        project.ProjectItems.AddFromDirectory(Path.Combine(projectPath, "CodeTemplates"));
                    }
                }

                var startTime = DateTime.Now;

                _package.Dte2.StatusBar.Animate(true, icon);
                _package.Dte2.StatusBar.Text = "Generating code...";
                var revEngResult = EfRevEngLauncher.LaunchExternalRunner(options, useEFCore5);
                _package.Dte2.StatusBar.Animate(false, icon);
                if (modelingOptionsResult.Payload.SelectedToBeGenerated == 0 || modelingOptionsResult.Payload.SelectedToBeGenerated == 2)
                {
                    foreach (var filePath in revEngResult.EntityTypeFilePaths)
                    {
                        if (!project.IsNetCore() && !isNetStandard)
                        {
                            project.ProjectItems.AddFromFile(filePath);
                        }
                    }
                    if (modelingOptionsResult.Payload.SelectedToBeGenerated == 2)
                    {
                        if (File.Exists(revEngResult.ContextFilePath))
                        {
                            File.Delete(revEngResult.ContextFilePath);
                        }
                        foreach (var filePath in revEngResult.ContextConfigurationFilePaths)
                        {
                            if (File.Exists(filePath))
                            {
                                File.Delete(filePath);
                            }
                        }
                    }
                }

                if (modelingOptionsResult.Payload.SelectedToBeGenerated == 0 || modelingOptionsResult.Payload.SelectedToBeGenerated == 1)
                {
                    if (!project.IsNetCore() && !isNetStandard)
                    {
                        foreach (var filePath in revEngResult.ContextConfigurationFilePaths)
                        {
                            project.ProjectItems.AddFromFile(filePath);
                        }
                        project.ProjectItems.AddFromFile(revEngResult.ContextFilePath);
                    }

                    _package.Dte2.ItemOperations.OpenFile(revEngResult.ContextFilePath);

                    if (modelingOptionsResult.Payload.SelectedToBeGenerated == 1)
                    {
                        foreach (var filePath in revEngResult.EntityTypeFilePaths)
                        {
                            if (File.Exists(filePath))
                            {
                                File.Delete(filePath);
                            }
                        }
                    }
                }

                var duration = DateTime.Now - startTime;

                var missingProviderPackage = packageResult.Item1 ? null : packageResult.Item2;
                if (modelingOptionsResult.Payload.InstallNuGetPackage || modelingOptionsResult.Payload.SelectedToBeGenerated == 2)
                {
                    missingProviderPackage = null;
                }

                _package.Dte2.StatusBar.Text = "Reporting result...";
                var errors = reverseEngineerHelper.ReportRevEngErrors(revEngResult, missingProviderPackage);

                SaveOptions(project, optionsPath, options, new Tuple <List <Schema>, string>(pickTablesResult.Payload.CustomReplacers.ToList(), namingOptionsAndPath.Item2));

                if (modelingOptionsResult.Payload.InstallNuGetPackage)
                {
                    _package.Dte2.StatusBar.Text = "Installing EF Core provider package";
                    var nuGetHelper = new NuGetHelper();
                    await nuGetHelper.InstallPackageAsync(packageResult.Item2, project);
                }

                _package.Dte2.StatusBar.Text = $"Reverse engineer completed in {duration:h\\:mm\\:ss}";

                EnvDteHelper.ShowMessage(errors);

                if (revEngResult.EntityErrors.Count > 0)
                {
                    _package.LogError(revEngResult.EntityErrors, null);
                }
                if (revEngResult.EntityWarnings.Count > 0)
                {
                    _package.LogError(revEngResult.EntityWarnings, null);
                }
                Telemetry.TrackEvent("PowerTools.ReverseEngineer");
            }
            catch (AggregateException ae)
            {
                foreach (var innerException in ae.Flatten().InnerExceptions)
                {
                    _package.LogError(new List <string>(), innerException);
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
Beispiel #24
0
        public async System.Threading.Tasks.Task HandleComparisonAsync(string outputPath, Project project)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            try
            {
                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError(CompareLocale.CannotCompareContextToDatabaseWhileDebugging);
                    return;
                }

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

                if (project.Properties.Item("TargetFrameworkMoniker") == null)
                {
                    EnvDteHelper.ShowError(SharedLocale.SelectedProjectTypeNoTargetFrameworkMoniker);
                    return;
                }

                if (!project.IsNetCore30OrHigher())
                {
                    EnvDteHelper.ShowError($"{SharedLocale.SupportedFramework}: {project.Properties.Item("TargetFrameworkMoniker").Value}");
                    return;
                }

                var result = await project.ContainsEfSchemaCompareReferenceAsync();

                if (!result.Item1)
                {
                    if (!Version.TryParse(result.Item2, out Version version))
                    {
                        EnvDteHelper.ShowError(String.Format(CompareLocale.CannotSupportVersion, result.Item2));
                        return;
                    }

                    if (version.Major != 5)
                    {
                        EnvDteHelper.ShowError(CompareLocale.VersionSupported);
                        return;
                    }

                    var nugetHelper = new NuGetHelper();
                    nugetHelper.InstallPackage("EfCore.SchemaCompare", project, new Version(5, 1, 3));
                    EnvDteHelper.ShowError(CompareLocale.InstallingEfCoreSchemaCompare);
                    return;
                }

                _package.Dte2.StatusBar.Text = CompareLocale.LoadingData;
                object icon = (short)Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_Build;
                _package.Dte2.StatusBar.Animate(true, icon);

                var databaseList = vsDataHelper.GetDataConnections(_package);
                var contextTypes = await GetDbContextTypesAsync(outputPath, project);

                var optionsDialog = _package.GetView <ICompareOptionsDialog>();

                if (databaseList != null && databaseList.Any())
                {
                    optionsDialog.AddConnections(databaseList.Select(m => new DatabaseConnectionModel
                    {
                        ConnectionName   = m.Value.Caption,
                        ConnectionString = m.Value.ConnectionString,
                        DatabaseType     = m.Value.DatabaseType,
                        DataConnection   = m.Value.DataConnection,
                    }));
                }

                optionsDialog.AddContextTypes(contextTypes);

                _package.Dte2.StatusBar.Animate(false, icon);
                _package.Dte2.StatusBar.Clear();
                var pickDataSourceResult = optionsDialog.ShowAndAwaitUserResponse(true);
                if (!pickDataSourceResult.ClosedByOK)
                {
                    return;
                }

                if (!pickDataSourceResult.Payload.ContextTypes.Any())
                {
                    EnvDteHelper.ShowError(CompareLocale.NoContextsSelected);
                    return;
                }

                pickDataSourceResult.Payload.Connection.DataConnection.Open();
                pickDataSourceResult.Payload.Connection.ConnectionString = DataProtection.DecryptString(pickDataSourceResult.Payload.Connection.DataConnection.EncryptedConnectionString);

                _package.Dte2.StatusBar.Text = CompareLocale.ComparingDatabaseWithContexts;
                _package.Dte2.StatusBar.Animate(true, icon);
                var timer = new Stopwatch();
                timer.Start();
                var comparisonResult = await GetComparisonResultAsync(
                    outputPath,
                    project,
                    pickDataSourceResult.Payload.Connection,
                    pickDataSourceResult.Payload.ContextTypes.ToArray());

                timer.Stop();
                _package.Dte2.StatusBar.Animate(false, icon);
                _package.Dte2.StatusBar.Text = String.Format(CompareLocale.CompareCompletedIn, timer.Elapsed.ToString("h\\:mm\\:ss"));

                if (comparisonResult.Any())
                {
                    var resultDialog = _package.GetView <ICompareResultDialog>();
                    resultDialog.AddComparisonResult(comparisonResult);
                    resultDialog.ShowAndAwaitUserResponse(true);
                }
                else
                {
                    EnvDteHelper.ShowMessage(CompareLocale.ContextDatabaseMatch);
                }

                _package.Dte2.StatusBar.Clear();

                Telemetry.TrackEvent("PowerTools.Compare");
            }
            catch (AggregateException ae)
            {
                foreach (var innerException in ae.Flatten().InnerExceptions)
                {
                    _package.LogError(new List <string>(), innerException);
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
        public async System.Threading.Tasks.Task ReverseEngineerCodeFirstAsync(Project project, string optionsPath, bool onlyGenerate)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            try
            {
                var dteH = new EnvDteHelper();

                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                var renamingPath         = project.GetRenamingPath();
                var namingOptionsAndPath = CustomNameOptionsExtensions.TryRead(renamingPath, optionsPath);

                Tuple <bool, string> containsEfCoreReference = null;

                var options = ReverseEngineerOptionsExtensions.TryRead(optionsPath) ?? new ReverseEngineerOptions();

                options.ProjectPath = project.Properties.Item("FullPath")?.Value.ToString();

                if (string.IsNullOrWhiteSpace(options.ProjectRootNamespace))
                {
                    options.ProjectRootNamespace = project.Properties.Item("DefaultNamespace").Value.ToString();
                }

                bool forceEdit = false;

                if (onlyGenerate)
                {
                    forceEdit = !ChooseDataBaseConnectionByUiHint(options);

                    if (forceEdit)
                    {
                        _package.Dte2.StatusBar.Text = "Database don't found, force edit config";
                    }
                    else
                    {
                        containsEfCoreReference     = project.ContainsEfCoreReference(options.DatabaseType);
                        options.InstallNuGetPackage = false;
                    }
                }

                if (!onlyGenerate || forceEdit)
                {
                    if (!ChooseDataBaseConnection(options))
                    {
                        return;
                    }

                    _package.Dte2.StatusBar.Text = "Getting ready to connect...";

                    DatabaseInfo dbInfo = GetDatabaseInfo(options);

                    if (dbInfo == null)
                    {
                        return;
                    }

                    _package.Dte2.StatusBar.Text = "Loading database objects...";

                    if (!await LoadDataBaseObjectsAsync(options, dbInfo, namingOptionsAndPath))
                    {
                        return;
                    }

                    _package.Dte2.StatusBar.Text = "Loading options...";

                    containsEfCoreReference     = project.ContainsEfCoreReference(options.DatabaseType);
                    options.InstallNuGetPackage = !containsEfCoreReference.Item1;

                    if (!GetModelOptions(options, project.Name))
                    {
                        return;
                    }

                    SaveOptions(project, optionsPath, options, new Tuple <List <Schema>, string>(options.CustomReplacers, namingOptionsAndPath.Item2));
                }

                VerifySQLServerRightsAndVersion(options);

                GenerateEfRevEng(project, options, containsEfCoreReference);

                if (options.InstallNuGetPackage && (!onlyGenerate || forceEdit))
                {
                    _package.Dte2.StatusBar.Text = "Installing EF Core provider package";
                    var nuGetHelper = new NuGetHelper();
                    await nuGetHelper.InstallPackageAsync(containsEfCoreReference.Item2, project);
                }

                Telemetry.TrackEvent("PowerTools.ReverseEngineer");
            }
            catch (AggregateException ae)
            {
                foreach (var innerException in ae.Flatten().InnerExceptions)
                {
                    _package.LogError(new List <string>(), innerException);
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
Beispiel #26
0
        public async System.Threading.Tasks.Task HandleComparisonAsync(string outputPath, Project project)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            try
            {
                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot compare context to database while debugging");
                    return;
                }

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

                if (project.Properties.Item("TargetFrameworkMoniker") == null)
                {
                    EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker");
                    return;
                }

                if (!project.IsNetCore30OrHigher())
                {
                    EnvDteHelper.ShowError("Only .NET Core 3.0+ projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                    return;
                }

                var result = await project.ContainsEfCoreDesignReferenceAsync();

                if (!result.Item1)
                {
                    if (!Version.TryParse(result.Item2, out Version version))
                    {
                        EnvDteHelper.ShowError($"Cannot support version {result.Item2}, notice that previews have limited supported. You can try to manually install Microsoft.EntityFrameworkCore.Design preview.");
                        return;
                    }

                    if (version.Major != 5)
                    {
                        EnvDteHelper.ShowError($"Only EF Core 5 is supported.");
                        return;
                    }

                    var nugetHelper = new NuGetHelper();
                    nugetHelper.InstallPackage("EfCore.SchemaCompare", project, new Version(5, 1, 3));
                    EnvDteHelper.ShowError($"Installing EfCore.SchemaCompare version 5.1.3, please retry the command");
                    return;
                }

                _package.Dte2.StatusBar.Text = "Loading data";
                object icon = (short)Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_Build;
                _package.Dte2.StatusBar.Animate(true, icon);

                var databaseList = VsDataHelper.GetDataConnections(_package);
                var contextTypes = await GetDbContextTypesAsync(outputPath, project);

                var optionsDialog = _package.GetView <ICompareOptionsDialog>();

                if (databaseList != null && databaseList.Any())
                {
                    optionsDialog.AddConnections(databaseList.Select(m => new DatabaseConnectionModel
                    {
                        ConnectionName   = m.Value.Caption,
                        ConnectionString = m.Value.ConnectionString,
                        DatabaseType     = m.Value.DatabaseType,
                        DataConnection   = m.Value.DataConnection,
                    }));
                }

                optionsDialog.AddContextTypes(contextTypes);

                _package.Dte2.StatusBar.Animate(false, icon);
                _package.Dte2.StatusBar.Clear();
                var pickDataSourceResult = optionsDialog.ShowAndAwaitUserResponse(true);
                if (!pickDataSourceResult.ClosedByOK)
                {
                    return;
                }

                pickDataSourceResult.Payload.Connection.DataConnection.Open();
                pickDataSourceResult.Payload.Connection.ConnectionString = DataProtection.DecryptString(pickDataSourceResult.Payload.Connection.DataConnection.EncryptedConnectionString);

                _package.Dte2.StatusBar.Text = "Comparing database with context(s)...";
                _package.Dte2.StatusBar.Animate(true, icon);
                var timer = new Stopwatch();
                timer.Start();
                var comparisonResult = await GetComparisonResultAsync(
                    outputPath,
                    project,
                    pickDataSourceResult.Payload.Connection,
                    pickDataSourceResult.Payload.ContextTypes.ToArray());

                timer.Stop();
                _package.Dte2.StatusBar.Animate(false, icon);
                _package.Dte2.StatusBar.Text = $"Compare completed in {timer.Elapsed:h\\:mm\\:ss}";

                if (comparisonResult.Any())
                {
                    var resultDialog = _package.GetView <ICompareResultDialog>();
                    resultDialog.AddComparisonResult(comparisonResult);
                    resultDialog.ShowAndAwaitUserResponse(true);
                }
                else
                {
                    EnvDteHelper.ShowMessage("Context(s) and database structure match");
                }

                _package.Dte2.StatusBar.Clear();

                Telemetry.TrackEvent("PowerTools.Compare");
            }
            catch (AggregateException ae)
            {
                foreach (var innerException in ae.Flatten().InnerExceptions)
                {
                    _package.LogError(new List <string>(), innerException);
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
Beispiel #27
0
        public async void ReverseEngineerCodeFirst(Project project)
        {
            try
            {
                var    dteH         = new EnvDteHelper();
                var    revEng       = new EfCoreReverseEngineer();
                string dacpacSchema = null;

                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                var startTime    = DateTime.Now;
                var projectPath  = project.Properties.Item("FullPath").Value.ToString();
                var optionsPath  = Path.Combine(projectPath, "efpt.config.json");
                var renamingPath = Path.Combine(projectPath, "efpt.renaming.json");

                var databaseList = EnvDteHelper.GetDataConnections(_package);
                var dacpacList   = _package.Dte2.DTE.GetDacpacFilesInActiveSolution();

                var psd = _package.GetView <IPickServerDatabaseDialog>();

                if (databaseList != null && databaseList.Any())
                {
                    psd.PublishConnections(databaseList.Select(m => new DatabaseConnectionModel
                    {
                        ConnectionName   = m.Value.Caption,
                        ConnectionString = m.Value.ConnectionString,
                        DatabaseType     = m.Value.DatabaseType
                    }));
                }

                if (dacpacList != null && dacpacList.Any())
                {
                    psd.PublishDefinitions(dacpacList.Select(m => new DatabaseDefinitionModel
                    {
                        FilePath = m
                    }));
                }

                var pickDataSourceResult = psd.ShowAndAwaitUserResponse(true);
                if (!pickDataSourceResult.ClosedByOK)
                {
                    return;
                }

                _package.Dte2.StatusBar.Text = "Loading schema information...";

                // Reload the database list, in case the user has added a new database in the dialog
                databaseList = EnvDteHelper.GetDataConnections(_package);

                DatabaseInfo dbInfo = null;
                if (pickDataSourceResult.Payload.Connection != null)
                {
                    dbInfo = databaseList.Single(m => m.Value.ConnectionString == pickDataSourceResult.Payload.Connection?.ConnectionString).Value;
                }
                var dacpacPath = pickDataSourceResult.Payload.Definition?.FilePath;

                if (dbInfo == null)
                {
                    dbInfo = new DatabaseInfo();
                }

                if (!string.IsNullOrEmpty(dacpacPath))
                {
                    dbInfo.DatabaseType     = DatabaseType.SQLServer;
                    dbInfo.ConnectionString = "Data Source=.;Initial Catalog=" + Path.GetFileNameWithoutExtension(dacpacPath);
                    dacpacPath = _package.Dte2.DTE.BuildSqlProj(dacpacPath);
                    if (string.IsNullOrEmpty(dacpacPath))
                    {
                        EnvDteHelper.ShowMessage("Unable to build selected Database Project");
                        return;
                    }
                }

                if (dbInfo.DatabaseType == DatabaseType.SQLCE35)
                {
                    EnvDteHelper.ShowError($"Unsupported provider: {dbInfo.ServerVersion}");
                    return;
                }

                var options = ReverseEngineerOptionsExtensions.TryRead(optionsPath);

                var predefinedTables = !string.IsNullOrEmpty(dacpacPath)
                                           ? revEng.GetDacpacTables(dacpacPath)
                                           : GetTablesFromRepository(dbInfo);

                var preselectedTables = new List <TableInformationModel>();
                if (options != null)
                {
                    dacpacSchema = options.DefaultDacpacSchema;
                    if (options.Tables.Count > 0)
                    {
                        preselectedTables.AddRange(options.Tables);
                    }
                }

                var ptd = _package.GetView <IPickTablesDialog>()
                          .AddTables(predefinedTables)
                          .PreselectTables(preselectedTables);

                var customNameOptions = CustomNameOptionsExtensions.TryRead(renamingPath);

                var pickTablesResult = ptd.ShowAndAwaitUserResponse(true);
                if (!pickTablesResult.ClosedByOK)
                {
                    return;
                }

                var classBasis = string.Empty;
                if (dbInfo.DatabaseType == DatabaseType.Npgsql)
                {
                    classBasis = EnvDteHelper.GetNpgsqlDatabaseName(dbInfo.ConnectionString);
                }
                else if (dbInfo.DatabaseType == DatabaseType.Mysql)
                {
                    classBasis = EnvDteHelper.GetMysqlDatabaseName(dbInfo.ConnectionString);
                }
                else
                {
                    classBasis = RepositoryHelper.GetClassBasis(dbInfo.ConnectionString, dbInfo.DatabaseType);
                }
                var model         = revEng.GenerateClassName(classBasis) + "Context";
                var packageResult = project.ContainsEfCoreReference(dbInfo.DatabaseType);

                var presets = new ModelingOptionsModel
                {
                    InstallNuGetPackage = !packageResult.Item1,
                    ModelName           = options != null ? options.ContextClassName : model,
                    ProjectName         = project.Name,
                    Namespace           = options != null ? options.ProjectRootNamespace : project.Properties.Item("DefaultNamespace").Value.ToString(),
                    DacpacPath          = dacpacPath,
                };
                if (options != null)
                {
                    presets.UseDataAnnotations         = !options.UseFluentApiOnly;
                    presets.UseDatabaseNames           = options.UseDatabaseNames;
                    presets.UsePluralizer              = options.UseInflector;
                    presets.UseHandelbars              = options.UseHandleBars;
                    presets.SelectedHandlebarsLanguage = options.SelectedHandlebarsLanguage;
                    presets.ReplaceId               = options.IdReplace;
                    presets.DoNotCombineNamespace   = options.DoNotCombineNamespace;
                    presets.IncludeConnectionString = options.IncludeConnectionString;
                    presets.ModelName               = options.ContextClassName;
                    presets.Namespace               = options.ProjectRootNamespace;
                    presets.OutputPath              = options.OutputPath;
                    presets.SelectedToBeGenerated   = options.SelectedToBeGenerated;
                }

                var modelDialog = _package.GetView <IModelingOptionsDialog>()
                                  .ApplyPresets(presets);

                _package.Dte2.StatusBar.Text = "Getting options...";

                var modelingOptionsResult = modelDialog.ShowAndAwaitUserResponse(true);
                if (!modelingOptionsResult.ClosedByOK)
                {
                    return;
                }

                options = new ReverseEngineerOptions
                {
                    UseFluentApiOnly           = !modelingOptionsResult.Payload.UseDataAnnotations,
                    ConnectionString           = dbInfo.ConnectionString,
                    ContextClassName           = modelingOptionsResult.Payload.ModelName,
                    DatabaseType               = (ReverseEngineer20.DatabaseType)dbInfo.DatabaseType,
                    ProjectPath                = projectPath,
                    OutputPath                 = modelingOptionsResult.Payload.OutputPath,
                    ProjectRootNamespace       = modelingOptionsResult.Payload.Namespace,
                    UseDatabaseNames           = modelingOptionsResult.Payload.UseDatabaseNames,
                    UseInflector               = modelingOptionsResult.Payload.UsePluralizer,
                    UseLegacyPluralizer        = options?.UseLegacyPluralizer ?? false,
                    IdReplace                  = modelingOptionsResult.Payload.ReplaceId,
                    DoNotCombineNamespace      = modelingOptionsResult.Payload.DoNotCombineNamespace,
                    UseHandleBars              = modelingOptionsResult.Payload.UseHandelbars,
                    SelectedHandlebarsLanguage = modelingOptionsResult.Payload.SelectedHandlebarsLanguage,
                    IncludeConnectionString    = modelingOptionsResult.Payload.IncludeConnectionString,
                    SelectedToBeGenerated      = modelingOptionsResult.Payload.SelectedToBeGenerated,
                    Dacpac = dacpacPath,
                    DefaultDacpacSchema = dacpacSchema,
                    Tables          = pickTablesResult.Payload.ToList(),
                    CustomReplacers = customNameOptions
                };

                _package.Dte2.StatusBar.Text = "Generating code...";

                var  tfm           = project.Properties.Item("TargetFrameworkMoniker").Value.ToString();
                bool isNetStandard = tfm.Contains(".NETStandard,Version=v2.0");

                if (modelingOptionsResult.Payload.UseHandelbars)
                {
                    var dropped = (DropTemplates(projectPath));
                    if (dropped && !project.IsNetCore() && !isNetStandard)
                    {
                        project.ProjectItems.AddFromDirectory(Path.Combine(projectPath, "CodeTemplates"));
                    }
                }

                var revEngResult = revEng.GenerateFiles(options);

                if (modelingOptionsResult.Payload.SelectedToBeGenerated == 0 || modelingOptionsResult.Payload.SelectedToBeGenerated == 2)
                {
                    foreach (var filePath in revEngResult.EntityTypeFilePaths)
                    {
                        project.ProjectItems.AddFromFile(filePath);
                    }
                    if (modelingOptionsResult.Payload.SelectedToBeGenerated == 2)
                    {
                        if (File.Exists(revEngResult.ContextFilePath))
                        {
                            File.Delete(revEngResult.ContextFilePath);
                        }
                    }
                }
                if (modelingOptionsResult.Payload.SelectedToBeGenerated == 0 || modelingOptionsResult.Payload.SelectedToBeGenerated == 1)
                {
                    project.ProjectItems.AddFromFile(revEngResult.ContextFilePath);
                    if (!project.IsNetCore() && !isNetStandard)
                    {
                        _package.Dte2.ItemOperations.OpenFile(revEngResult.ContextFilePath);
                    }
                    if (modelingOptionsResult.Payload.SelectedToBeGenerated == 1)
                    {
                        foreach (var filePath in revEngResult.EntityTypeFilePaths)
                        {
                            if (File.Exists(filePath))
                            {
                                File.Delete(filePath);
                            }
                        }
                    }
                }

                var missingProviderPackage = packageResult.Item1 ? null : packageResult.Item2;
                if (modelingOptionsResult.Payload.InstallNuGetPackage || modelingOptionsResult.Payload.SelectedToBeGenerated == 2)
                {
                    missingProviderPackage = null;
                }

                _package.Dte2.StatusBar.Text = "Reporting result...";
                var errors = ReportRevEngErrors(revEngResult, missingProviderPackage);

                SaveOptions(project, optionsPath, options);

                if (modelingOptionsResult.Payload.InstallNuGetPackage)
                {
                    _package.Dte2.StatusBar.Text = "Installing EF Core provider package";
                    var nuGetHelper = new NuGetHelper();
                    await nuGetHelper.InstallPackageAsync(packageResult.Item2, project);
                }
                var duration = DateTime.Now - startTime;
                _package.Dte2.StatusBar.Text = $"Reverse engineer completed in {duration:h\\:mm\\:ss}";

                EnvDteHelper.ShowMessage(errors);

                if (revEngResult.EntityErrors.Count > 0)
                {
                    _package.LogError(revEngResult.EntityErrors, null);
                }
                if (revEngResult.EntityWarnings.Count > 0)
                {
                    _package.LogError(revEngResult.EntityWarnings, null);
                }
                Telemetry.TrackEvent("PowerTools.ReverseEngineer");
            }
            catch (AggregateException ae)
            {
                foreach (var innerException in ae.Flatten().InnerExceptions)
                {
                    _package.LogError(new List <string>(), innerException);
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
        public async System.Threading.Tasks.Task HandleComparisonAsync(string outputPath, Project project)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            try
            {
                if (await VSHelper.IsDebugModeAsync())
                {
                    VSHelper.ShowError(CompareLocale.CannotCompareContextToDatabaseWhileDebugging);
                    return;
                }

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

                if (await project.GetAttributeAsync("TargetFrameworkMoniker") == null)
                {
                    VSHelper.ShowError(SharedLocale.SelectedProjectTypeNoTargetFrameworkMoniker);
                    return;
                }

                if (!await project.IsNetCore31OrHigherAsync())
                {
                    VSHelper.ShowError($"{SharedLocale.SupportedFramework}: {await project.GetAttributeAsync("TargetFrameworkMoniker")}");
                    return;
                }

                var result = await project.ContainsEfSchemaCompareReferenceAsync();

                if (!result.Item1)
                {
                    if (!Version.TryParse(result.Item2, out Version version))
                    {
                        VSHelper.ShowError(string.Format(CultureInfo.InvariantCulture, CompareLocale.CannotSupportVersion, result.Item2));
                        return;
                    }

                    if (version.Major != 5 && version.Major != 6)
                    {
                        VSHelper.ShowError(CompareLocale.VersionSupported);
                        return;
                    }

                    var nugetHelper = new NuGetHelper();
                    if (version.Major == 6)
                    {
                        await nugetHelper.InstallPackageAsync("EfCore.SchemaCompare", project, new Version(6, 0, 0));
                    }
                    else if (version.Major == 5)
                    {
                        await nugetHelper.InstallPackageAsync("EfCore.SchemaCompare", project, new Version(5, 1, 3));
                    }

                    VSHelper.ShowError(CompareLocale.InstallingEfCoreSchemaCompare);
                    return;
                }

                await VS.StatusBar.ShowMessageAsync(CompareLocale.LoadingData);

                await VS.StatusBar.StartAnimationAsync(StatusAnimation.Build);

                var databaseList = vsDataHelper.GetDataConnections(package);
                var contextTypes = await GetDbContextTypesAsync(outputPath, project);

                var optionsDialog = package.GetView <ICompareOptionsDialog>();

                if (databaseList != null && databaseList.Any())
                {
                    optionsDialog.AddConnections(databaseList.Select(m => new DatabaseConnectionModel
                    {
                        ConnectionName   = m.Value.ConnectionName,
                        ConnectionString = m.Value.ConnectionString,
                        DatabaseType     = m.Value.DatabaseType,
                        DataConnection   = m.Value.DataConnection,
                    }));
                }

                optionsDialog.AddContextTypes(contextTypes);

                await VS.StatusBar.EndAnimationAsync(StatusAnimation.Build);

                await VS.StatusBar.ClearAsync();

                var pickDataSourceResult = optionsDialog.ShowAndAwaitUserResponse(true);
                if (!pickDataSourceResult.ClosedByOK)
                {
                    return;
                }

                if (!pickDataSourceResult.Payload.ContextTypes.Any())
                {
                    VSHelper.ShowError(CompareLocale.NoContextsSelected);
                    return;
                }

                pickDataSourceResult.Payload.Connection.DataConnection.Open();
                pickDataSourceResult.Payload.Connection.ConnectionString = DataProtection.DecryptString(pickDataSourceResult.Payload.Connection.DataConnection.EncryptedConnectionString);

                await VS.StatusBar.ShowMessageAsync(CompareLocale.ComparingDatabaseWithContexts);

                await VS.StatusBar.StartAnimationAsync(StatusAnimation.Build);

                var timer = new Stopwatch();
                timer.Start();
                var comparisonResult = await GetComparisonResultAsync(
                    outputPath,
                    project,
                    pickDataSourceResult.Payload.Connection,
                    pickDataSourceResult.Payload.ContextTypes.ToArray());

                timer.Stop();

                await VS.StatusBar.EndAnimationAsync(StatusAnimation.Build);

                await VS.StatusBar.ShowMessageAsync(string.Format(CompareLocale.CompareCompletedIn, timer.Elapsed.ToString("h\\:mm\\:ss")));

                if (comparisonResult.Any())
                {
                    var resultDialog = package.GetView <ICompareResultDialog>();
                    resultDialog.AddComparisonResult(comparisonResult);
                    resultDialog.ShowAndAwaitUserResponse(true);
                }
                else
                {
                    VSHelper.ShowMessage(CompareLocale.ContextDatabaseMatch);
                }

                await VS.StatusBar.ClearAsync();

                Telemetry.TrackEvent("PowerTools.Compare");
            }
            catch (AggregateException ae)
            {
                foreach (var innerException in ae.Flatten().InnerExceptions)
                {
                    package.LogError(new List <string>(), innerException);
                }
            }
            catch (Exception exception)
            {
                package.LogError(new List <string>(), exception);
            }
        }
        public async System.Threading.Tasks.Task GenerateAsync(string outputPath, Project project, GenerationType generationType)
        {
            try
            {
                if (string.IsNullOrEmpty(outputPath))
                {
                    throw new ArgumentException(outputPath, nameof(outputPath));
                }

                if (project.Properties.Item("TargetFrameworkMoniker") == null)
                {
                    EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker");
                    return;
                }

                if (!project.IsNetCore30OrHigher())
                {
                    EnvDteHelper.ShowError("Only .NET Core 3.0+ projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                    return;
                }

                var result = await project.ContainsEfCoreDesignReferenceAsync();

                if (string.IsNullOrEmpty(result.Item2))
                {
                    EnvDteHelper.ShowError("EF Core 3.1 or later not found in project");
                    return;
                }

                if (!result.Item1)
                {
                    if (!Version.TryParse(result.Item2, out Version version))
                    {
                        EnvDteHelper.ShowError($"Cannot support version {result.Item2}, notice that previews have limited supported. You can try to manually install Microsoft.EntityFrameworkCore.Design preview.");
                        return;
                    }
                    var nugetHelper = new NuGetHelper();
                    nugetHelper.InstallPackage("Microsoft.EntityFrameworkCore.Design", project, version);
                    EnvDteHelper.ShowError($"Installing EFCore.Design version {version}, please retry the command");
                    return;
                }

                var processLauncher = new ProcessLauncher(project);

                var processResult = await processLauncher.GetOutputAsync(outputPath, generationType, null);

                if (string.IsNullOrEmpty(processResult))
                {
                    throw new ArgumentException("Unable to collect model information", nameof(processResult));
                }

                if (processResult.StartsWith("Error:"))
                {
                    throw new ArgumentException(processResult, nameof(processResult));
                }

                var modelResult = processLauncher.BuildModelResult(processResult);

                switch (generationType)
                {
                case GenerationType.Dgml:
                    GenerateDgml(modelResult, project);
                    Telemetry.TrackEvent("PowerTools.GenerateModelDgml");
                    break;

                case GenerationType.Ddl:
                    var files = project.GenerateFiles(modelResult, ".sql");
                    foreach (var file in files)
                    {
                        _package.Dte2.ItemOperations.OpenFile(file);
                    }
                    Telemetry.TrackEvent("PowerTools.GenerateSqlCreate");
                    break;

                case GenerationType.DebugView:
                    var views = project.GenerateFiles(modelResult, ".txt");
                    foreach (var file in views)
                    {
                        _package.Dte2.ItemOperations.OpenFile(file);
                    }
                    Telemetry.TrackEvent("PowerTools.GenerateDebugView");
                    break;

                default:
                    break;
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }
        public void ReverseEngineerCodeFirst(Project project)
        {
            try
            {
                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                var startTime = DateTime.Now;

                // Show dialog with SqlClient selected by default
                var dialogFactory = _package.GetService <IVsDataConnectionDialogFactory>();
                var dialog        = dialogFactory.CreateConnectionDialog();
                dialog.AddAllSources();
                dialog.SelectedSource = new Guid("067ea0d9-ba62-43f7-9106-34930c60c528");
                var dialogResult = dialog.ShowDialog(connect: true);

                if (dialogResult != null)
                {
                    _package.Dte2.StatusBar.Text = "Loading schema information...";

                    // Find connection string and provider
                    var             connection       = (DbConnection)dialogResult.GetLockedProviderObject();
                    var             connectionString = connection.ConnectionString;
                    var             providerManager  = (IVsDataProviderManager)Package.GetGlobalService(typeof(IVsDataProviderManager));
                    IVsDataProvider dp;
                    providerManager.Providers.TryGetValue(dialogResult.Provider, out dp);
                    var providerInvariant = (string)dp.GetProperty("InvariantName");

                    var dbType = DatabaseType.SQLCE35;
                    if (providerInvariant == "System.Data.SqlServerCe.4.0")
                    {
                        dbType = DatabaseType.SQLCE40;
                    }
                    if (providerInvariant == "System.Data.SQLite.EF6")
                    {
                        dbType = DatabaseType.SQLite;
                    }
                    if (providerInvariant == "System.Data.SqlClient")
                    {
                        dbType = DatabaseType.SQLServer;
                    }

                    if (dbType == DatabaseType.SQLCE35)
                    {
                        EnvDteHelper.ShowError($"Unsupported provider: {providerInvariant}");
                        return;
                    }

                    var ptd = new PickTablesDialog {
                        IncludeTables = true
                    };
                    using (var repository = RepositoryHelper.CreateRepository(new DatabaseInfo {
                        ConnectionString = connectionString, DatabaseType = dbType
                    }))
                    {
                        ptd.Tables = repository.GetAllTableNamesForExclusion();
                    }

                    var res = ptd.ShowModal();
                    if (!res.HasValue || !res.Value)
                    {
                        return;
                    }

                    var classBasis = RepositoryHelper.GetClassBasis(connectionString, dbType);

                    var dteH   = new EnvDteHelper();
                    var revEng = new EfCoreReverseEngineer();

                    var model         = revEng.GenerateClassName(classBasis) + "Context";
                    var packageResult = dteH.ContainsEfCoreReference(project, dbType);

                    var modelDialog = new EfCoreModelDialog
                    {
                        InstallNuGetPackage = !packageResult.Item1,
                        ModelName           = model,
                        ProjectName         = project.Name,
                        NameSpace           = project.Properties.Item("DefaultNamespace").Value.ToString()
                    };

                    _package.Dte2.StatusBar.Text = "Getting options...";
                    var result = modelDialog.ShowModal();
                    if (!result.HasValue || result.Value != true)
                    {
                        return;
                    }

                    var projectPath = project.Properties.Item("FullPath").Value.ToString();

                    var options = new ReverseEngineerOptions
                    {
                        UseFluentApiOnly     = !modelDialog.UseDataAnnotations,
                        ConnectionString     = connectionString,
                        ContextClassName     = modelDialog.ModelName,
                        DatabaseType         = (EFCoreReverseEngineer.DatabaseType)dbType,
                        ProjectPath          = projectPath,
                        OutputPath           = modelDialog.OutputPath,
                        ProjectRootNamespace = modelDialog.NameSpace,
                        UseDatabaseNames     = modelDialog.UseDatabaseNames,
                        Tables = ptd.Tables
                    };

                    _package.Dte2.StatusBar.Text = "Generating code...";
                    var revEngResult = revEng.GenerateFiles(options);

                    if (modelDialog.SelectedTobeGenerated == 0 || modelDialog.SelectedTobeGenerated == 2)
                    {
                        foreach (var filePath in revEngResult.EntityTypeFilePaths)
                        {
                            project.ProjectItems.AddFromFile(filePath);
                        }
                    }
                    if (modelDialog.SelectedTobeGenerated == 0 || modelDialog.SelectedTobeGenerated == 1)
                    {
                        project.ProjectItems.AddFromFile(revEngResult.ContextFilePath);
                        _package.Dte2.ItemOperations.OpenFile(revEngResult.ContextFilePath);
                    }

                    packageResult = dteH.ContainsEfCoreReference(project, dbType);

                    var missingProviderPackage = packageResult.Item1 ? null : packageResult.Item2;
                    if (modelDialog.InstallNuGetPackage)
                    {
                        missingProviderPackage = null;
                    }

                    _package.Dte2.StatusBar.Text = "Reporting result...";
                    var errors = ReportRevEngErrors(revEngResult, missingProviderPackage);

                    if (modelDialog.InstallNuGetPackage)
                    {
                        _package.Dte2.StatusBar.Text = "Installing EF Core provider package";
                        var nuGetHelper = new NuGetHelper();
                        nuGetHelper.InstallPackage(packageResult.Item2, project);
                    }
                    var duration = DateTime.Now - startTime;
                    _package.Dte2.StatusBar.Text = $"Reverse engineer completed in {duration:h\\:mm\\:ss}";

                    EnvDteHelper.ShowMessage(errors);

                    if (revEngResult.EntityErrors.Count > 0)
                    {
                        _package.LogError(revEngResult.EntityErrors, null);
                    }
                    if (revEngResult.EntityWarnings.Count > 0)
                    {
                        _package.LogError(revEngResult.EntityWarnings, null);
                    }
                }
            }
            catch (Exception exception)
            {
                _package.LogError(new List <string>(), exception);
            }
        }