/// <summary>
        /// Imports the selected MySQL procedure's result sets into the active <see cref="ExcelInterop.Worksheet"/>.
        /// </summary>
        private bool ImportData()
        {
            if (_importDataSet == null)
            {
                MiscUtilities.ShowCustomizedErrorDialog(string.Format(Resources.UnableToRetrieveData, "procedure", _dbProcedure.Name));
                return(false);
            }

            if (_sumOfResultSetsExceedsMaxCompatibilityRows && ProcedureResultSetsImportType == DbProcedure.ProcedureResultSetsImportType.AllResultSetsVertically && _importDataSet.Tables.Count > 1)
            {
                InfoDialog.ShowDialog(InfoDialogProperties.GetWarningDialogProperties(
                                          Resources.ImportVerticallyExceedsMaxRowsTitleWarning,
                                          Resources.ImportVerticallyExceedsMaxRowsDetailWarning));
            }

            Cursor = Cursors.WaitCursor;

            // Refresh import parameter values
            _dbProcedure.ImportParameters.AddSummaryRow      = AddSummaryFieldsCheckBox.Checked;
            _dbProcedure.ImportParameters.CreatePivotTable   = CreatePivotTableCheckBox.Checked;
            _dbProcedure.ImportParameters.IncludeColumnNames = IncludeHeadersCheckBox.Checked;
            _dbProcedure.ImportParameters.IntoNewWorksheet   = false;

            // Import the result sets into Excel
            bool success = _dbProcedure.ImportData(ProcedureResultSetsImportType, _selectedResultSetIndex, _importDataSet);

            Cursor = Cursors.Default;
            return(success);
        }
Example #2
0
        /// <summary>
        /// Attempts to start the service deletion watcher.
        /// </summary>
        /// <param name="wmiManagementScope">The scope (namespace) used for WMI operations.</param>
        /// <returns>true if watcher was started successfull, false otherwise.</returns>
        private bool ServiceStatusChangeWatcherStart(ManagementScope wmiManagementScope)
        {
            bool success = true;

            if (!WatchForServiceStatusChange)
            {
                return(true);
            }

            try
            {
                if (!wmiManagementScope.IsConnected)
                {
                    wmiManagementScope.Connect();
                }

                if (Asynchronous)
                {
                    var queryTimeout = TimeSpan.FromSeconds(WmiQueriesTimeoutInSeconds);
                    _wmiAsyncStatusChangeWatcher = _wmiAsyncStatusChangeWatcher ?? new ManagementEventWatcher(wmiManagementScope, new WqlEventQuery("__InstanceModificationEvent", queryTimeout, WMI_QUERIES_WHERE_CLAUSE));
                    _wmiAsyncStatusChangeWatcher.EventArrived += ServiceStatusChangeWatcher_EventArrived;
                    _wmiAsyncStatusChangeWatcher.Start();
                }
                else
                {
                    if (_wmiSemiSyncStatusChangeWatcher == null)
                    {
                        _wmiSemiSyncStatusChangeWatcher = new BackgroundWorker
                        {
                            WorkerSupportsCancellation = true,
                            WorkerReportsProgress      = true
                        };
                        _wmiSemiSyncStatusChangeWatcher.DoWork             += ServiceStatusChangeWatcherStartSemiSyncDoWork;
                        _wmiSemiSyncStatusChangeWatcher.ProgressChanged    += ServiceStatusChangeWatcherStartSemiSynProgressChanged;
                        _wmiSemiSyncStatusChangeWatcher.RunWorkerCompleted += ServiceStatusChangeWatcherStartSemiSyncCompleted;
                    }

                    if (!_wmiSemiSyncStatusChangeWatcher.IsBusy)
                    {
                        _wmiSemiSyncStatusChangeWatcher.RunWorkerAsync(wmiManagementScope);
                    }
                }
            }
            catch (Exception ex)
            {
                success = false;
                string title    = Resources.WMIEventsSubscriptionErrorTitle;
                string detail   = Resources.WMIEventsSubscriptionErrorDetail;
                string moreInfo = ex.Message.Contains("0x80070776")
          ? Resources.ObjectExporterSpecifierNotFoundExtendedMessage
          : null;
                var infoProperties = InfoDialogProperties.GetWarningDialogProperties(title, detail, null, moreInfo);
                infoProperties.CommandAreaProperties.DefaultButton        = InfoDialog.DefaultButtonType.Button1;
                infoProperties.CommandAreaProperties.DefaultButtonTimeout = 30;
                InfoDialog.ShowDialog(infoProperties);
                Program.MySqlNotifierErrorHandler(title, detail, false, ex, SourceLevels.Information);
            }

            return(success);
        }
