private void ReportRevEngErrors(EfCoreReverseEngineerResult revEngResult, string missingProviderPackage)
        {
            var errors = new StringBuilder();

            foreach (var entityError in revEngResult.EntityErrors)
            {
                errors.Append($"Table: {entityError.Key}{Environment.NewLine}");
                errors.Append($"Error: {entityError.Value}{Environment.NewLine}");
            }
            if (revEngResult.EntityErrors.Count == 0)
            {
                errors.Insert(0, "Model generated successfully." + Environment.NewLine);
            }
            else
            {
                errors.Insert(0, "The following issues were encountered:" + Environment.NewLine);
            }

            if (!string.IsNullOrEmpty(missingProviderPackage))
            {
                errors.AppendLine();
                errors.AppendFormat("The \"{0}\" NuGet package was not found in the project - it must be installed in order to build.", missingProviderPackage);
            }

            EnvDteHelper.ShowMessage(errors.ToString());
        }
Beispiel #2
0
        private DatabaseConnectionModel GetDatabaseInfo(ReverseEngineerOptions options)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var dbInfo = new DatabaseConnectionModel();

            if (!string.IsNullOrEmpty(options.ConnectionString))
            {
                dbInfo.ConnectionString = options.ConnectionString;
                dbInfo.DatabaseType     = options.DatabaseType;
            }

            if (!string.IsNullOrEmpty(options.Dacpac))
            {
                dbInfo.DatabaseType      = DatabaseType.SQLServerDacpac;
                dbInfo.ConnectionString  = $"Data Source=(local);Initial Catalog={Path.GetFileNameWithoutExtension(options.Dacpac)};Integrated Security=true;";
                options.ConnectionString = dbInfo.ConnectionString;
                options.DatabaseType     = dbInfo.DatabaseType;

                options.Dacpac = _package.Dte2.DTE.BuildSqlProj(options.Dacpac);
                if (string.IsNullOrEmpty(options.Dacpac))
                {
                    EnvDteHelper.ShowMessage(ReverseEngineerLocale.UnableToBuildSelectedDatabaseProject);
                    return(null);
                }
            }

            if (dbInfo.DatabaseType == DatabaseType.Undefined)
            {
                EnvDteHelper.ShowError($"{ReverseEngineerLocale.UnsupportedProvider}");
                return(null);
            }

            return(dbInfo);
        }
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            cmbDbContext.IsEnabled      = false;
            imgUnicorn.Opacity          = 0;
            txtMigrationName.Visibility = Visibility.Collapsed;
            lblMigration.Visibility     = Visibility.Collapsed;
            btnApply.Visibility         = Visibility.Collapsed;

            var image        = new Image();
            var thisassembly = Assembly.GetExecutingAssembly();
            var imageStream  = thisassembly.GetManifestResourceStream("EFCorePowerTools.Resources.Unicorn.png");
            var bmp          = BitmapFrame.Create(imageStream);

            image.Source           = bmp;
            imgUnicorn.ImageSource = image.Source;

            await GetMigrationStatus();

            if (cmbDbContext.Items.Count == 0)
            {
                EnvDteHelper.ShowMessage("No valid DbContext classes found in the current project");
                Close();
            }
            cmbDbContext.IsEnabled = true;
        }
 private void RuntimeMissing_Click(object sender, RoutedEventArgs e)
 {
     if (!DataConnectionHelper.IsV35Installed() && !DataConnectionHelper.IsV40Installed())
     {
         EnvDteHelper.ShowMessage("The SQL Server Compact 3.5 SP2 and 4.0 runtimes are not properly installed,\r\nso many features are not available,\r\ninstall or repair SQL Server Compact 3.5 SP2 or 4.0 Desktop to remedy");
     }
 }
        public void SyncFxDeprovisionDatabase(object sender, ExecutedRoutedEventArgs e)
        {
            var databaseInfo = ValidateMenuInfo(sender);

            if (databaseInfo == null)
            {
                return;
            }

            if (databaseInfo.DatabaseInfo.DatabaseType != DatabaseType.SQLCE35)
            {
                EnvDteHelper.ShowError("Sorry, only version 3.5 databases are supported for now");
                return;
            }
            if (!SyncFxHelper.IsProvisioned(databaseInfo.DatabaseInfo))
            {
                EnvDteHelper.ShowError("The database is not provisioned, cannot deprovision");
                return;
            }
            try
            {
                new SyncFxHelper().DeprovisionDatabase(databaseInfo.DatabaseInfo.ConnectionString);
                databaseInfo.ExplorerControl.RefreshTables(databaseInfo.DatabaseInfo);
                EnvDteHelper.ShowMessage("Database deprovisioned");
                DataConnectionHelper.LogUsage("DatabaseSyncDeprovision");
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false);
            }
        }
        private void AddButton_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                var info = EnvDteHelper.PromptForInfo(_package);
                if (info.DatabaseType == DatabaseType.SQLCE35)
                {
                    return;
                }

                var databaseList = EnvDteHelper.GetDataConnections(_package);
                comboBox1.DisplayMemberPath = "Value.Caption";
                comboBox1.ItemsSource       = databaseList;

                int i = 0;
                foreach (var item in databaseList)
                {
                    if (item.Key == info.ConnectionString)
                    {
                        comboBox1.SelectedIndex = i;
                    }
                    i++;
                }
            }

            catch (Exception exception)
            {
                EnvDteHelper.ShowMessage(exception.ToString());
            }
        }
        public void DropScope(object sender, ExecutedRoutedEventArgs e)
        {
            if (EnvDteHelper.ShowMessageBox("Do you really want to deprovision this scope?", Microsoft.VisualStudio.Shell.Interop.OLEMSGBUTTON.OLEMSGBUTTON_YESNO, Microsoft.VisualStudio.Shell.Interop.OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND, Microsoft.VisualStudio.Shell.Interop.OLEMSGICON.OLEMSGICON_WARNING) == System.Windows.Forms.DialogResult.No)
            {
                return;
            }

            var menuItem = sender as MenuItem;

            if (menuItem == null)
            {
                return;
            }
            var menuInfo = menuItem.CommandParameter as MenuCommandParameters;

            if (menuInfo == null)
            {
                return;
            }
            try
            {
                SyncFxHelper.DeprovisionSqlCeScope(menuInfo.DatabaseInfo.ConnectionString, menuInfo.Name);
                EnvDteHelper.ShowMessage("Scope deprovisioned");
                if (_parentWindow != null && _parentWindow.Content != null)
                {
                    ExplorerControl control = _parentWindow.Content as ExplorerControl;
                    control.BuildDatabaseTree();
                }
                Helpers.DataConnectionHelper.LogUsage("SyncScopeDrop");
            }
            catch (Exception ex)
            {
                Helpers.DataConnectionHelper.SendError(ex, menuInfo.DatabaseInfo.DatabaseType);
            }
        }
