private async Task GetMigrationStatus() { try { StartAnimation(); _package.Dte2.StatusBar.Text = "Getting Migration Status"; if (_project.TryBuild()) { var processResult = await _processLauncher.GetOutputAsync(_outputPath, _isNetCore, GenerationType.MigrationStatus, null); ReportStatus(processResult); } else { EnvDteHelper.ShowError("Build failed"); } } catch (Exception ex) { EnvDteHelper.ShowError(ex.ToString()); } finally { _package.Dte2.StatusBar.Text = string.Empty; StopAnimation(); } }
private void SaveOptions(Project project, string optionsPath, ReverseEngineerOptions options, Tuple <List <Schema>, string> renamingOptions) { ThreadHelper.ThrowIfNotOnUIThread(); if (File.Exists(optionsPath) && File.GetAttributes(optionsPath).HasFlag(FileAttributes.ReadOnly)) { EnvDteHelper.ShowError($"Unable to save options, the file is readonly: {optionsPath}"); return; } if (!File.Exists(optionsPath + ".ignore")) { File.WriteAllText(optionsPath, options.Write(), Encoding.UTF8); project.ProjectItems.AddFromFile(optionsPath); } if (renamingOptions.Item1 != null && !File.Exists(renamingOptions.Item2 + ".ignore") && renamingOptions.Item1.Count() > 0) { if (File.Exists(renamingOptions.Item2) && File.GetAttributes(renamingOptions.Item2).HasFlag(FileAttributes.ReadOnly)) { EnvDteHelper.ShowError($"Unable to save renaming options, the file is readonly: {renamingOptions.Item2}"); return; } File.WriteAllText(renamingOptions.Item2, CustomNameOptionsExtensions.Write(renamingOptions.Item1), Encoding.UTF8); project.ProjectItems.AddFromFile(renamingOptions.Item2); } }
internal void LogError(List <string> statusMessages, Exception exception) { ThreadHelper.JoinableTaskFactory.Run(async delegate { // Switch to main thread await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); _dte2.StatusBar.Text = "An error occurred. See the Output window for details."; try { var buildOutputWindow = _dte2.ToolWindows.OutputWindow.OutputWindowPanes.Item("Build"); buildOutputWindow.OutputString(Environment.NewLine); foreach (var error in statusMessages) { buildOutputWindow.OutputString(error + Environment.NewLine); } if (exception != null) { buildOutputWindow.OutputString(exception + Environment.NewLine); } buildOutputWindow.Activate(); } catch { EnvDteHelper.ShowError(exception.ToString()); } }); }
public async System.Threading.Tasks.Task ManageMigrationsAsync(string outputPath, Project project) { try { if (string.IsNullOrEmpty(outputPath)) { throw new ArgumentException(outputPath, nameof(outputPath)); } if (project == null) { throw new ArgumentNullException(nameof(project)); } if (project.Properties.Item("TargetFrameworkMoniker") == null) { EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker"); return; } if (!project.IsNetCore30OrHigher()) { EnvDteHelper.ShowError("Only .NET Core 3.0+ projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value); return; } var outputFolder = Path.GetDirectoryName(outputPath); var result = await project.ContainsEfCoreDesignReferenceAsync(); if (string.IsNullOrEmpty(result.Item2)) { EnvDteHelper.ShowError("EF Core 3.1 or later not found in project"); return; } if (!result.Item1) { if (!Version.TryParse(result.Item2, out Version version)) { EnvDteHelper.ShowError($"Cannot support version {version}, notice that previews are not supported."); return; } var nugetHelper = new NuGetHelper(); nugetHelper.InstallPackage("Microsoft.EntityFrameworkCore.Design", project, version); EnvDteHelper.ShowError($"Installing EFCore.Design version {version}, please retry the command"); return; } var migrationsDialog = _package.GetView <IMigrationOptionsDialog>(); migrationsDialog.UseProjectForMigration(project) .UseOutputPath(outputPath); migrationsDialog.ShowAndAwaitUserResponse(true); } catch (Exception exception) { _package.LogError(new List <string>(), exception); } }
public void GenerateServerDgmlFiles() { ThreadHelper.ThrowIfNotOnUIThread(); EnvDteHelper.ShowError("This feature is no longer supported, install SQLite Toolbox to get it back."); return; }
private bool SaveSettings() { try { TableName = txtTableDesc.Text; if (string.IsNullOrEmpty(TableName)) { EnvDteHelper.ShowError("Table name is required"); return(false); } var validation = TableColumn.ValidateColumns(_columns.ToList()); if (!string.IsNullOrEmpty(validation)) { EnvDteHelper.ShowError(validation); return(false); } TableColumns = TableColumn.BuildColumns(_columns.ToList(), TableName); PkScript = TableColumn.BuildPkScript(_columns.ToList(), TableName); PkScript = _dbType == DatabaseType.SQLite ? BuildSqLitePkScript(_columns.ToList(), TableName) : TableColumn.BuildPkScript(_columns.ToList(), TableName); return(true); } catch (Exception ex) { DataConnectionHelper.SendError(ex, DatabaseType.SQLServer); } return(false); }
public void AddCe40Database(object sender, ExecutedRoutedEventArgs e) { // http://www.mztools.com/articles/2007/MZ2007011.aspx if (!DataConnectionHelper.DdexProviderIsInstalled(new Guid(Resources.SqlCompact40Provider))) { EnvDteHelper.ShowError("The version 4.0 Visual Studio DDEX provider is not installed, cannot add connection"); return; } try { var objIVsDataConnectionDialogFactory = _package.GetServiceHelper(typeof(IVsDataConnectionDialogFactory)) as IVsDataConnectionDialogFactory; if (objIVsDataConnectionDialogFactory != null) { var objIVsDataConnectionDialog = objIVsDataConnectionDialogFactory.CreateConnectionDialog(); objIVsDataConnectionDialog.AddAllSources(); objIVsDataConnectionDialog.SelectedSource = new Guid("34A4B3E8-C54D-466F-92EA-E5814B97CA43"); objIVsDataConnectionDialog.SelectedProvider = new Guid(Resources.SqlCompact40Provider); if (objIVsDataConnectionDialog.ShowDialog() && objIVsDataConnectionDialog.SelectedProvider == new Guid(Resources.SqlCompact40Provider)) { DataConnectionHelper.SaveDataConnection(_package, objIVsDataConnectionDialog.EncryptedConnectionString, objIVsDataConnectionDialog.DisplayConnectionString, DatabaseType.SQLCE40, new Guid(Resources.SqlCompact40Provider)); var control = _parentWindow.Content as ExplorerControl; control?.BuildDatabaseTree(); DataConnectionHelper.LogUsage("DatabasesAddCe40Database"); } objIVsDataConnectionDialog.Dispose(); } } catch (Exception ex) { DataConnectionHelper.SendError(ex, DatabaseType.SQLCE40, false); } }
public async System.Threading.Tasks.Task ReverseEngineerCodeFirstAsync(Project project) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); 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(); if (optionsPaths.Count > 1) { var pcd = _package.GetView <IPickConfigDialog>(); pcd.PublishConfigurations(optionsPaths.Select(m => new ConfigModel { ConfigPath = m, ProjectPath = projectPath })); var pickConfigResult = pcd.ShowAndAwaitUserResponse(true); if (!pickConfigResult.ClosedByOK) { return; } optionsPath = pickConfigResult.Payload.ConfigPath; } await ReverseEngineerCodeFirstAsync(project, optionsPath, false); }
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 GenerateDgml(List <Tuple <string, string> > modelResult, Project project) { var dgmlBuilder = new DgmlBuilder.DgmlBuilder(); ProjectItem item = null; foreach (var info in modelResult) { var dgmlText = dgmlBuilder.Build(info.Item2, info.Item1, GetTemplate()); if (info.Item1.IndexOfAny(Path.GetInvalidPathChars()) >= 0 || info.Item1.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { EnvDteHelper.ShowError("Invalid name: " + info.Item1); return; } var path = Path.Combine(Path.GetTempPath(), info.Item1 + ".dgml"); File.WriteAllText(path, dgmlText, Encoding.UTF8); item = project.ProjectItems.GetItem(Path.GetFileName(path)); if (item != null) { item.Delete(); } item = project.ProjectItems.AddFromFileCopy(path); } if (item != null) { var window = item.Open(); window.Document.Activate(); } }
public static List <string> GenerateFiles(this Project project, List <Tuple <string, string> > result, string extension) { ThreadHelper.ThrowIfNotOnUIThread(); var list = new List <string>(); foreach (var item in result) { if (item.Item1.IndexOfAny(Path.GetInvalidPathChars()) >= 0 || item.Item1.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { EnvDteHelper.ShowError($"{SharedLocale.InvalidName}: {item.Item1}"); return(list); } var filePath = Path.Combine(Path.GetTempPath(), item.Item1 + extension); if (File.Exists(filePath)) { File.SetAttributes(filePath, FileAttributes.Normal); } File.WriteAllText(filePath, item.Item2); File.SetAttributes(filePath, FileAttributes.ReadOnly); list.Add(filePath); } return(list); }
public async System.Threading.Tasks.Task ManageMigrationsAsync(string outputPath, Project project) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { if (string.IsNullOrEmpty(outputPath)) { throw new ArgumentException(outputPath, nameof(outputPath)); } if (project == null) { throw new ArgumentNullException(nameof(project)); } if (project.Properties.Item("TargetFrameworkMoniker") == null) { EnvDteHelper.ShowError(SharedLocale.SelectedProjectTypeNoTargetFrameworkMoniker); return; } if (!project.IsNetCore30OrHigher()) { EnvDteHelper.ShowError($"{SharedLocale.SupportedFramework}: {project.Properties.Item("TargetFrameworkMoniker").Value}"); return; } var result = await project.ContainsEfCoreDesignReferenceAsync(); if (string.IsNullOrEmpty(result.Item2)) { EnvDteHelper.ShowError(SharedLocale.EFCoreVersionNotFound); return; } if (!result.Item1) { if (!Version.TryParse(result.Item2, out Version version)) { EnvDteHelper.ShowError(string.Format(MigrationsLocale.CannotSupportVersion, version)); return; } var nugetHelper = new NuGetHelper(); nugetHelper.InstallPackage("Microsoft.EntityFrameworkCore.Design", project, version); EnvDteHelper.ShowError(string.Format(SharedLocale.InstallingEfCoreDesignPackage, version)); return; } var migrationsDialog = _package.GetView <IMigrationOptionsDialog>(); migrationsDialog.UseProjectForMigration(project) .UseOutputPath(outputPath); migrationsDialog.ShowAndAwaitUserResponse(true); } catch (Exception exception) { _package.LogError(new List <string>(), exception); } }
internal void LogError(List <string> statusMessages, Exception exception) { _dte2.StatusBar.Text = "An error occurred. See the Output window for details."; try { var buildOutputWindow = _dte2.ToolWindows.OutputWindow.OutputWindowPanes.Item("Build"); buildOutputWindow.OutputString(Environment.NewLine); foreach (var error in statusMessages) { buildOutputWindow.OutputString(error + Environment.NewLine); } if (exception != null) { buildOutputWindow.OutputString(exception + Environment.NewLine); } buildOutputWindow.Activate(); } catch { EnvDteHelper.ShowError(exception.ToString()); } }
public void AddCe35Database(object sender, ExecutedRoutedEventArgs e) { // http://www.mztools.com/articles/2007/MZ2007011.aspx if (!DataConnectionHelper.DdexProviderIsInstalled(new Guid(Resources.SqlCompact35Provider))) { EnvDteHelper.ShowError("The version 3.5 Visual Studio DDEX provider is not installed, cannot add connection"); return; } try { var objIVsDataConnectionDialogFactory = _package.GetServiceHelper(typeof(IVsDataConnectionDialogFactory)) as IVsDataConnectionDialogFactory; if (objIVsDataConnectionDialogFactory == null) { return; } var objIVsDataConnectionDialog = objIVsDataConnectionDialogFactory.CreateConnectionDialog(); objIVsDataConnectionDialog.AddAllSources(); objIVsDataConnectionDialog.SelectedSource = new Guid("130BADA6-E128-423c-9D07-02E4734D45D4"); objIVsDataConnectionDialog.SelectedProvider = new Guid(Resources.SqlCompact35Provider); if (objIVsDataConnectionDialog.ShowDialog() && objIVsDataConnectionDialog.SelectedProvider == new Guid(Resources.SqlCompact35Provider)) { DataConnectionHelper.SaveDataConnection(_package, objIVsDataConnectionDialog.EncryptedConnectionString, DatabaseType.SQLCE35, new Guid(Resources.SqlCompact35Provider)); var control = _parentWindow.Content as ExplorerControl; control?.BuildDatabaseTree(); DataConnectionHelper.LogUsage("DatabasesAddCe35Database"); } objIVsDataConnectionDialog.Dispose(); } catch (Exception ex) { DataConnectionHelper.SendError(ex, DatabaseType.SQLCE35); } }
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 void ResultsetGrid_Load(object sender, EventArgs e) { this.tableName = TableName; try { this.dataGridView1.AutoGenerateColumns = true; this.dataGridView1.DataError += new DataGridViewDataErrorEventHandler(dataGridView1_DataError); imageContext.Items.Add("Import Image", null, new EventHandler(ImportImage)); imageContext.Items.Add("Export Image", null, new EventHandler(ExportImage)); imageContext.Items.Add("Delete Image", null, new EventHandler(DeleteImage)); LoadData(SqlText); this.dataGridView1.ReadOnly = ReadOnly; if (this.ReadOnlyColumns != null) { foreach (int x in ReadOnlyColumns) { this.dataGridView1.Columns[x].ReadOnly = true; this.dataGridView1.Columns[x].DefaultCellStyle.ForeColor = SystemColors.GrayText; } } if (Properties.Settings.Default.MultiLineTextEntry) { foreach (DataGridViewColumn col in dataGridView1.Columns) { if (col is DataGridViewTextBoxColumn) { col.DefaultCellStyle.WrapMode = DataGridViewTriState.True; } } this.dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; } this.bindingNavigatorAddNewItem.Enabled = !ReadOnly; this.bindingNavigatorDeleteItem.Enabled = !ReadOnly; this.toolStripButton1.Enabled = !ReadOnly; this.dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText; this.dataGridView1.AllowUserToOrderColumns = true; this.dataGridView1.MultiSelect = false; //if (Properties.Settings.Default.ShowNullValuesAsNULL) //{ // this.dataGridView1.DefaultCellStyle.NullValue = "NULL"; //} this.dataGridView1.KeyDown += new KeyEventHandler(dataGridView1_KeyDown); //this.dataGridView1.CellContentClick += new DataGridViewCellEventHandler(dataGridView1_CellContentClick); dgs = new DataGridViewSearch(this.dataGridView1); if (ReadOnly) { this.dataGridView1.DefaultCellStyle.ForeColor = SystemColors.GrayText; EnvDteHelper.ShowError("No primary keys on table, data is read-only"); } } catch (Exception ex) { Helpers.DataConnectionHelper.SendError(ex, DatabaseInfo.DatabaseType, false); } }
public void ReportTableData(object sender, ExecutedRoutedEventArgs e) { string sqlText; var menuItem = sender as MenuItem; var ds = new DataSet(); var menuInfo = menuItem?.CommandParameter as MenuCommandParameters; if (menuInfo == null) { return; } try { using (var repository = Helpers.RepositoryHelper.CreateRepository(menuInfo.DatabaseInfo)) { var generator = DataConnectionHelper.CreateGenerator(repository, menuInfo.DatabaseInfo.DatabaseType); generator.GenerateViewSelect(menuInfo.Name); OpenSqlEditorToolWindow(menuInfo, generator.GeneratedScript); sqlText = Environment.NewLine + generator.GeneratedScript + Environment.NewLine + "GO"; ds = repository.ExecuteSql(sqlText); } var pkg = ParentWindow.Package as SqlCeToolboxPackage; Debug.Assert(pkg != null, "Package property of the Explorere Tool Window should never be null, have you tried to create it manually and not through FindToolWindow()?"); string dbName = System.IO.Path.GetFileNameWithoutExtension(menuInfo.DatabaseInfo.Caption); if (dbName != null) { var window = pkg.CreateWindow <ReportWindow>(Math.Abs(menuInfo.Name.GetHashCode() - dbName.GetHashCode())); if (window == null) { return; } window.Caption = menuInfo.Name + " (" + dbName + ")"; pkg.ShowWindow(window); var control = window.Content as ReportControl; if (control != null) { control.DatabaseInfo = menuInfo.DatabaseInfo; control.TableName = menuInfo.Name; control.DataSet = ds; control.ShowReport(); } } DataConnectionHelper.LogUsage("ViewReport"); } catch (System.IO.FileNotFoundException) { EnvDteHelper.ShowError("Microsoft Report Viewer 2010 not installed, please download and install to use this feature http://www.microsoft.com/en-us/download/details.aspx?id=6442"); return; } catch (Exception ex) { DataConnectionHelper.SendError(ex, menuInfo.DatabaseInfo.DatabaseType, false); } ds.Dispose(); }
public void GenerateServerDgmlFiles() { try { if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug) { EnvDteHelper.ShowError("Cannot generate code while debugging"); return; } // Show dialog with SqlClient selected by default var dialogFactory = _package.GetService <IVsDataConnectionDialogFactory>(); var dialog = dialogFactory.CreateConnectionDialog(); dialog.AddAllSources(); dialog.SelectedSource = new Guid("067ea0d9-ba62-43f7-9106-34930c60c528"); var dialogResult = dialog.ShowDialog(connect: true); if (dialogResult == null) { return; } _package.Dte2.StatusBar.Text = "Loading schema information..."; var dbInfo = GetDatabaseInfo(dialogResult, DataProtection.DecryptString(dialog.EncryptedConnectionString)); if (dbInfo.DatabaseType == DatabaseType.SQLCE35) { EnvDteHelper.ShowError($"Unsupported provider: {dbInfo.ServerVersion}"); return; } var ptd = new PickTablesDialog(); using (var repository = RepositoryHelper.CreateRepository(dbInfo)) { ptd.Tables = repository.GetAllTableNamesForExclusion(); } var res = ptd.ShowModal(); if (!res.HasValue || !res.Value) { return; } var path = Path.GetTempFileName() + ".dgml"; using (var repository = RepositoryHelper.CreateRepository(dbInfo)) { var generator = RepositoryHelper.CreateGenerator(repository, path, dbInfo.DatabaseType); generator.GenerateSchemaGraph(dbInfo.ConnectionString, ptd.Tables); _package.Dte2.ItemOperations.OpenFile(path); _package.Dte2.ActiveDocument.Activate(); } } catch (Exception ex) { _package.LogError(new List <string>(), ex); } }
public void GenerateServerDgmlFiles() { try { if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug) { EnvDteHelper.ShowError("Cannot generate code while debugging"); return; } var databaseList = EnvDteHelper.GetDataConnections(_package); var psd = new PickServerDatabaseDialog(databaseList, _package); var diagRes = psd.ShowModal(); if (!diagRes.HasValue || !diagRes.Value) { return; } _package.Dte2.StatusBar.Text = "Loading schema information..."; var dbInfo = psd.SelectedDatabase.Value; if (dbInfo.DatabaseType == DatabaseType.SQLCE35) { EnvDteHelper.ShowError($"Unsupported provider: {dbInfo.ServerVersion}"); return; } var ptd = new PickTablesDialog(); using (var repository = RepositoryHelper.CreateRepository(dbInfo)) { ptd.Tables = repository.GetAllTableNamesForExclusion(); } var res = ptd.ShowModal(); if (!res.HasValue || !res.Value) { return; } var path = Path.GetTempFileName() + ".dgml"; using (var repository = RepositoryHelper.CreateRepository(dbInfo)) { var generator = RepositoryHelper.CreateGenerator(repository, path, dbInfo.DatabaseType); generator.GenerateSchemaGraph(dbInfo.ConnectionString, ptd.Tables); _package.Dte2.ItemOperations.OpenFile(path); _package.Dte2.ActiveDocument.Activate(); } Telemetry.TrackEvent("PowerTools.GenerateSchemaDgml"); } catch (Exception ex) { _package.LogError(new List <string>(), ex); } }
public void Generate(string outputPath, Project project, GenerationType generationType) { try { if (string.IsNullOrEmpty(outputPath)) { throw new ArgumentException(outputPath, nameof(outputPath)); } if (project.Properties.Item("TargetFrameworkMoniker") == null) { EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker"); return; } if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework") && !project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2.0")) { EnvDteHelper.ShowError("Currently only .NET Framework and .NET Core 2.0 projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value); return; } bool isNetCore = project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2.0"); var processResult = _processLauncher.GetOutput(outputPath, isNetCore, generationType); if (processResult.StartsWith("Error:")) { throw new ArgumentException(processResult, nameof(processResult)); } switch (generationType) { case GenerationType.Dgml: GenerateDgml(processResult, project); Telemetry.TrackEvent("PowerTools.GenerateModelDgml"); break; case GenerationType.Ddl: GenerateFiles(processResult, project, ".sql"); Telemetry.TrackEvent("PowerTools.GenerateSqlCreate"); break; case GenerationType.DebugView: GenerateFiles(processResult, project, ".txt"); Telemetry.TrackEvent("PowerTools.GenerateDebugView"); break; default: break; } } catch (Exception exception) { _package.LogError(new List <string>(), exception); } }
public void RemoveDatabaseConnection(object sender, ExecutedRoutedEventArgs e) { try { var databaseInfo = ValidateMenuInfo(sender); if (databaseInfo == null) { return; } if (databaseInfo.DatabaseInfo.FromServerExplorer) { bool providerInstalled = true; var provider = new Guid(Resources.SqlCompact40Provider); if (databaseInfo.DatabaseInfo.DatabaseType == DatabaseType.SQLCE35) { provider = new Guid(Resources.SqlCompact35Provider); } if (databaseInfo.DatabaseInfo.DatabaseType == DatabaseType.SQLite) { provider = new Guid(Resources.SqlitePrivateProvider); } providerInstalled = DataConnectionHelper.DdexProviderIsInstalled(provider); if (!providerInstalled) { if (databaseInfo.DatabaseInfo.DatabaseType == DatabaseType.SQLCE40) { provider = new Guid(Resources.SqlCompact40PrivateProvider); providerInstalled = DataConnectionHelper.DdexProviderIsInstalled(provider); } if (!providerInstalled) { EnvDteHelper.ShowError("The DDEX provider is not installed, cannot remove connection"); return; } } DataConnectionHelper.RemoveDataConnection(package, databaseInfo.DatabaseInfo.ConnectionString, provider); } else { DataConnectionHelper.RemoveDataConnection(databaseInfo.DatabaseInfo.ConnectionString); } var control = _parentWindow.Content as ExplorerControl; if (control != null) { control.BuildDatabaseTree(); } DataConnectionHelper.LogUsage("DatabaseRemoveCe"); } catch (Exception ex) { DataConnectionHelper.SendError(ex, DatabaseType.SQLCE35); } }
public void ImportData(object sender, ExecutedRoutedEventArgs e) { var menuInfo = ValidateMenuInfo(sender); if (menuInfo == null) { return; } try { using (var repository = DataConnectionHelper.CreateRepository(menuInfo.DatabaseInfo)) { var generator = DataConnectionHelper.CreateGenerator(repository, menuInfo.DatabaseInfo.DatabaseType); var imo = new ImportDialog { SampleHeader = generator.GenerateTableColumns(menuInfo.Name), Separator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator.ToCharArray()[0] }; if (imo.ShowModal() != true) { return; } if (string.IsNullOrWhiteSpace(imo.File) || !System.IO.File.Exists(imo.File)) { return; } using (var reader = new CsvReader(imo.File, Encoding.UTF8)) { reader.ValueSeparator = imo.Separator; var hr = reader.ReadHeaderRecord(); if (generator.ValidColumns(menuInfo.Name, hr.Values)) { var i = 1; foreach (var record in reader.DataRecords) { generator.GenerateTableInsert(menuInfo.Name, hr.Values, record.Values, i); i++; } } } OpenSqlEditorToolWindow(menuInfo, generator.GeneratedScript); DataConnectionHelper.LogUsage("TableImport"); } } catch (System.IO.IOException iox) { EnvDteHelper.ShowError(iox.Message); } catch (Exception ex) { DataConnectionHelper.SendError(ex, menuInfo.DatabaseInfo.DatabaseType, false); } }
private void toolStripButton2_Click(object sender, EventArgs e) { try { LoadData(_sqlText); } catch (Exception ex) { EnvDteHelper.ShowError(ex.ToString()); } }
private void SaveTable() { try { _adapter.Update(_table); } catch (Exception ex) { EnvDteHelper.ShowError(ex.ToString()); } }
private void ReportStatus(string processResult) { _package.Dte2.StatusBar.Text = string.Empty; if (processResult.StartsWith("Error:")) { EnvDteHelper.ShowError(processResult); return; } var result = BuildModelResult(processResult); UpdateStatusList(result); }
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); } }
public void ManageMigrations(string outputPath, Project project) { try { if (string.IsNullOrEmpty(outputPath)) { throw new ArgumentException(outputPath, nameof(outputPath)); } if (project == null) { throw new ArgumentNullException(nameof(project)); } if (project.Properties.Item("TargetFrameworkMoniker") == null) { EnvDteHelper.ShowError("The selected project type has no TargetFrameworkMoniker"); return; } if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework") && !project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2.0")) { EnvDteHelper.ShowError("Currently only .NET Framework and .NET Core 2.0 projects are supported - TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value); return; } var outputFolder = Path.GetDirectoryName(outputPath); bool isNetCore = project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETCoreApp,Version=v2."); if (!isNetCore && !File.Exists(Path.Combine(outputFolder, "Microsoft.EntityFrameworkCore.dll"))) { EnvDteHelper.ShowError("EF Core is not installed in the current project"); return; } var msd = new EfCoreMigrationsDialog(_package, outputPath, isNetCore, project) { ProjectName = project.Name }; msd.ShowModal(); } catch (Exception exception) { _package.LogError(new List <string>(), exception); } }
public async System.Threading.Tasks.Task ReverseEngineerCodeFirstAsync(Project project) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug) { EnvDteHelper.ShowError(ReverseEngineerLocale.CannotGenerateCodeWhileDebugging); return; } var projectPath = project.Properties.Item("FullPath")?.Value.ToString(); var optionsPaths = project.GetConfigFiles(); var optionsPath = optionsPaths.First(); if (optionsPaths.Count > 1) { var pcd = _package.GetView <IPickConfigDialog>(); pcd.PublishConfigurations(optionsPaths.Select(m => new ConfigModel { ConfigPath = m, ProjectPath = projectPath })); var pickConfigResult = pcd.ShowAndAwaitUserResponse(true); if (!pickConfigResult.ClosedByOK) { return; } optionsPath = pickConfigResult.Payload.ConfigPath; } await ReverseEngineerCodeFirstAsync(project, optionsPath, false); } catch (AggregateException ae) { foreach (var innerException in ae.Flatten().InnerExceptions) { _package.LogError(new List <string>(), innerException); } } catch (Exception exception) { _package.LogError(new List <string>(), exception); } }
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); } }
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); } } }