Example #3
0
        /// <summary>
        /// Exports currently selected Excel data to a new MySQL table or appends it to an existing MySQL table.
        /// </summary>
        /// <param name="toTableObject">Table to append the data to, if null exports to a new table.</param>
        /// <returns><c>true</c> if the export/append action was executed, <c>false</c> otherwise.</returns>
        public bool AppendDataToTable(DbTable toTableObject)
        {
            DialogResult dr;

            if (!(Globals.ThisAddIn.Application.Selection is ExcelInterop.Range exportRange))
            {
                return(false);
            }

            if (exportRange.Areas.Count > 1)
            {
                InfoDialog.ShowDialog(InfoDialogProperties.GetWarningDialogProperties(Resources.MultipleAreasNotSupportedWarningTitle, Resources.MultipleAreasNotSupportedWarningDetail));
                return(false);
            }

            Cursor = Cursors.WaitCursor;
            if (toTableObject != null)
            {
                using (var appendDataForm = new AppendDataForm(toTableObject, exportRange, ActiveWorksheet.Name))
                {
                    dr = appendDataForm.ShowDialog();
                }
            }
            else
            {
                using (var exportForm = new ExportDataForm(WbConnection, exportRange, ActiveWorksheet.Name))
                {
                    dr = exportForm.ShowDialog();
                }
            }

            Cursor = Cursors.Default;
            return(dr == DialogResult.OK);
        }
Example #4
0
        private void Drop()
        {
            string typeString = LocalizedTypeString.ToLower(CultureInfo.CurrentCulture);
            var    infoResult = InfoDialog.ShowDialog(InfoDialogProperties.GetYesNoDialogProperties(InfoDialog.InfoType.Info,
                                                                                                    string.Format(Resources.DropConfirmationCaption, typeString), string.Format(
                                                                                                        Resources.DropConfirmation, typeString, Name)));

            if (infoResult.DialogResult == DialogResult.No)
            {
                throw new OperationCanceledException();
            }

            string sql = GetDropSql();

            try
            {
                ExecuteSql(sql);

                // now we drop the node from the hierarchy
                HierarchyAccessor.DropObjectNode(ItemId);
            }
            catch (Exception ex)
            {
                MySqlSourceTrace.WriteAppErrorToLog(ex, Resources.ErrorTitle, string.Format(Resources.ErrorAttemptingToDrop, LocalizedTypeString, Name), true);
                throw new OperationCanceledException();
            }
        }
Example #5
0
        /// <summary>
        /// Event delegate method fired when the button to connect to the database is clicked.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        protected void ConnectButtonClick(object sender, EventArgs e)
        {
            try
            {
                using (var connectDialog = new ConnectDialog())
                {
                    connectDialog.Connection = Connection;
                    if (connectDialog.ShowDialog() == DialogResult.Cancel)
                    {
                        return;
                    }

                    // Check if the MySQL Server version supports the X Protocol.
                    if (IsHybrid && !connectDialog.Connection.ServerVersionSupportsXProtocol(false))
                    {
                        InfoDialog.ShowDialog(InfoDialogProperties.GetWarningDialogProperties(Resources.WarningText,
                                                                                              Resources.NewConnectionNotXProtocolCompatibleDetail, null,
                                                                                              Resources.NewConnectionNotXProtocolCompatibleMoreInfo));
                        return;
                    }

                    SetConnection(connectDialog.Connection, connectDialog.ConnectionName);
                    ClearResults();
                }
            }
            catch (MySqlException ex)
            {
                MySqlSourceTrace.WriteAppErrorToLog(ex, Resources.NewConnectionErrorDetail, Resources.NewConnectionErrorSubDetail, true);
            }
        }
Example #6
0
    internal override void OnStarting(BaseWizardForm wizard)
    {
      _wiz = (BaseWizardForm)wizard;

      ConnectionString = _wiz.ConnectionString;
      if (!string.IsNullOrEmpty(_wiz.ConnectionString))
      {
        var cnn = new MySqlConnection(_wiz.ConnectionString);
        try
        {
          cnn.Open();
        }
        catch (Exception)
        {
          var infoProps = InfoDialogProperties.GetInfoDialogProperties(InfoDialog.InfoType.Error, CommandAreaProperties.ButtonsLayoutType.Generic2Buttons, Resources.ErrorTitle, Resources.ErrorOnConnection);
          infoProps.CommandAreaProperties.Button1Text = "Retry";
          infoProps.CommandAreaProperties.Button1DialogResult = DialogResult.Retry;
          infoProps.CommandAreaProperties.Button2Text = "Cancel";
          infoProps.CommandAreaProperties.Button2DialogResult = DialogResult.Cancel;
          var infoResult = InfoDialog.ShowDialog(infoProps);
          if (infoResult.DialogResult == DialogResult.Cancel)
          {
            listTables.Enabled = false;
          }
        }

        FillTables(_wiz.ConnectionString);
      }
    }