Beispiel #8
0
        private void OnItemContextMenuInvokeHandler(object sender, EventArgs e)
        {
            try
            {
                var menuCommand = sender as MenuCommand;

                if (menuCommand == null)
                {
                    return;
                }

                if (menuCommand.CommandID.ID == PkgCmdIDList.cmdidEdmMenuAbout)
                {
                    _aboutHandler.ShowDialog();
                    return;
                }

                if (_dte2.SelectedItems.Count != 1)
                {
                    return;
                }

                try
                {
                    Type systemContextType;
                    var  context = DiscoverUserContextType(out systemContextType);

                    if (context != null)
                    {
                        if (menuCommand.CommandID.ID == PkgCmdIDList.cmdidDebugView)
                        {
                            _modelAnalyzerHandler.GenerateDebugView(context);
                        }
                        else if (menuCommand.CommandID.ID == PkgCmdIDList.cmdidDgmlView)
                        {
                            _modelAnalyzerHandler.GenerateDgml(context);
                        }
                    }
                }
                catch (TargetInvocationException ex)
                {
                    var innerException = ex.InnerException;

                    var remoteStackTraceString =
                        typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic)
                        ?? typeof(Exception).GetField("remote_stack_trace", BindingFlags.Instance | BindingFlags.NonPublic);
                    remoteStackTraceString.SetValue(innerException, innerException.StackTrace + "$$RethrowMarker$$");

                    EnvDteHelper.ShowMessage("An error occurred: " + Environment.NewLine + innerException.ToString());
                }
            }
            catch (Exception ex)
            {
                EnvDteHelper.ShowMessage("An error occurred: " + Environment.NewLine + ex.ToString());
            }
        }
        public void SetPassword(object sender, ExecutedRoutedEventArgs e)
        {
            var databaseInfo = ValidateMenuInfo(sender);

            if (databaseInfo == null)
            {
                return;
            }
            try
            {
                var dbInfo = databaseInfo.DatabaseInfo;
                var pwd    = new PasswordDialog();
                pwd.ShowModal();
                if (!pwd.DialogResult.HasValue || !pwd.DialogResult.Value)
                {
                    return;
                }
                var helper = Helpers.RepositoryHelper.CreateEngineHelper(databaseInfo.DatabaseInfo.DatabaseType);
                var newConnectionString = helper.ChangeDatabasePassword(databaseInfo.DatabaseInfo.ConnectionString, pwd.Password);
                if (dbInfo.FromServerExplorer)
                {
                    var providerId = Resources.SqlCompact35Provider;
                    if (dbInfo.DatabaseType == DatabaseType.SQLCE40)
                    {
                        providerId = Resources.SqlCompact40Provider;
                    }
                    DataConnectionHelper.RemoveDataConnection(package, dbInfo.ConnectionString, new Guid(providerId));
                }
                else
                {
                    DataConnectionHelper.RemoveDataConnection(databaseInfo.DatabaseInfo.ConnectionString);
                }

                if (!string.IsNullOrEmpty(newConnectionString))
                {
                    DataConnectionHelper.SaveDataConnection(newConnectionString, dbInfo.DatabaseType, package);
                    EnvDteHelper.ShowMessage("Password was set, and connection updated");
                }
                else
                {
                    EnvDteHelper.ShowMessage("Password was set, but could not update connection, please reconnect the database");
                }

                var control = _parentWindow.Content as ExplorerControl;
                if (control != null)
                {
                    control.BuildDatabaseTree();
                }
                DataConnectionHelper.LogUsage("DatabaseMaintainSetPassword");
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false);
            }
        }
        public void SyncFxProvisionScope(object sender, ExecutedRoutedEventArgs e)
        {
            var databaseInfo = ValidateMenuInfo(sender);

            if (databaseInfo == null)
            {
                return;
            }

            if (databaseInfo.DatabaseInfo.DatabaseType != DatabaseType.SQLCE35)
            {
                EnvDteHelper.ShowError("Sorry, only version 3.5 databases are supported for now");
                return;
            }

            try
            {
                var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(databaseInfo.DatabaseInfo.Caption);
                if (fileNameWithoutExtension == null)
                {
                    return;
                }
                var model = fileNameWithoutExtension.Replace(" ", string.Empty).Replace("#", string.Empty).Replace(".", string.Empty).Replace("-", string.Empty);
                var sfd   = new SyncFxDialog {
                    ModelName = model
                };

                var res = sfd.ShowModal();

                if (!res.HasValue || res.Value != true || (sfd.Tables.Count <= 0))
                {
                    return;
                }
                if (SyncFxHelper.SqlCeScopeExists(databaseInfo.DatabaseInfo.ConnectionString, model))
                {
                    EnvDteHelper.ShowError("Scope name is already in use. Please enter a different scope name.");
                    return;
                }

                model = sfd.ModelName;
                new SyncFxHelper().ProvisionScope(databaseInfo.DatabaseInfo.ConnectionString, model, sfd.Columns.Where(c => sfd.Tables.Contains(c.TableName)).ToList());
                EnvDteHelper.ShowMessage("Scope: " + model + " has been provisioned.");
                DataConnectionHelper.LogUsage("DatabaseSyncProvision");
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false);
            }
        }