Example #7
0
        /// <summary>
        /// Event delegate method fired before the <see cref="MonitorMySqlServerInstancesDialog"/> dialog is closed.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void MonitorMySQLServerInstancesDialog_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult != DialogResult.OK ||
                SelectedWorkbenchConnection == null ||
                WorkbenchConnectionsListView.SelectedItems.Count <= 0 ||
                WorkbenchConnectionsListView.SelectedItems[0].Checked)
            {
                ResetChangeCursorDelegate(false);
                return;
            }

            var infoProperties = InfoDialogProperties.GetYesNoDialogProperties(
                InfoDialog.InfoType.Info,
                Resources.ConnectionAlreadyInInstancesTitle,
                Resources.ConnectionAlreadyInInstancesDetail,
                Resources.ConnectionAlreadyInInstancesSubDetail);

            infoProperties.CommandAreaProperties.DefaultButton        = InfoDialog.DefaultButtonType.Button2;
            infoProperties.CommandAreaProperties.DefaultButtonTimeout = 30;
            var infoResult = InfoDialog.ShowDialog(infoProperties);

            if (infoResult.DialogResult == DialogResult.Yes)
            {
                ResetChangeCursorDelegate(false);
                return;
            }

            SelectedWorkbenchConnection = null;
            e.Cancel = true;
        }
Example #8
0
        /// <summary>
        /// Event delegate method fired when one of the items in the fast-switch connections drop-down menu is clicked.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        protected virtual void SwitchConnectionItemClick(object sender, EventArgs e)
        {
            var connectionMenuItem = sender as ToolStripMenuItem;

            if (connectionMenuItem == null)
            {
                return;
            }

            var parent = connectionMenuItem.GetCurrentParent();

            if (parent == null)
            {
                return;
            }

            var connectionName = connectionMenuItem.Text;
            var connection     = Package.GetMySqlConnection(connectionName);

            if (connection == null)
            {
                // The connection is no longer present in the Server Explorer
                InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(
                                          Resources.Editors_SeConnectionNotFoundTitle,
                                          string.Format(Resources.Editors_SeConnectionNotFoundDetail, connectionName)));
                return;
            }

            // Switch to the selected connection
            SetConnection(connection, connectionName);
            ClearResults();
        }
Example #9
0
        protected void LaunchDebugTarget()
        {
            Microsoft.VisualStudio.Shell.ServiceProvider sp =
                new Microsoft.VisualStudio.Shell.ServiceProvider((IOleServiceProvider)Dte);

            IVsDebugger dbg = (IVsDebugger)sp.GetService(typeof(SVsShellDebugger));

            VsDebugTargetInfo info = new VsDebugTargetInfo();


            info.cbSize     = (uint)Marshal.SizeOf(info);
            info.dlo        = DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;
            info.bstrExe    = Moniker;
            info.bstrCurDir = @"C:\";
            string connectionString = HierarchyAccessor.Connection.ConnectionSupport.ConnectionString + ";Allow User Variables=true;Allow Zero DateTime=true;";

            if (connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase) == -1)
            {
                var connection = (MySqlConnection)HierarchyAccessor.Connection.GetLockedProviderObject();
                try
                {
                    var settings = (MySqlConnectionStringBuilder)connection.GetType().GetProperty("Settings", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(connection, null);
                    connectionString += "password="******";Persist Security Info=true;";
                }
                finally
                {
                    HierarchyAccessor.Connection.UnlockProviderObject();
                }
            }
            info.bstrArg                   = connectionString;
            info.bstrRemoteMachine         = null;                                               // Environment.MachineName; // debug locally
            info.fSendStdoutToOutputWindow = 0;                                                  // Let stdout stay with the application.
            info.clsidCustom               = new Guid("{EEEE0740-10F7-4e5f-8BC4-1CC0AC9ED5B0}"); // Set the launching engine the sample engine guid
            info.grfLaunch                 = 0;

            IntPtr pInfo = Marshal.AllocCoTaskMem((int)info.cbSize);

            Marshal.StructureToPtr(info, pInfo, false);

            try
            {
                int result = dbg.LaunchDebugTargets(1, pInfo);
                if (result != 0 && result != VSConstants.E_ABORT)
                {
                    throw new ApplicationException("COM error " + result);
                }
            }
            catch (Exception ex)
            {
                InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties("Debugger Error", ex.GetBaseException().Message));
            }
            finally
            {
                if (pInfo != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pInfo);
                }
            }
        }
Example #10
0
 /// <summary>
 /// Shows an error dialog with the specified text message.
 /// </summary>
 /// <param name="message"></param>
 private void ShowErrorDialog(int rowIndex, int columnIndex, string dataType, string message)
 {
     InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.ErrorCaption, string.Format(message, dataType)));
     columnGrid.CurrentCell.Value    = _previousDataType;
     columnGrid.CurrentCell          = columnGrid.Rows[rowIndex].Cells[columnIndex];
     columnGrid.CurrentCell.Selected = true;
     columnGrid.BeginEdit(true);
 }
Example #11
0
        /// <summary>
        /// Event delegate method fired when the <see cref="OriginalQueryButton"/> is clicked.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void OriginalQueryButton_Click(object sender, EventArgs e)
        {
            if (InfoDialog.ShowDialog(InfoDialogProperties.GetYesNoDialogProperties(InfoDialog.InfoType.Warning, Resources.ReviewSqlQueryRevertTitle, Resources.ReviewSqlQueryRevertDetail)).DialogResult != DialogResult.Yes)
            {
                return;
            }

            OriginalQueryButton.Enabled = false;
            SqlScript = OriginalSqlScript;
        }
Example #12
0
 /// <summary>
 /// Event delegate method fired when the <see cref="WhyDisabledLinkLabel"/> is clicked.
 /// </summary>
 /// <param name="sender">Sender object.</param>
 /// <param name="e">Event arguments.</param>
 private void WhyDisabledLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     InfoDialog.ShowDialog(InfoDialogProperties.GetInformationDialogProperties(
                               Resources.ImportMultipleRelationshipsNotSupportedTitleText,
                               Excel2010OrLower
   ? Resources.ImportMultipleRelationshipsNotSupportedExcelVersionWarningText
   : Resources.ImportMultipleRelationshipsNotSupportedNoExcelTablesWarningText,
                               null,
                               Resources.ImportMultipleSinglePivotTableNotSupportedText));
 }
Example #13
0
 private void _worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
   if (e.Error != null)
   {
     this.Invoke((Action)(() =>
     {
       InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.TablesSelection_ExportingError, e.Error.Message));
     }));
   }
   UnlockUI();
 }
Example #14
0
        /// <summary>
        /// Returns a <see cref="DbConnection"/> created from the connection parameters in this dialog.
        /// </summary>
        /// <param name="askToCreateSchemaIfNotExists">Flag indicating whether a prompt is shown to ask for the schema creation in case the specified schema does not exist.</param>
        /// <param name="testOnly">Flag indicating whether the method only tests if a connection can be created and disposes of the connection after the test is done.</param>
        /// <returns>A <see cref="DbConnection"/> if <see cref="testOnly"/> is <c>false</c>.</returns>
        private DbConnection GetConnection(bool askToCreateSchemaIfNotExists, bool testOnly)
        {
            var newConnection = _factory.CreateConnection();

            if (newConnection == null)
            {
                return(null);
            }

            newConnection.ConnectionString = ConnectionString;
            try
            {
                newConnection.Open();
            }
            catch (MySqlException mysqlException)
            {
                string schema    = _connectionStringBuilder.Database;
                bool   showError = true;
                newConnection = null;
                if (mysqlException.InnerException != null &&
                    string.Compare(mysqlException.InnerException.Message, string.Format("Unknown database '{0}'", schema), StringComparison.InvariantCultureIgnoreCase) == 0 &&
                    askToCreateSchemaIfNotExists)
                {
                    var infoResult = InfoDialog.ShowDialog(InfoDialogProperties.GetYesNoDialogProperties(InfoDialog.InfoType.Warning,
                                                                                                         Resources.ConnectDialog_CreateSchemaTitle,
                                                                                                         string.Format(Resources.ConnectDialog_CreateSchemaDetail, schema),
                                                                                                         Resources.ConnectDialog_CreateSchemaSubDetail));
                    if (infoResult.DialogResult == DialogResult.Yes && CreateSchema(schema))
                    {
                        newConnection = GetConnection(false, testOnly);
                        showError     = false;
                    }
                }

                if (showError)
                {
                    MySqlSourceTrace.WriteAppErrorToLog(mysqlException, Resources.ErrorTitle, Resources.ConnectDialog_GetConnectionError, true);
                }
            }
            finally
            {
                if (testOnly && newConnection != null)
                {
                    if (newConnection.State == ConnectionState.Open)
                    {
                        newConnection.Close();
                    }

                    newConnection.Dispose();
                }
            }

            return(newConnection);
        }
Example #15
0
        internal void _worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.Invoke((Action)(() =>
                {
                    InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.ErrorTitle, string.Format("{0} {1}", _runWorkerCompletedErrorMessage, e.Error.Message)));
                }));
            }

            UnlockUI();
        }
Example #16
0
        public int OnClose(ref uint pgrfSaveOptions)
        {
            if (WindowHandler.Caption.Contains("*"))
            {
                var infoResult = InfoDialog.ShowDialog(InfoDialogProperties.GetYesNoDialogProperties(InfoDialog.InfoType.Info, Resources.MySqlDataProviderPackage_Information, Resources.SaveSelectedSettingsText));
                if (infoResult.DialogResult == DialogResult.Yes)
                {
                    DbExportPanelControl.SaveSettings(true);
                }
            }

            return(VSConstants.S_OK);
        }