Beispiel #11
0
 private void button1_Click(object sender, RoutedEventArgs e)
 {
     if (string.IsNullOrEmpty(txtNameSpace.Text))
     {
         EnvDteHelper.ShowMessage("Namespace is required");
         return;
     }
     if (string.IsNullOrEmpty(textBox1.Text))
     {
         EnvDteHelper.ShowMessage("Context name is required");
         return;
     }
     DialogResult = true;
     Close();
 }
        public void SyncFxGenerateSnapshot(object sender, ExecutedRoutedEventArgs e)
        {
            var databaseInfo = ValidateMenuInfo(sender);

            if (databaseInfo == null)
            {
                return;
            }
            if (databaseInfo.DatabaseInfo.DatabaseType != DatabaseType.SQLCE35)
            {
                EnvDteHelper.ShowError("Sorry, only version 3.5 databases are supported for now");
                return;
            }
            if (!SyncFxHelper.IsProvisioned(databaseInfo.DatabaseInfo))
            {
                EnvDteHelper.ShowError("The database is not provisioned, cannot generate snapshots");
                return;
            }

            var fd = new SaveFileDialog
            {
                Title           = "Save generated snapshot database file as",
                Filter          = DataConnectionHelper.GetSqlCeFileFilter(),
                OverwritePrompt = true,
                ValidateNames   = true
            };
            var result = fd.ShowDialog();

            if (!result.HasValue || !result.Value)
            {
                return;
            }
            var fileName = fd.FileName;

            try
            {
                SyncFxHelper.GenerateSnapshot(databaseInfo.DatabaseInfo.ConnectionString, fileName);
                EnvDteHelper.ShowMessage("Database snapshot generated.");
                DataConnectionHelper.LogUsage("DatabaseSyncSnapshot");
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, DatabaseType.SQLCE35, false);
            }
        }
Beispiel #13
0
        public void CheckCeVersion(object sender, ExecutedRoutedEventArgs e)
        {
            var helper = Helpers.RepositoryHelper.CreateEngineHelper(DatabaseType.SQLCE40);
            var ofd    = new OpenFileDialog();

            ofd.Filter          = DataConnectionHelper.GetSqlCeFileFilter();
            ofd.CheckFileExists = true;
            ofd.Multiselect     = false;
            ofd.ValidateNames   = true;
            if (ofd.ShowDialog() == true)
            {
                try
                {
                    var    sdfVersion = helper.DetermineVersion(ofd.FileName);
                    string found;
                    switch (sdfVersion)
                    {
                    case SQLCEVersion.SQLCE20:
                        found = "2.0";
                        break;

                    case SQLCEVersion.SQLCE30:
                        found = "3.0/3.1";
                        break;

                    case SQLCEVersion.SQLCE35:
                        found = "3.5";
                        break;

                    case SQLCEVersion.SQLCE40:
                        found = "4.0";
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    EnvDteHelper.ShowMessage(string.Format("{0} is SQL Server Compact version {1}", Path.GetFileName(ofd.FileName), found));
                    DataConnectionHelper.LogUsage("DatabaseVersionDetect");
                }
                catch (Exception ex)
                {
                    EnvDteHelper.ShowError(ex.Message);
                }
            }
        }
        private void VerifySQLServerRightsAndVersion(ReverseEngineerOptions options)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            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.");
                }
            }
        }
        private void VerifySQLServerRightsAndVersion(ReverseEngineerOptions options)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

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

                if (rightsAndVersion.Item1 == false)
                {
                    EnvDteHelper.ShowMessage(ReverseEngineerLocale.SqlServerNoViewDefinitionRights);
                }

                if (rightsAndVersion.Item2.Major < 11)
                {
                    EnvDteHelper.ShowMessage(String.Format(ReverseEngineerLocale.SQLServerVersionNotSupported, rightsAndVersion.Item2));
                }
            }
        }
        private DatabaseInfo GetDatabaseInfo(ReverseEngineerOptions options)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            DatabaseInfo dbInfo = new DatabaseInfo();

            if (!string.IsNullOrEmpty(options.ConnectionString))
            {
                dbInfo.ConnectionString = options.ConnectionString;
                dbInfo.DatabaseType     = options.DatabaseType;
            }

            if (!string.IsNullOrEmpty(options.Dacpac))
            {
                dbInfo.DatabaseType = DatabaseType.SQLServerDacpac;
                if (options.Dacpac.EndsWith(".edmx", StringComparison.OrdinalIgnoreCase))
                {
                    dbInfo.DatabaseType = DatabaseType.Edmx;
                }
                dbInfo.ConnectionString  = $"Data Source=(local);Initial Catalog={Path.GetFileNameWithoutExtension(options.Dacpac)};Integrated Security=true;";
                options.ConnectionString = dbInfo.ConnectionString;
                options.DatabaseType     = dbInfo.DatabaseType;

                options.Dacpac = _package.Dte2.DTE.BuildSqlProj(options.Dacpac);
                if (string.IsNullOrEmpty(options.Dacpac))
                {
                    EnvDteHelper.ShowMessage(ReverseEngineerLocale.UnableToBuildSelectedDatabaseProject);
                    return(null);
                }
            }

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

            return(dbInfo);
        }