Example #17
0
        private bool IsValidData()
        {
            if (IsEntityFrameworkPage)
            {
                if (useProvider.Checked && !radioBtnEF5.Checked && !radioBtnEF6.Checked)
                {
                    InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.ErrorTitle, Resources.WebConfigDlg_SelectEfVersion));
                    return(false);
                }
            }
            else
            {
                if (!IsSimpleMembershipPage)
                {
                    if (useProvider.Checked && connectionString.Text.Trim().Length == 0)
                    {
                        InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.ErrorTitle, Resources.WebConfigConnStrNoEmpty));
                        return(false);
                    }
                }
                else
                {
                    if (useProvider.Checked)
                    {
                        bool   valid = true;
                        string controlsToValidate = "";
                        foreach (Control control in pnlSimpleMembership.Controls)
                        {
                            if (ControlsFriendlyName.ContainsKey(control.Name))
                            {
                                controlsToValidate += controlsToValidate.Length > 0 ? ", " : "";
                                TextBox txt = control as TextBox;
                                if (txt != null && string.IsNullOrEmpty(txt.Text))
                                {
                                    valid = false;
                                    controlsToValidate += string.Format("{0}, ", ControlsFriendlyName[txt.Name]);
                                }
                            }
                        }

                        if (!valid)
                        {
                            controlsToValidate = (controlsToValidate += ".").Replace(", .", ".");
                            InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.ErrorTitle, string.Format("{0}: {1}", Resources.WrongNetFxVersionMessage, controlsToValidate)));
                            return(false);
                        }
                    }
                }
            }
            return(true);
        }
Example #18
0
        private void columnGrid_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (columnGrid.Rows[e.RowIndex].IsNewRow)
            {
                return;
            }

            int index = e.RowIndex;

            DataGridViewCell parentCell = columnGrid.Rows[e.RowIndex].Cells[0];
            DataGridViewCell childCell  = columnGrid.Rows[e.RowIndex].Cells[1];
            string           parent     = parentCell.Value as string;
            string           child      = childCell.Value as string;

            bool bad = false;

            parentCell.ErrorText = childCell.ErrorText = null;

            if ((String.IsNullOrEmpty(parent) || parent == None) &&
                (!String.IsNullOrEmpty(child) && child != None))
            {
                parentCell.ErrorText = Resources.FKNeedColumn;
                bad = true;
            }
            else if ((String.IsNullOrEmpty(child) || child == None) &&
                     (!String.IsNullOrEmpty(parent) && parent != None))
            {
                childCell.ErrorText = Resources.FKNeedColumn;
                bad = true;
            }
            if (bad)
            {
                InfoDialog.ShowDialog(InfoDialogProperties.GetInformationDialogProperties(Resources.MySqlDataProviderPackage_Information, Resources.FKColumnsNotMatched));
                e.Cancel = true;
                return;
            }
            else if (
                (((ForeignKey)foreignKeyBindingSource.Current).ReferencedTable == tableNode.Table.Name) &&
                (parent == child))
            {
                InfoDialog.ShowDialog(InfoDialogProperties.GetInformationDialogProperties(Resources.MySqlDataProviderPackage_Information, Resources.FKSameColumn));
                return;
            }
            FKColumnPair pair = fkColumnsBindingSource.Current as FKColumnPair;

            pair.Column           = parent;
            pair.ReferencedColumn = child;
            fkColumnsBindingSource.EndEdit();
        }
Example #19
0
        /// <summary>
        /// Sends an error message to the application log and optionally shows it to the users.
        /// </summary>
        /// <param name="errorTitle">The title displayed on the error dialog.</param>
        /// <param name="errorMessage">A custom error message.</param>
        /// <param name="showErrorDialog">Flag indicating whether the error is shown to users.</param>
        /// <param name="exception">An <see cref="Exception"/> object.</param>
        /// <param name="errorLevel">The <see cref="SourceLevels"/> to describe the severity of the error.</param>
        public static void MySqlNotifierErrorHandler(string errorTitle, string errorMessage, bool showErrorDialog, Exception exception, SourceLevels errorLevel = SourceLevels.Error)
        {
            bool emptyErrorMessage = string.IsNullOrEmpty(errorMessage);

            if (string.IsNullOrEmpty(errorTitle))
            {
                errorTitle = errorLevel == SourceLevels.Critical || emptyErrorMessage ? Resources.HighSeverityError : Resources.ErrorTitle;
            }

            if (emptyErrorMessage)
            {
                errorMessage = Resources.UnhandledExceptionText;
            }

            string exceptionMessage  = null;
            string exceptionMoreInfo = null;
            var    errorBuilder      = new StringBuilder(errorMessage);

            if (exception != null)
            {
                if (exception.Message.Length > 0)
                {
                    exceptionMessage = exception.Message;
                    errorBuilder.AppendLine(exception.Message);
                }

                if (exception.InnerException != null)
                {
                    errorBuilder.AppendLine(exception.InnerException.Message);
                    exceptionMoreInfo = exception.InnerException != null?string.Format("{0}{1}{1}", exception.InnerException.Message, Environment.NewLine) : string.Empty;
                }

                exceptionMoreInfo += exception.StackTrace;
            }

            string completeErrorMessage = errorBuilder.ToString();

            if (showErrorDialog)
            {
                var infoProperties = InfoDialogProperties.GetErrorDialogProperties(errorTitle, errorMessage, exceptionMessage, exceptionMoreInfo);
                infoProperties.FitTextStrategy  = InfoDialog.FitTextsAction.IncreaseDialogWidth;
                infoProperties.WordWrapMoreInfo = false;
                infoProperties.CommandAreaProperties.DefaultButton        = InfoDialog.DefaultButtonType.Button1;
                infoProperties.CommandAreaProperties.DefaultButtonTimeout = 60;
                InfoDialog.ShowDialog(infoProperties);
            }

            MySqlSourceTrace.WriteToLog(completeErrorMessage, errorLevel);
        }