Beispiel #17
0
        private void TestConnection(bool showMessage)
        {
            if (string.IsNullOrWhiteSpace(_builder.DataSource))
            {
                return;
            }
            try
            {
                if (_createDb)
                {
                    if (!System.IO.File.Exists(_builder.DataSource))
                    {
                        var engineHelper = DataConnectionHelper.CreateEngineHelper(DatabaseType.SQLite);
                        engineHelper.CreateDatabase(_builder.ConnectionString);
                    }
                }

                using (var conn = new SQLiteConnection(_builder.ConnectionString))
                {
                    conn.Open();
                    ConnectionString = _builder.ConnectionString;
                    if (showMessage)
                    {
                        EnvDteHelper.ShowMessage("Test succeeded!");
                    }
                    else
                    {
                        DialogResult = true;
                    }
                }
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, DatabaseType.SQLite, false);
            }
        }
        public void GenerateModelCodeInProject(object sender, ExecutedRoutedEventArgs e)
        {
            var databaseInfo = ValidateMenuInfo(sender);

            if (databaseInfo == null)
            {
                return;
            }

            if (package == null)
            {
                return;
            }
            var dte = package.GetServiceHelper(typeof(DTE)) as DTE;

            var dteH = new EnvDteHelper();

            var project = dteH.GetProject(dte);

            if (project == null)
            {
                EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the DataAccess.cs to be placed");
                return;
            }
            if (!dteH.AllowedProjectKinds.Contains(new Guid(project.Kind)))
            {
                EnvDteHelper.ShowError(string.Format("The selected project type {0} does not support sqlite-net (please let me know if I am wrong)", project.Kind));
                return;
            }
            if (project.CodeModel != null && project.CodeModel.Language != CodeModelLanguageConstants.vsCMLanguageCSharp)
            {
                EnvDteHelper.ShowError("Unsupported code language, only C# is currently supported");
                return;
            }
            if (databaseInfo.DatabaseInfo.DatabaseType != DatabaseType.SQLite)
            {
                EnvDteHelper.ShowError("Sorry, only SQLite databases are supported");
                return;
            }
            try
            {
                var defaultNamespace = "Model";
                if (project.Properties.Item("DefaultNamespace") != null)
                {
                    defaultNamespace = project.Properties.Item("DefaultNamespace").Value.ToString();
                }
                var projectPath = project.Properties.Item("FullPath").Value.ToString();
                using (var repository = Helpers.RepositoryHelper.CreateRepository(databaseInfo.DatabaseInfo))
                {
                    var generator = DataConnectionHelper.CreateGenerator(repository, databaseInfo.DatabaseInfo.DatabaseType);
                    generator.GenerateSqliteNetModel(defaultNamespace);

                    var fileName = Path.Combine(projectPath, "DataAccess.cs");
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                    var warning = @"//This code was generated by a tool.
//Changes to this file will be lost if the code is regenerated."
                                  + Environment.NewLine +
                                  "// See the blog post here for help on using the generated code: http://erikej.blogspot.dk/2014/10/database-first-with-sqlite-in-universal.html"
                                  + Environment.NewLine;

                    File.WriteAllText(fileName, warning + generator.GeneratedScript);
                    project.ProjectItems.AddFromFile(fileName);
                    EnvDteHelper.ShowMessage("DataAccess.cs generated.");
                    DataConnectionHelper.LogUsage("DatabaseSqliteNetCodegen");
                }
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType);
            }
        }
 private bool TestConnection(bool showMessage)
 {
     try
     {
         if (_createDb)
         {
             if (!System.IO.File.Exists(dataSourceTextBox.Text))
             {
                 var engineHelper = Helpers.RepositoryHelper.CreateEngineHelper(DbType);
                 engineHelper.CreateDatabase(_connectionString);
             }
         }
         using (Helpers.RepositoryHelper.CreateRepository(new DatabaseInfo {
             ConnectionString = _connectionString, DatabaseType = DbType
         }))
         {
             if (showMessage)
             {
                 EnvDteHelper.ShowMessage("Connection OK!");
             }
             else
             {
                 DialogResult = true;
             }
         }
         return(true);
     }
     catch (Exception ex)
     {
         if (ex.Message.Contains("Please upgrade using SqlCeEngine.Upgrade() method") && DbType == DatabaseType.SQLCE40)
         {
             if (EnvDteHelper.ShowMessageBox("This database file is from an earlier version,\n\rwould you like to Upgrade it?\n\r(A copy of the original file will be named .bak)"
                                             , Microsoft.VisualStudio.Shell.Interop.OLEMSGBUTTON.OLEMSGBUTTON_YESNO
                                             , Microsoft.VisualStudio.Shell.Interop.OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND
                                             , Microsoft.VisualStudio.Shell.Interop.OLEMSGICON.OLEMSGICON_WARNING) == System.Windows.Forms.DialogResult.Yes)
             {
                 var bakFile = dataSourceTextBox.Text + ".bak";
                 var go      = true;
                 try
                 {
                     if (System.IO.File.Exists(bakFile))
                     {
                         if (EnvDteHelper.ShowMessageBox(string.Format("{0} already exists, do you wish to overwrite it?", bakFile)
                                                         , Microsoft.VisualStudio.Shell.Interop.OLEMSGBUTTON.OLEMSGBUTTON_YESNO
                                                         , Microsoft.VisualStudio.Shell.Interop.OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND
                                                         , Microsoft.VisualStudio.Shell.Interop.OLEMSGICON.OLEMSGICON_WARNING) == System.Windows.Forms.DialogResult.Yes)
                         {
                             System.IO.File.Delete(bakFile);
                         }
                         else
                         {
                             go = false;
                         }
                     }
                     if (go)
                     {
                         System.IO.File.Copy(dataSourceTextBox.Text, dataSourceTextBox.Text + ".bak");
                         var helper = new SqlCeScripting.SqlCeHelper4();
                         helper.UpgradeTo40(_connectionString);
                         DialogResult = true;
                     }
                 }
                 catch (Exception ex2)
                 {
                     DataConnectionHelper.SendError(ex2, DbType, false);
                     return(false);
                 }
             }
         }
         else
         {
             DataConnectionHelper.SendError(ex, DbType, false);
             return(false);
         }
     }
     return(true);
 }
        public void GenerateEfPocoInProject(object sender, ExecutedRoutedEventArgs e)
        {
            EnvDteHelper.LaunchUrl("https://github.com/ErikEJ/SqlCeToolbox/wiki/EntityFramework-Reverse-POCO-Code-First-Generator");

            var databaseInfo = ValidateMenuInfo(sender);

            if (databaseInfo == null)
            {
                return;
            }

            var isEf6 = SqlCeToolboxPackage.VsSupportsEf6();

            try
            {
                if (package == null)
                {
                    return;
                }
                var dte = package.GetServiceHelper(typeof(DTE)) as DTE;
                if (dte == null)
                {
                    return;
                }
                if (dte.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                var dteH = new EnvDteHelper();

                var project = dteH.GetProject(dte);
                if (project == null)
                {
                    EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the code to be placed");
                    return;
                }
                if (dte.Solution.SolutionBuild.BuildState == vsBuildState.vsBuildStateNotStarted)
                {
                    EnvDteHelper.ShowError("Please build the project before proceeding");
                    return;
                }
                if (isEf6)
                {
                    if (databaseInfo.DatabaseInfo.DatabaseType == DatabaseType.SQLCE40 && !dteH.ContainsEfSqlCeReference(project))
                    {
                        EnvDteHelper.ShowError("Please add the EntityFramework.SqlServerCompact NuGet package to the project");
                        return;
                    }
                    if (databaseInfo.DatabaseInfo.DatabaseType == DatabaseType.SQLCE35 && !dteH.ContainsEfSqlCeLegacyReference(project))
                    {
                        EnvDteHelper.ShowError("Please add the EntityFramework.SqlServerCompact.Legacy NuGet package to the project");
                        return;
                    }
                    if (!File.Exists(Path.Combine(dteH.GetVisualStudioInstallationDir(SqlCeToolboxPackage.VisualStudioVersion), "ItemTemplates\\CSharp\\Data\\1033\\DbCtxCSEF6\\CSharpDbContext.Context.tt")))
                    {
                        EnvDteHelper.ShowError("Please install the Entity Framework 6 Tools in order to proceed");
                        return;
                    }
                }
                if (!dteH.AllowedProjectKinds.Contains(new Guid(project.Kind)))
                {
                    EnvDteHelper.ShowError("The selected project type does not support Entity Framework (please let me know if I am wrong)");
                    return;
                }

                if (project.Properties.Item("TargetFrameworkMoniker") == null)
                {
                    EnvDteHelper.ShowError("The selected project type does not have a TargetFrameworkMoniker");
                    return;
                }
                if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework"))
                {
                    EnvDteHelper.ShowError("The selected project type does not support .NET Desktop - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                    return;
                }

                var dte2 = (DTE2)package.GetServiceHelper(typeof(DTE));
                // ReSharper disable once SuspiciousTypeConversion.Global
                var solution2 = dte2.Solution as Solution2;

                if (solution2 != null)
                {
                    var projectItemTemplate = solution2.GetProjectItemTemplate("EntityFramework Reverse POCO Code First Generator", "CSharp");
                    if (!string.IsNullOrEmpty(projectItemTemplate))
                    {
                        project.ProjectItems.AddFromTemplate(projectItemTemplate, "Database.tt");
                    }
                }
                DataConnectionHelper.LogUsage("DatabaseCreateEFPOCO");
            }
            // EDM end
            catch (Exception ex)
            {
                if (ex.GetType() == typeof(FileNotFoundException))
                {
                    EnvDteHelper.ShowMessage("Unable to find the EF Reverse POCO Template, is it installed?");
                }
                else
                {
                    DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false);
                }
            }
        }
        public void ScriptDatabase(object sender, ExecutedRoutedEventArgs e)
        {
            var menuItem = sender as MenuItem;

            if (menuItem == null)
            {
                return;
            }
            var scope = (Scope)menuItem.Tag;

            var databaseInfo = ValidateMenuInfo(sender);

            if (databaseInfo == null)
            {
                return;
            }

            try
            {
                int totalCount;
                var ptd = new PickTablesDialog();
                using (var repository = Helpers.RepositoryHelper.CreateRepository(databaseInfo.DatabaseInfo))
                {
                    ptd.Tables = repository.GetAllTableNamesForExclusion();
                    totalCount = ptd.Tables.Count;
                }

                var res = ptd.ShowModal();
                if (res == true && (ptd.Tables.Count < totalCount))
                {
                    var fd = new SaveFileDialog
                    {
                        Title  = "Save generated script as",
                        Filter =
                            "SQL Server Compact Script (*.sqlce)|*.sqlce|SQL Server Script (*.sql)|*.sql|All Files(*.*)|*.*"
                    };
                    if (scope == Scope.SchemaDataSQLite || scope == Scope.SchemaSQLite || databaseInfo.DatabaseInfo.DatabaseType == DatabaseType.SQLite)
                    {
                        fd.Filter = "SQLite Script (*.sql)|*.sql|All Files(*.*)|*.*";
                    }
                    fd.OverwritePrompt = true;
                    fd.ValidateNames   = true;
                    var result = fd.ShowDialog();
                    if (!result.HasValue || result.Value != true)
                    {
                        return;
                    }
                    using (var repository = Helpers.RepositoryHelper.CreateRepository(databaseInfo.DatabaseInfo))
                    {
                        var generator = DataConnectionHelper.CreateGenerator(repository, fd.FileName, databaseInfo.DatabaseInfo.DatabaseType);
                        generator.ExcludeTables(ptd.Tables);
                        EnvDteHelper.ShowMessage(generator.ScriptDatabaseToFile(scope));
                        DataConnectionHelper.LogUsage("DatabaseScriptCe");
                    }
                }
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false);
            }
        }