Example #20
0
        /// <summary>
        /// Handles the click event for the <see cref="TestConnectionButton"/>.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void TestConnectionButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            DialogOKButton.Enabled = false;
            NewMachine.Name        = HostTextBox.Text.Trim();
            NewMachine.User        = UserTextBox.Text.Trim();
            NewMachine.Password    = MySqlSecurity.EncryptPassword(PasswordTextBox.Text);
            if (TestConnectionAndPermissionsSet(true))
            {
                InfoDialog.ShowDialog(InfoDialogProperties.GetSuccessDialogProperties(Resources.ConnectionSuccessfulTitle, Resources.ConnectionSuccessfulMessage));
                DialogOKButton.Enabled = true;
            }

            Cursor = Cursors.Default;
        }
Example #21
0
        /// <summary>
        /// Creates a <see cref="ExcelInterop.ModelRelationship"/> objects representing relationships among imported <see cref="DbTable"/> objects.
        /// </summary>
        private void CreateExcelRelationships()
        {
            if (!CreateExcelRelationshipsCheckBox.Checked || _relationshipsToCreateList == null || _relationshipsToCreateList.Count <= 0 || _excelTablesDictionary == null)
            {
                return;
            }

            var relationshipsCreationErrorBuilder = new StringBuilder(_relationshipsToCreateList.Count * 200);

            foreach (var relationship in _relationshipsToCreateList)
            {
                ExcelInterop.ListObject excelTable;
                ExcelInterop.ListObject relatedExcelTable;
                bool excelTableExists        = _excelTablesDictionary.TryGetValue(relationship.TableName, out excelTable);
                bool relatedExcelTableExists = _excelTablesDictionary.TryGetValue(relationship.RelatedTableName, out relatedExcelTable);
                if (!excelTableExists || !relatedExcelTableExists)
                {
                    if (relationshipsCreationErrorBuilder.Length > 0)
                    {
                        relationshipsCreationErrorBuilder.Append(Environment.NewLine);
                    }

                    relationshipsCreationErrorBuilder.Append(relationship.GetCreationErrorMessage(MySqlDataRelationship.CreationStatus.ModelTablesNotFound));
                    continue;
                }

                var creationStatus = relationship.CreateExcelRelationship(excelTable.Name, relatedExcelTable.Name);
                if (creationStatus == MySqlDataRelationship.CreationStatus.Success)
                {
                    continue;
                }

                if (relationshipsCreationErrorBuilder.Length > 0)
                {
                    relationshipsCreationErrorBuilder.Append(Environment.NewLine);
                }

                relationshipsCreationErrorBuilder.Append(relationship.GetCreationErrorMessage(creationStatus));
            }

            if (relationshipsCreationErrorBuilder.Length > 0)
            {
                InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.ExcelRelationshipsCreationErrorTitle, Resources.ExcelRelationshipsCreationErrorDetail, null, relationshipsCreationErrorBuilder.ToString()));
                relationshipsCreationErrorBuilder.Clear();
            }

            _excelTablesDictionary.Clear();
        }
Example #22
0
        private void btnEditSM_Click(object sender, EventArgs e)
        {
            ConnectionStringEditorDlg dlg = new ConnectionStringEditorDlg();

            try
            {
                dlg.ConnectionString = txtConnStringSM.Text;
                if (DialogResult.Cancel == dlg.ShowDialog(this))
                {
                    return;
                }
                txtConnStringSM.Text = dlg.ConnectionString;
            }
            catch (ArgumentException)
            {
                InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.ErrorTitle, Resources.ConnectionStringInvalid));
            }
        }
Example #23
0
        /// <summary>
        /// Event delegate method fired when the <see cref="NewConnectionHotLabel"/> label is clicked.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void NewConnectionHotLabel_Click(object sender, EventArgs e)
        {
            if (MySqlWorkbench.IsRunning)
            {
                // If Workbench is running we can't allow adding new connections
                InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.OperationErrorTitle, Resources.UnableToAddConnectionsWhenWBRunning, Resources.CloseWBAdviceToAdd));
                return;
            }

            using (var newConnectionDialog = new MySqlWorkbenchConnectionDialog(null))
            {
                var result = newConnectionDialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    LoadConnections(false);
                }
            }
        }
Example #24
0
        private bool ValidGridData()
        {
            if (!InEditMode)
            {
                return(true);
            }

            // Removes empty rows
            columnGrid.CurrentCell = null;
            for (int i = 0; i < fkColumnsBindingSource.Count; i++)
            {
                FKColumnPair pair = fkColumnsBindingSource[i] as FKColumnPair;
                if ((string.IsNullOrEmpty(pair.Column) || pair.Column.Equals(None)) &&
                    (string.IsNullOrEmpty(pair.ReferencedColumn) || pair.ReferencedColumn.Equals(None)))
                {
                    fkColumnsBindingSource.RemoveAt(i);
                    columnGrid.CurrentCell = null;
                    i--;
                }
            }

            for (int i = 0; i < columnGrid.Rows.Count; i++)
            {
                string str1 = ( string )((DataGridViewComboBoxCell)columnGrid.Rows[i].Cells[0]).FormattedValue;
                string str2 = (string)((DataGridViewComboBoxCell)columnGrid.Rows[i].Cells[1]).FormattedValue;
                if ((string.IsNullOrEmpty(str1) && string.IsNullOrEmpty(str2) && i == 0) ||
                    (str1.Equals("<None>", StringComparison.InvariantCultureIgnoreCase)) ||
                    (str2.Equals("<None>", StringComparison.InvariantCultureIgnoreCase)))
                {
                    InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.ErrorCaption, Resources.FkDlgBeforeClose));
                    return(false);
                }
            }
            foreach (object o in foreignKeyBindingSource)
            {
                ForeignKey fk = ( ForeignKey )o;
                if (fk.Columns.Count == 0)
                {
                    InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.ErrorCaption, string.Format(Resources.FkNoColumnsForForeignKey, fk.Name)));
                    return(false);
                }
            }
            return(true);
        }
Example #25
0
        protected void CopyPackageToProject(VSProject vsProj, string projPath, string packagesPath, string folderName)
        {
            try
            {
                var destination = Path.Combine(projPath, folderName);

                if (Directory.Exists(destination))
                {
                    Directory.Delete(destination);
                }

                Directory.Move(packagesPath, destination);
                vsProj.Project.ProjectItems.AddFromDirectory(destination);
            }
            catch
            {
                InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.BaseWizard_PackageAddErrorTitle, Resources.BaseWizard_PackageAddErrorDetail));
            }
        }
Example #26
0
        /// <summary>
        /// Validates user entries seem valid credentials on the textboxes  to perform a connection test.
        /// </summary>
        private void ValidateEntries()
        {
            // Validate Host name
            if (!string.IsNullOrEmpty(HostTextBox.Text))
            {
                bool   validName;
                string hostname = HostTextBox.Text.Trim();
                if (hostname.ToLowerInvariant() == MySqlWorkbenchConnection.DEFAULT_HOSTNAME || hostname == MySqlWorkbenchConnection.LOCAL_IP || hostname == ".")
                {
                    // Since we are attempting to add a remote computer, we deem the Host name as invalid if it resolves to a local machine.
                    validName = false;
                    InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.CannotAddLocalhostTitle, Resources.CannotAddLocalhostMessage));
                }
                else if (!EditMode && MachinesList.HasMachineWithName(hostname))
                {
                    // Host name already exists on the list of added remote machines.
                    validName = false;
                    InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.MachineAlreadyExistTitle, Resources.MachineAlreadyExistMessage));
                }
                else
                {
                    // Host name is also invalid if has non allowed characters or if is not a proper formated IP address.
                    validName = Regex.IsMatch(hostname, VALID_HOSTNAME_REGEX) || Regex.IsMatch(hostname, VALID_IP_REGEX);
                }

                hostErrorSign.Visible = !validName;
            }

            // Username is invalid if if has non allowed characters.
            var userName = UserTextBox.Text;

            userErrorSign.Visible = !string.IsNullOrEmpty(userName) &&
                                    !Regex.IsMatch(userName, VALID_DOWN_LEVEL_LOGON_NAME_REGEX) &&
                                    !Regex.IsMatch(userName, VALID_USER_PRINCIPAL_NAME_REGEX);

            // Enable or dissable buttons if entries seem valid.
            TestConnectionButton.Enabled = EntriesAreValid;
            if (!EntriesAreValid)
            {
                DialogOKButton.Enabled = false;
            }
        }
        /// <summary>
        /// Initializes GUI elements with properties values.
        /// </summary>
        public override void LoadProperties()
        {
            if (ConnectionProperties == null)
            {
                InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.MessageBoxErrorTitle, Resources.ConnectionPropertiesNull));
                throw new Exception(Resources.ConnectionPropertiesNull);
            }

            var parentForm = ParentForm;

            if (parentForm != null)
            {
                var okButton = parentForm.AcceptButton as Button;
                if (okButton != null)
                {
                    okButton.Click += okButton_Click;
                }
            }

            var prop = ConnectionProperties as MySqlConnectionProperties;

            if (prop == null)
            {
                return;
            }

            var cb = prop.ConnectionStringBuilder;

            _loadingInProcess = true;
            try
            {
                serverNameTextBox.Text       = (string)cb["Server"];
                userNameTextBox.Text         = (string)cb["User Id"];
                passwordTextBox.Text         = (string)cb["Password"];
                dbList.Text                  = (string)cb["Database"];
                savePasswordCheckBox.Checked = (bool)cb["Persist Security Info"];
            }
            finally
            {
                _loadingInProcess = false;
            }
        }
        /// <summary>
        /// We hook the ok button of our parent form so we can implement our 'create database' functionality
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void okButton_Click(object sender, EventArgs e)
        {
            //verify if the connection is a MySql connection
            if (!IsMySqlConnection())
            {
                return;
            }

            bool exists = DatabaseExists();

            if (exists)
            {
                return;
            }

            var prompt = string.Format(Resources.UnknownDbPromptCreate, dbList.Text);

            prompt = prompt.Replace(@"\n", @"\n");
            var infoResult = InfoDialog.ShowDialog(InfoDialogProperties.GetYesNoDialogProperties(InfoDialog.InfoType.Warning, Resources.WarningText, prompt));
            var parentForm = ParentForm;

            if (parentForm == null)
            {
                return;
            }

            parentForm.DialogResult = DialogResult.None;
            if (infoResult.DialogResult != DialogResult.Yes)
            {
                return;
            }

            if (!AttemptToCreateDatabase())
            {
                InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.MessageBoxErrorTitle, string.Format(Resources.ErrorAttemptingToCreateDB, dbList.Text)));
            }
            else
            {
                parentForm.DialogResult = DialogResult.OK;
            }
        }