Beispiel #22
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);
            }
        }
Beispiel #23
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 #24
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);
            }
        }
        private void HandleShowMessageBoxMessage(ShowMessageBoxMessage msg)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            EnvDteHelper.ShowMessage(msg.Content);
        }
Beispiel #26
0
 private void DDEXButton_Click(object sender, RoutedEventArgs e)
 {
     DataConnectionHelper.RegisterDdexProviders(true);
     EnvDteHelper.ShowMessage("Providers registered, you may have to restart Visual Studio");
 }
Beispiel #27
0
        private async System.Threading.Tasks.Task GenerateFilesAsync(Project project, ReverseEngineerOptions options, Tuple <bool, string> containsEfCoreReference)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var startTime = DateTime.Now;

            if (options.UseHandleBars)
            {
                var dropped = (DropTemplates(options.ProjectPath, options.CodeGenerationMode == CodeGenerationMode.EFCore5));
                if (dropped)
                {
                    project.ProjectItems.AddFromDirectory(Path.Combine(options.ProjectPath, "CodeTemplates"));
                }
            }

            options.UseNullableReferences = project.IsNetFramework() ? false : options.UseNullableReferences;

            _package.Dte2.StatusBar.Animate(true, _icon);
            _package.Dte2.StatusBar.Text = ReverseEngineerLocale.GeneratingCode;
            var revEngResult = await EfRevEngLauncher.LaunchExternalRunnerAsync(options, options.CodeGenerationMode);

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

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

            if (options.SelectedToBeGenerated == 0 || options.SelectedToBeGenerated == 2)
            {
                if (!project.IsNetCore31OrHigher() && !isNetStandard)
                {
                    foreach (var filePath in revEngResult.EntityTypeFilePaths)
                    {
                        project.ProjectItems.AddFromFile(filePath);
                    }
                }
            }

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

                    project.ProjectItems.AddFromFile(revEngResult.ContextFilePath);
                }

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

            var duration = DateTime.Now - startTime;

            var missingProviderPackage = containsEfCoreReference.Item1 ? null : containsEfCoreReference.Item2;

            if (options.InstallNuGetPackage || options.SelectedToBeGenerated == 2)
            {
                missingProviderPackage = null;
            }

            _package.Dte2.StatusBar.Text = ReverseEngineerLocale.ReportingResult;
            var errors = reverseEngineerHelper.ReportRevEngErrors(revEngResult, missingProviderPackage);

            _package.Dte2.StatusBar.Text = String.Format(ReverseEngineerLocale.ReverseEngineerCompleted, duration.ToString("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);
            }
        }