Example #29
0
        /// <summary>
        /// Shows a <see cref="InfoDialog"/> dialog customized for MySQL for Excel, only an OK/Back button is displayed to users.
        /// </summary>
        /// <param name="infoType">The type of information the dialog will display to users.</param>
        /// <param name="detail">The text describing information details to the users.</param>
        /// <param name="moreInformation">The extended text users can see in the More Information text box.</param>
        /// <param name="wordWrapMoreInfo">Indicates if the More Information text box word wraps the text.</param>
        /// <returns>A dialog result with the user's selection.</returns>
        public static DialogResult ShowCustomizedInfoDialog(InfoDialog.InfoType infoType, string detail, string moreInformation = null, bool wordWrapMoreInfo = true)
        {
            string title      = string.Empty;
            var    layoutType = InfoButtonsProperties.ButtonsLayoutType.OkOnly;

            switch (infoType)
            {
            case InfoDialog.InfoType.Success:
                title = Resources.OperationSuccessTitle;
                break;

            case InfoDialog.InfoType.Warning:
                title = Resources.OperationWarningTitle;
                break;

            case InfoDialog.InfoType.Error:
                title      = Resources.OperationErrorTitle;
                layoutType = InfoButtonsProperties.ButtonsLayoutType.BackOnly;
                break;

            case InfoDialog.InfoType.Info:
                title = Resources.OperationInformationTitle;
                break;
            }

            string subDetailText  = string.Format(Resources.OperationSubDetailText, infoType == InfoDialog.InfoType.Error ? "Back" : "OK");
            var    infoProperties = new InfoDialogProperties
            {
                ButtonsProperties = new InfoButtonsProperties(layoutType),
                InfoType          = infoType,
                TitleText         = title,
                DetailText        = detail,
                DetailSubText     = subDetailText,
                MoreInfoText      = moreInformation,
                WordWrapMoreInfo  = wordWrapMoreInfo
            };

            return(InfoDialog.ShowDialog(infoProperties).DialogResult);
        }
Example #30
0
        /// <summary>
        /// Event delegate method fired when the <see cref="DeleteButton"/> is clicked.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void DeleteButton_Click(object sender, EventArgs e)
        {
            var infoProperties = InfoDialogProperties.GetYesNoDialogProperties(
                InfoDialog.InfoType.Warning,
                Resources.DeleteMachineConfirmationTitle,
                Resources.DeleteMachineConfirmationText);

            infoProperties.CommandAreaProperties.DefaultButton        = InfoDialog.DefaultButtonType.Button2;
            infoProperties.CommandAreaProperties.DefaultButtonTimeout = 30;
            var infoResult = InfoDialog.ShowDialog(infoProperties);

            if (infoResult.DialogResult != DialogResult.Yes)
            {
                return;
            }

            HasChanges = true;
            MachinesList.ChangeMachine(NewMachine, ListChangeType.RemoveByUser);
            int removedMachineIndex = MachineSelectionComboBox.SelectedIndex;

            MachineSelectionComboBox.SelectedIndex = 0;
            MachineSelectionComboBox.Items.RemoveAt(removedMachineIndex);
        }