Beispiel #28
0
        public void SyncFxGenerateLocalDatabaseCacheCode(object sender, ExecutedRoutedEventArgs e)
        {
            // http://www.mztools.com/articles/2007/MZ2007011.aspx
            var menuItem = sender as MenuItem;

            if (menuItem == null)
            {
                return;
            }
            var dte     = _package.GetServiceHelper(typeof(DTE)) as DTE;
            var dteH    = new EnvDteHelper();
            var project = dteH.GetProject(dte);

            if (project == null)
            {
                EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the SyncFx classes to be placed");
                return;
            }
            if (!dteH.AllowedProjectKinds.Contains(new Guid(project.Kind)))
            {
                EnvDteHelper.ShowError("The selected project type does not support Sync Framework (please let me know if I am wrong)");
                return;
            }
            if (project.CodeModel.Language != CodeModelLanguageConstants.vsCMLanguageCSharp)
            {
                EnvDteHelper.ShowError("Unsupported code language, only C# is currently supported");
                return;
            }
            if (project.Properties.Item("TargetFrameworkMoniker") == null)
            {
                EnvDteHelper.ShowError("The selected project type does not support Sync Framework - missing TargetFrameworkMoniker");
                return;
            }
            if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework"))
            {
                EnvDteHelper.ShowError("The selected project type does not support .NET Desktop - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                return;
            }

            try
            {
                var serverConnectionString = DataConnectionHelper.PromptForConnectionString(_package);
                if (string.IsNullOrEmpty(serverConnectionString))
                {
                    return;
                }
                string clientConnectionString;

                //grab target SQL CE Database
                var dialog = new ConnectionDialog();
                dialog.DbType = DatabaseType.SQLCE35;
                var result = dialog.ShowModal();
                if (result.HasValue && result.Value && !string.IsNullOrWhiteSpace(dialog.ConnectionString))
                {
                    clientConnectionString = dialog.ConnectionString;
                }
                else
                {
                    return;
                }

                var model        = string.Empty;
                var sfd          = new SyncFxDialog();
                var databaseInfo = new DatabaseMenuCommandParameters
                {
                    DatabaseInfo = new DatabaseInfo
                    {
                        ConnectionString = serverConnectionString,
                        DatabaseType     = DatabaseType.SQLServer
                    }
                };
                SyncFxGetObjectsForSync(sfd, databaseInfo);
                sfd.ModelName = model;

                var res = sfd.ShowModal();
                if (res.HasValue && res.Value && (sfd.Tables.Count > 0) && !string.IsNullOrWhiteSpace(sfd.ModelName))
                {
                    model = sfd.ModelName;
                    var defaultNamespace = project.Properties.Item("DefaultNamespace").Value.ToString();

                    var columns     = sfd.Columns.Where(c => sfd.Tables.Contains(c.TableName)).ToList();
                    var classes     = new SyncFxHelper().GenerateCodeForScope(serverConnectionString, clientConnectionString, "SQL", model, columns, defaultNamespace);
                    var projectPath = project.Properties.Item("FullPath").Value.ToString();

                    foreach (var item in classes)
                    {
                        var fileName = Path.Combine(projectPath, item.Key + ".cs");
                        if (File.Exists(fileName))
                        {
                            File.Delete(fileName);
                        }
                        File.WriteAllText(fileName, item.Value);
                        project.ProjectItems.AddFromFile(fileName);
                    }
                    //Adding references - http://blogs.msdn.com/b/murat/archive/2008/07/30/envdte-adding-a-refernce-to-a-project.aspx
                    EnvDteHelper.AddReference(project, "System.Data.SqlServerCe, Version=3.5.1.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");

                    EnvDteHelper.AddReference(project, "Microsoft.Synchronization, Version=2.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                    EnvDteHelper.AddReference(project, "Microsoft.Synchronization.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                    EnvDteHelper.AddReference(project, "Microsoft.Synchronization.Data.SqlServer, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                    EnvDteHelper.AddReference(project, "Microsoft.Synchronization.Data.SqlServerCe, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                    EnvDteHelper.ShowMessage("Scope: " + model + " code generated.");
                    DataConnectionHelper.LogUsage("DatabasesSyncAddLocalDBCache");
                }
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, DatabaseType.SQLServer);
            }
        }
        private void GenerateFiles(Project project, ReverseEngineerOptions options, Tuple <bool, string> containsEfCoreReference)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var startTime = DateTime.Now;

            if (options.UseHandleBars)
            {
                var dropped = (DropTemplates(options.ProjectPath, options.CodeGenerationMode == CodeGenerationMode.EFCore5));
                if (dropped)
                {
                    project.ProjectItems.AddFromDirectory(Path.Combine(options.ProjectPath, "CodeTemplates"));
                }
            }

            options.UseNullableReferences = project.IsNetFramework() ? false : options.UseNullableReferences;

            _package.Dte2.StatusBar.Animate(true, _icon);
            _package.Dte2.StatusBar.Text = ReverseEngineerLocale.GeneratingCode;
            var revEngResult = EfRevEngLauncher.LaunchExternalRunner(options, options.CodeGenerationMode == CodeGenerationMode.EFCore5);

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

            if (options.SelectedToBeGenerated == 0 || options.SelectedToBeGenerated == 2)
            {
                foreach (var filePath in revEngResult.EntityTypeFilePaths)
                {
                    project.ProjectItems.AddFromFile(filePath);
                }
            }

            if (options.SelectedToBeGenerated == 0 || options.SelectedToBeGenerated == 1)
            {
                foreach (var filePath in revEngResult.ContextConfigurationFilePaths)
                {
                    project.ProjectItems.AddFromFile(filePath);
                }

                project.ProjectItems.AddFromFile(revEngResult.ContextFilePath);

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

            var duration = DateTime.Now - startTime;

            var missingProviderPackage = containsEfCoreReference.Item1 ? null : containsEfCoreReference.Item2;

            if (options.InstallNuGetPackage || options.SelectedToBeGenerated == 2)
            {
                missingProviderPackage = null;
            }

            _package.Dte2.StatusBar.Text = ReverseEngineerLocale.ReportingResult;
            var errors = reverseEngineerHelper.ReportRevEngErrors(revEngResult, missingProviderPackage);

            _package.Dte2.StatusBar.Text = String.Format(ReverseEngineerLocale.ReverseEngineerCompleted, duration.ToString("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);
            }
        }
        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);
            }
        }