Пример #1
0
        /// <summary>
        /// Executes the given query and returns the result set in a <see cref="DataTable"/> object.
        /// </summary>
        /// <param name="connection">MySQL Workbench connection to a MySQL server instance selected by users.</param>
        /// <param name="query">Select query to be sent to the MySQL Server.</param>
        /// <param name="tableIndex">The index of the table in the <see cref="DataSet"/> to be returned.</param>
        /// <returns>Table containing the results of the query.</returns>
        public static DataTable GetDataFromSelectQuery(this MySqlWorkbenchConnection connection, string query, int tableIndex = 0)
        {
            if (connection == null)
            {
                return(null);
            }

            DataSet ds = null;

            try
            {
                var connectionBuilder = connection.GetConnectionStringBuilder();
                connectionBuilder.AllowUserVariables = true;
                ds = MySqlHelper.ExecuteDataset(connectionBuilder.ConnectionString, query);
            }
            catch (Exception ex)
            {
                MiscUtilities.ShowCustomizedErrorDialog(string.Format(Resources.UnableToRetrieveData, "from query: ", query), ex.Message);
                MySqlSourceTrace.WriteAppErrorToLog(ex);
            }

            return(ds == null || ds.Tables.Count <= 0 || tableIndex < 0 || tableIndex >= ds.Tables.Count
        ? null
        : ds.Tables[tableIndex]);
        }
        /// <summary>
        /// Event delegate method fired when <see cref="NextButton"/> is clicked.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void NextButton_Click(object sender, EventArgs e)
        {
            var selectedNode = SchemasList.SelectedNode;

            if (selectedNode == null || selectedNode.Type == MySqlListViewNode.MySqlNodeType.Header || string.IsNullOrEmpty(selectedNode.DbObject.Name))
            {
                return;
            }

            var passwordFlags = _wbConnection.TestConnectionAndRetryOnWrongPassword();

            if (!passwordFlags.ConnectionSuccess)
            {
                return;
            }

            try
            {
                var excelAddInPane = Parent as ExcelAddInPane;
                if (excelAddInPane != null)
                {
                    excelAddInPane.OpenSchema(selectedNode.DbObject.Name, true);
                }
            }
            catch (Exception ex)
            {
                MiscUtilities.ShowCustomizedErrorDialog(Resources.SchemaOpeningErrorTitle, ex.Message, true);
                MySqlSourceTrace.WriteAppErrorToLog(ex);
            }
        }
Пример #3
0
        protected override void Load()
        {
            if (IsNew)
            {
                _editor.Text = GetNewTriggerText();
                _sqlMode     = string.Empty;
            }
            else
            {
                try
                {
                    DataTable dt = GetDataTable(string.Format("SHOW CREATE TRIGGER `{0}`.`{1}`",
                                                              Database, Name));

                    _sqlMode = dt.Rows[0][1].ToString();
                    string sql = dt.Rows[0][2].ToString();
                    OldObjectDefinition = sql;
                    _editor.Text        = sql;
                    Dirty = false;
                    OnDataLoaded();
                }
                catch (Exception ex)
                {
                    MySqlSourceTrace.WriteAppErrorToLog(ex, null, Resources.TriggerNode_UnableToLoadObjectError, true);
                }
            }

            _table = GetTargetedTable(_editor.Text);
        }
Пример #4
0
        /// <summary>
        /// Attempts to save settings values into the settings file.
        /// </summary>
        /// <returns><c>true</c> if the settings file was saved successfully, <c>false</c> otherwise.</returns>
        public static bool SaveSettings()
        {
            string errorMessage = null;

            // Attempt to save the settings file up to 3 times, if not successful show an error message to users.
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    Settings.Default.Save();
                    errorMessage = null;
                }
                catch (Exception ex)
                {
                    MySqlSourceTrace.WriteAppErrorToLog(ex);
                    errorMessage = ex.Message;
                }
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                ShowCustomizedErrorDialog(Resources.SettingsFileSaveErrorTitle, errorMessage);
            }

            return(errorMessage == null);
        }
Пример #5
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();
            }
        }
Пример #6
0
        /// <summary>
        /// Attempts to create a new schema using a connection related to the parameters in the dialog.
        /// </summary>
        /// <param name="schemaName">The name of the new schema.</param>
        /// <returns><c>true</c> if the schema is created successfully, <c>false</c> otherwise.</returns>
        private bool CreateSchema(string schemaName)
        {
            bool success = true;

            try
            {
                using (var conn = new MySqlConnectionSupport())
                {
                    var connectionStringBuilder = new MySqlConnectionStringBuilder(ConnectionString)
                    {
                        Database = string.Empty
                    };
                    conn.Initialize(null);
                    conn.ConnectionString = connectionStringBuilder.ConnectionString;
                    conn.Open(false);
                    conn.ExecuteWithoutResults(string.Format("CREATE DATABASE `{0}`", schemaName), 1, null, 0);
                }
            }
            catch (Exception ex)
            {
                success = false;
                MySqlSourceTrace.WriteAppErrorToLog(ex, Resources.ErrorTitle, string.Format(Resources.ErrorAttemptingToCreateDB, schemaName), true);
            }

            return(success);
        }
Пример #7
0
        /// <summary>
        /// Executes the select.
        /// </summary>
        /// <param name="sql">The SQL.</param>
        /// <param name="counter">Query counter</param>
        private void ExecuteSelect(string sql, int counter)
        {
            if (string.IsNullOrEmpty(sql))
            {
                return;
            }

            try
            {
                var newResPage   = Utils.CreateResultPage(counter);
                var detailedData = new DetailedResultsetView
                {
                    Dock = DockStyle.Fill
                };

                bool querySuccess = detailedData.SetQuery((MySqlConnection)Connection, sql);
                newResPage.Controls.Add(detailedData);
                ResultsTabControl.TabPages.Add(newResPage);
                ResultsTabControl.Visible = querySuccess;
                WriteToMySqlOutput(sql, string.Format("{0} row(s) returned", detailedData.AffectedRows), detailedData.ServerExecutionTime, MessageType.Information);
            }
            catch (Exception ex)
            {
                WriteToMySqlOutput(sql, ex.Message, null, MessageType.Error);
                MySqlSourceTrace.WriteAppErrorToLog(ex, false);
            }
            finally
            {
                CodeEditor.Dock = ResultsTabControl.Visible ? DockStyle.Top : DockStyle.Fill;
            }
        }
        private bool AttemptToCreateDatabase()
        {
            var prop = ConnectionProperties as MySqlConnectionProperties;

            if (prop == null)
            {
                return(false);
            }

            var    cb    = prop.ConnectionStringBuilder;
            string olddb = (string)cb["Database"];

            cb["Database"] = "";
            try
            {
                using (var conn = new MySqlConnectionSupport())
                {
                    conn.Initialize(null);
                    conn.ConnectionString = cb.ConnectionString;
                    conn.Open(false);
                    conn.ExecuteWithoutResults("CREATE DATABASE `" + dbList.Text + "`", 1, null, 0);
                }
                return(true);
            }
            catch (Exception ex)
            {
                MySqlSourceTrace.WriteAppErrorToLog(ex, null, string.Format(Resources.ErrorAttemptingToCreateDB, dbList.Text), true);
                return(false);
            }
            finally
            {
                cb["Database"] = olddb;
            }
        }
Пример #9
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                errorProvider1.Clear();
                if (txtPassword.Text != txtConfirm.Text)
                {
                    errorProvider1.SetError(txtConfirm, Resources.NewPassword_PasswordNotMatch);
                    return;
                }
                if (string.IsNullOrEmpty(txtPassword.Text))
                {
                    errorProvider1.SetError(txtPassword, Resources.NewPassword_ProvideNewPassword);
                    return;
                }

                MySqlCommand cmd = new MySqlCommand(string.Format("SET PASSWORD = PASSWORD('{0}')", txtPassword.Text), _connection);
                cmd.ExecuteNonQuery();
                _connection.Close();
                _connection.Open();
                Close();
            }
            catch (Exception ex)
            {
                MySqlSourceTrace.WriteAppErrorToLog(ex, null, Resources.MySqlNewPasswordDialog_PasswordSetError, true);
            }
        }
Пример #10
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);
            }
        }
Пример #11
0
        /// <summary>
        /// Creates the temporary <see cref="ExcelInterop.Worksheet"/> that will contain the temporary <see cref="ExcelInterop.Range"/>.
        /// </summary>
        private void CreateTempWorksheet()
        {
            if (SourceRange == null)
            {
                return;
            }

            try
            {
                var parentWorkbook = SourceRange.Worksheet.Parent as ExcelInterop.Workbook;
                if (parentWorkbook == null)
                {
                    return;
                }

                TempWorksheet         = parentWorkbook.Worksheets.Add();
                TempWorksheet.Visible = HideAndDeleteWorksheet
          ? ExcelInterop.XlSheetVisibility.xlSheetVeryHidden
          : ExcelInterop.XlSheetVisibility.xlSheetVisible;
                TempWorksheet.Name = parentWorkbook.GetWorksheetNameAvoidingDuplicates("TEMP_SHEET");
            }
            catch (Exception ex)
            {
                MySqlSourceTrace.WriteAppErrorToLog(ex);
                MiscUtilities.ShowCustomizedErrorDialog(ex.Message, ex.StackTrace);
            }
        }
Пример #12
0
        /// <summary>
        /// Gets the web config XML from the project physical path.
        /// </summary>
        /// <param name="projectPath">The path of the project.</param>
        /// <param name="checkForAppConfig">if set to <c>true</c>, gets the conn. string from the app.config file.
        /// Otherwise, will get the conn. string from the web.config file</param>
        /// <returns>The XElement XML of the web config.</returns>
        internal static XElement GetWebConfig(string projectPath, bool checkForAppConfig)
        {
            if (string.IsNullOrEmpty(projectPath))
            {
                return(null);
            }

            XElement webConfig = null;

            try
            {
                webConfig = XElement.Load(string.Format(@"{0}\{1}", projectPath, checkForAppConfig ? "app.config" : "web.config"));
            }
            catch (Exception ex)
            {
                MySqlSourceTrace.WriteAppErrorToLog(ex, null, Resources.ItemTemplateUtilities_ConfigFileGetError, true);
            }

            // Try to get the config XML from the app.config file.
            if (webConfig == null && !checkForAppConfig)
            {
                GetWebConfig(projectPath, true);
            }

            return(webConfig);
        }
Пример #13
0
 protected override void Load()
 {
     if (IsNew)
     {
         _editor.Text = GetNewViewText();
     }
     else
     {
         try
         {
             string[] restrictions = new string[3];
             restrictions[1] = Database;
             restrictions[2] = Name;
             DataTable views = GetSchema("Views", restrictions);
             if (views.Rows.Count != 1)
             {
                 throw new Exception(string.Format("There is no view with the name '{0}'", Name));
             }
             _editor.Text = string.Format("CREATE VIEW `{0}` AS \r\n{1}",
                                          Name, views.Rows[0]["VIEW_DEFINITION"]);
             OldObjectDefinition = string.Format("CREATE VIEW `{0}` AS \r\n{1}",
                                                 Name, views.Rows[0]["VIEW_DEFINITION"]);
             Dirty = false;
             OnDataLoaded();
         }
         catch (Exception ex)
         {
             MySqlSourceTrace.WriteAppErrorToLog(ex, Resources.MessageBoxErrorTitle, Resources.ViewNode_LoadViewError, true);
         }
     }
 }
Пример #14
0
        /// <summary>
        /// Event delegate method fired when <see cref="EditDataHotLabel"/> is clicked.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void EditDataHotLabel_Click(object sender, EventArgs e)
        {
            var selectedNode  = DBObjectList.SelectedNode;
            var selectedTable = selectedNode.DbObject as DbTable;

            if (selectedNode == null || selectedNode.Type != MySqlListViewNode.MySqlNodeType.DbObject || selectedTable == null || _wbConnection == null)
            {
                return;
            }

            var passwordFlags = _wbConnection.TestConnectionAndRetryOnWrongPassword();

            if (!passwordFlags.ConnectionSuccess)
            {
                return;
            }

            try
            {
                var excelAddInPane = Parent as ExcelAddInPane;
                EditDataHotLabel.Enabled = excelAddInPane != null && !excelAddInPane.EditTableData(selectedTable, false, null);
            }
            catch (Exception ex)
            {
                MiscUtilities.ShowCustomizedErrorDialog(Resources.EditDataErrorTitle, ex.Message, true);
                MySqlSourceTrace.WriteAppErrorToLog(ex);
            }
        }
Пример #15
0
        /// <summary>
        /// Event delegate method fired when <see cref="AppendDataHotLabel"/> is clicked.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void AppendDataHotLabel_Click(object sender, EventArgs e)
        {
            var selectedNode = DBObjectList.SelectedNode;

            if (selectedNode == null || selectedNode.Type != MySqlListViewNode.MySqlNodeType.DbObject || !(selectedNode.DbObject is DbTable) || _wbConnection == null)
            {
                return;
            }

            var passwordFlags = _wbConnection.TestConnectionAndRetryOnWrongPassword();

            if (!passwordFlags.ConnectionSuccess)
            {
                return;
            }

            try
            {
                ExportDataToTable(selectedNode.DbObject as DbTable);
            }
            catch (Exception ex)
            {
                MiscUtilities.ShowCustomizedErrorDialog(Resources.AppendDataErrorTitle, ex.Message, true);
                MySqlSourceTrace.WriteAppErrorToLog(ex);
            }
            finally
            {
                if (Cursor == Cursors.WaitCursor)
                {
                    Cursor = Cursors.Default;
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Gets the web config XML from the "edmx" file.
        /// </summary>
        /// <param name="edmxFileName">Name of the edmx file.</param>
        /// <param name="dte">The DTE object.</param>
        /// <param name="checkForAppConfig">if set to <c>true</c>, gets the conn. string from the app.config file.
        /// Otherwise, will get the conn. string from the web.config file.</param>
        /// <returns>The XElement XML of the web config.</returns>
        internal static XElement GetWebConfig(string edmxFileName, DTE dte, bool checkForAppConfig)
        {
            if (string.IsNullOrEmpty(edmxFileName))
            {
                return(null);
            }

            string projectPath    = string.Empty;
            Array  activeProjects = (Array)dte.ActiveSolutionProjects;

            if (activeProjects.Length > 0)
            {
                Project   activeProj = (Project)activeProjects.GetValue(0);
                VSProject vsProj     = activeProj.Object as VSProject;
                projectPath = System.IO.Path.GetDirectoryName(activeProj.FullName);
            }

            XElement webConfig = null;

            if (!string.IsNullOrEmpty(projectPath))
            {
                try
                {
                    webConfig = XElement.Load(string.Format(@"{0}\{1}", projectPath, checkForAppConfig ? "app.config" : "web.config"));
                }
                catch (Exception ex)
                {
                    MySqlSourceTrace.WriteAppErrorToLog(ex, null, Resources.ItemTemplateUtilities_ConfigFileGetError, true);
                }
            }

            return(webConfig);
        }
Пример #17
0
        /// <summary>
        /// Event delegate method fired when the <see cref="PreviewDataGridView"/> detects a data error in one of its cells.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void PreviewDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if (PreviewDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ValueType != Type.GetType("System.Byte[]"))
            {
                return;
            }

            try
            {
                var img = (byte[])(PreviewDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex]).Value;
                using (var ms = new MemoryStream(img))
                {
                    Image.FromStream(ms);
                }
            }
            catch (ArgumentException argEx)
            {
                MySqlSourceTrace.WriteAppErrorToLog(argEx);
            }
            catch (Exception ex)
            {
                MiscUtilities.ShowCustomizedErrorDialog(Resources.DataLoadingError, ex.Message);
                MySqlSourceTrace.WriteAppErrorToLog(ex);
            }
        }
        /// <summary>
        /// Fetches all schema names from the current connection and loads them in the <see cref="SchemasList"/> tree.
        /// </summary>
        /// <returns><c>true</c> if schemas were loaded successfully, <c>false</c> otherwise.</returns>
        private bool LoadSchemas()
        {
            if (SchemasList.HeaderNodes.Count < 2)
            {
                return(false);
            }

            try
            {
                // Avoids flickering of schemas list while adding the items to it.
                SchemasList.BeginUpdate();

                LoadedSchemas.ForEach(schema => schema.Dispose());
                LoadedSchemas.Clear();
                foreach (TreeNode node in SchemasList.Nodes)
                {
                    node.Nodes.Clear();
                }

                DataTable databases = _wbConnection.GetSchemaCollection("Databases", null);
                foreach (DataRow row in databases.Rows)
                {
                    string schemaName = row["DATABASE_NAME"].ToString();

                    // If the user has specified a filter then check it
                    if (!string.IsNullOrEmpty(_filter) && !schemaName.ToUpper().Contains(_filter))
                    {
                        continue;
                    }

                    // Create the DbSchema and MySqlListViewNode objects
                    var    schemaObject = new DbSchema(_wbConnection, schemaName, row["DEFAULT_CHARACTER_SET_NAME"].ToString(), row["DEFAULT_COLLATION_NAME"].ToString(), DisplaySchemaCollationsToolStripMenuItem.Checked);
                    string lcSchemaName = schemaName.ToLowerInvariant();
                    var    headerNode   = SchemasList.HeaderNodes[_systemSchemasListValues.Contains(lcSchemaName) ? 1 : 0];
                    LoadedSchemas.Add(schemaObject);
                    var node = SchemasList.AddDbObjectNode(headerNode, schemaObject);
                    node.ImageIndex = DisplaySchemaCollationsToolStripMenuItem.Checked ? 1 : 0;
                }

                if (SchemasList.Nodes[0].GetNodeCount(true) > 0)
                {
                    SchemasList.Nodes[0].Expand();
                }

                // Avoids flickering of schemas list while adding the items to it.
                SchemasList.EndUpdate();

                return(true);
            }
            catch (Exception ex)
            {
                MiscUtilities.ShowCustomizedErrorDialog(Resources.SchemasLoadingErrorTitle, ex.Message, true);
                MySqlSourceTrace.WriteAppErrorToLog(ex);
                return(false);
            }
        }
Пример #19
0
        /// <summary>
        /// Gets the metadata information for a specific sql command query.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="connection"></param>
        /// <param name="sqlFilter">The SQL filter command.</param>
        /// <param name="sqlData">The SQL data.</param>
        /// <returns>A dictionary with the metadata information.</returns>
        private static Dictionary <string, T> GetMetadata <T>(MySqlConnection connection, string sqlFilter, string sqlData) where T : MetaObject, new()
        {
            Dictionary <string, T> dic = new Dictionary <string, T>();

            if (connection != null && (connection.State & ConnectionState.Open) == 0)
            {
                connection.Open();
            }

            try
            {
                MySqlCommand  cmd = new MySqlCommand(string.Empty, connection);
                StringBuilder sb  = new StringBuilder();

                if (!string.IsNullOrEmpty(sqlFilter))
                {
                    sb.Append("( ");
                    cmd.CommandText = sqlFilter;

                    using (MySqlDataReader r1 = cmd.ExecuteReader())
                    {
                        while (r1.Read())
                        {
                            sb.Append("'").Append(r1.GetString(0)).Append("',");
                        }
                    }

                    sb.Length = sb.Length - 1;
                    sb.Append(" ) ");
                    cmd.CommandText = string.Format(sqlData, sb);
                }
                else
                {
                    cmd.CommandText = sqlData;
                }

                // Get columns
                using (MySqlDataReader r = cmd.ExecuteReader())
                {
                    while (r.Read())
                    {
                        T t = new T();
                        t.Connection = connection;
                        t.Initialize(r);
                        dic.Add(t.Name, t);
                    }
                }
            }
            catch (Exception ex)
            {
                MySqlSourceTrace.WriteAppErrorToLog(ex, null, Resources.ItemTemplateUtilities_RetrieveMetadataError, true);
            }

            return(dic);
        }
Пример #20
0
        /// <summary>
        /// Delegate method that asynchronously monitors semi-sync WMI services creation.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void ServiceCreationWatcherStartSemiSyncDoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker         = sender as BackgroundWorker;
            Exception        throwException = null;

            if (worker != null && worker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            try
            {
                int             eventCount = 0;
                ManagementScope scope      = e.Argument as ManagementScope;
                _wmiAsyncCreationWatcher = _wmiAsyncCreationWatcher ?? new ManagementEventWatcher(scope, new WqlEventQuery("__InstanceCreationEvent", TimeSpan.FromSeconds(WmiQueriesTimeoutInSeconds), WMI_QUERIES_WHERE_CLAUSE));
                while (worker != null && !worker.CancellationPending)
                {
                    ManagementBaseObject remoteService = _wmiAsyncCreationWatcher.WaitForNextEvent();
                    if (remoteService != null)
                    {
                        worker.ReportProgress(++eventCount, remoteService);
                    }
                }
            }
            catch (Exception ex)
            {
                throwException = ex;
            }

            if (worker != null && worker.CancellationPending)
            {
                e.Cancel = true;
            }

            try
            {
                if (_wmiAsyncCreationWatcher != null)
                {
                    _wmiAsyncCreationWatcher.Stop();
                    _wmiAsyncCreationWatcher.Dispose();
                }

                _wmiAsyncCreationWatcher = null;
            }
            catch (Exception ex)
            {
                MySqlSourceTrace.WriteAppErrorToLog(ex);
            }

            if (throwException != null)
            {
                throw throwException;
            }
        }
Пример #21
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);
        }
Пример #22
0
        /// <summary>
        /// Fills the <see cref="SchemaComboBox"/> with a list of schemas in the connected MySQL Server.
        /// </summary>
        private void InitializeSchemasComboBox()
        {
            Cursor = Cursors.WaitCursor;
            SchemaComboBox.Items.Clear();
            try
            {
                using (var connection = _factory.CreateConnection())
                {
                    var mySqlConnection = connection as MySqlConnection;
                    if (mySqlConnection == null)
                    {
                        return;
                    }

                    mySqlConnection.ConnectionString = ConnectionString;
                    mySqlConnection.Open();
                    _schemasTable = mySqlConnection.GetSchema("Databases");
                    if (_schemasTable == null || _schemasTable.Rows.Count == 0)
                    {
                        return;
                    }

                    // Remove rows containing system schemas
                    foreach (var sysSchemaName in MySqlWorkbenchConnection.SystemSchemaNames)
                    {
                        var result = _schemasTable.Select(string.Format("DATABASE_NAME = '{0}'", sysSchemaName));
                        if (result.Length == 0)
                        {
                            continue;
                        }

                        foreach (var row in result)
                        {
                            row.Delete();
                        }
                    }

                    _schemasTable.AcceptChanges();
                    SchemaComboBox.DisplayMember = "DATABASE_NAME";
                    SchemaComboBox.ValueMember   = "DATABASE_NAME";
                    SchemaComboBox.DataSource    = _schemasTable;
                }
            }
            catch (Exception ex)
            {
                MySqlSourceTrace.WriteAppErrorToLog(ex, Resources.ErrorTitle, Resources.ConnectDialog_SchemasFetchError, true);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
Пример #23
0
 /// <summary>
 /// Unlocks tables locked in the current session.
 /// </summary>
 /// <param name="connection">MySQL Workbench connection to a MySQL server instance selected by users.</param>
 public static void UnlockTablesInClientSession(this MySqlWorkbenchConnection connection)
 {
     try
     {
         const string sql = "UNLOCK TABLES";
         MySqlHelper.ExecuteNonQuery(connection.GetConnectionStringBuilder().ConnectionString, sql);
     }
     catch (Exception ex)
     {
         MiscUtilities.ShowCustomizedErrorDialog(Resources.UnableToUnlockTablesError, ex.Message);
         MySqlSourceTrace.WriteAppErrorToLog(ex);
     }
 }
Пример #24
0
 /// <summary>
 /// Event delegate method fired when the <see cref="QueryChangedTimer"/> text changes.
 /// </summary>
 /// <param name="sender">Sender object.</param>
 /// <param name="e">Event arguments.</param>
 private void QueryChangedTimer_Tick(object sender, EventArgs e)
 {
     if (QueryTextBox.Focused)
     {
         QueryTextBox_Validated(QueryTextBox, EventArgs.Empty);
     }
     else
     {
         // The code should never hit this block in which case there is something wrong.
         MySqlSourceTrace.WriteToLog("QueryChangedTimer's Tick event fired but no valid control had focus.");
         QueryChangedTimer.Stop();
     }
 }
Пример #25
0
        /// <summary>
        /// Undoes changes in the <see cref="EditingWorksheet"/> only.
        /// </summary>
        private void UndoChanges()
        {
            Globals.ThisAddIn.SkipWorksheetChangeEvent = true;
            try
            {
                EditingWorksheet.Application.Undo();
            }
            catch (Exception ex)
            {
                MySqlSourceTrace.WriteAppErrorToLog(ex);
            }

            Globals.ThisAddIn.SkipWorksheetChangeEvent = false;
        }
Пример #26
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);
        }
        private void dbList_DropDown(object sender, EventArgs e)
        {
            if (_dbListPopulated)
            {
                return;
            }

            var prop = ConnectionProperties as MySqlConnectionProperties;

            if (prop == null)
            {
                return;
            }

            var cb = prop.ConnectionStringBuilder;

            try
            {
                using (var conn = new MySqlConnectionSupport())
                {
                    conn.Initialize(null);
                    conn.ConnectionString = cb.ConnectionString;
                    conn.Open(false);
                    dbList.Items.Clear();
                    using (var reader = conn.Execute("SHOW DATABASES", 1, null, 0))
                    {
                        while (reader.Read())
                        {
                            string dbName = reader.GetItem(0).ToString().ToLowerInvariant();
                            if (dbName == "information_schema")
                            {
                                continue;
                            }
                            if (dbName == "mysql")
                            {
                                continue;
                            }
                            dbList.Items.Add(reader.GetItem(0));
                        }
                        _dbListPopulated = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MySqlSourceTrace.WriteAppErrorToLog(ex, Resources.ErrorTitle, Resources.UnableToRetrieveDatabaseList, true);
            }
        }
        private void OnInvokedDynamicItem(object sender, EventArgs args)
        {
            var invokedCommand = sender as DynamicItemMenuCommand;

            if (invokedCommand == null)
            {
                return;
            }

            bool isRootItem      = invokedCommand.MatchedCommandId == 0;
            int  indexForDisplay = isRootItem ? 0 : invokedCommand.MatchedCommandId - _baselistID;

            if (MySqlDataProviderPackage.Instance == null)
            {
                return;
            }

            try
            {
                if (indexForDisplay < _connectionsList.Count)
                {
                    var connection = (MySqlConnection)_connectionsList[indexForDisplay].Connection.GetLockedProviderObject();
                    try
                    {
                        if (connection != null)
                        {
                            MySqlDataProviderPackage.Instance.SelectedMySqlConnection = connection;
                        }

                        var itemOp = MySqlDataProviderPackage.Instance.GetDTE2().ItemOperations;
                        itemOp.NewFile(@"MySQL\MySQL Script", null, "{A2FE74E1-B743-11D0-AE1A-00A0C90FFFC3}");
                    }
                    finally
                    {
                        _connectionsList[indexForDisplay].Connection.UnlockProviderObject();
                    }
                }
                else
                {
                    var itemOp = MySqlDataProviderPackage.Instance.GetDTE2().ItemOperations;
                    itemOp.NewFile(@"MySQL\MySQL Script", null, "{A2FE74E1-B743-11D0-AE1A-00A0C90FFFC3}");
                }
            }
            catch (Exception ex)
            {
                MySqlSourceTrace.WriteAppErrorToLog(ex, null, Resources.MySqlScriptWindowLaunchError, true);
            }
        }
Пример #29
0
        /// <summary>
        /// Callback method specified within the onAction attribute of a ribbon control declared in the Ribbon.xml.
        /// </summary>
        /// <param name="control">A ribbon control.</param>
        /// <param name="buttonPressed">Flag indicating whether the toggle button is depressed.</param>
        public void OnClickMySqlForExcel(OfficeCore.IRibbonControl control, bool buttonPressed)
        {
            ShowMySqlForExcelPaneTogglePressed = buttonPressed;
            Microsoft.Office.Tools.CustomTaskPane taskPane = Globals.ThisAddIn.GetOrCreateActiveCustomPane();
            if (taskPane == null)
            {
                MySqlSourceTrace.WriteToLog(string.Format("Could not get or create a custom task pane for the active Excel window. Using Excel version {0}.", Globals.ThisAddIn.ExcelVersionNumber));
                return;
            }

            taskPane.Visible = buttonPressed;
            if (!buttonPressed)
            {
                Globals.ThisAddIn.CloseExcelPane(taskPane.Control as ExcelAddInPane);
            }
        }
Пример #30
0
        /// <summary>
        /// Retrieves all the information for a given Foreign Key, for the specified table.
        /// </summary>
        /// <param name="con">The MySql connection.</param>
        /// <param name="tableName">Name of the table.</param>
        /// <param name="MyFKs">A dictionary containing the information for the related foreign keys.</param>
        internal static void RetrieveAllFkInfo(MySqlConnection con, string tableName, out Dictionary <string, ForeignKeyColumnInfo> MyFKs)
        {
            string sql = string.Format(@"select `constraint_name`, `table_name`, `column_name`, `referenced_table_name`, `referenced_column_name`
                                  from information_schema.key_column_usage where table_schema = '{0}' and `constraint_name` in
                                  (select `constraint_name` from information_schema.referential_constraints where `constraint_schema` = '{0}' and `table_name` = '{1}')", con.Database, tableName);

            if ((con.State & ConnectionState.Open) == 0)
            {
                con.Open();
            }

            Dictionary <string, ForeignKeyColumnInfo> FKs = new Dictionary <string, ForeignKeyColumnInfo>();

            // Gather FK info per column pair
            try
            {
                MySqlCommand cmd = new MySqlCommand(sql, con);
                using (MySqlDataReader r = cmd.ExecuteReader())
                {
                    while (r.Read())
                    {
                        ForeignKeyColumnInfo fk = new ForeignKeyColumnInfo()
                        {
                            ConstraintName       = r.GetString(0),
                            TableName            = r.GetString(1),
                            ColumnName           = r.GetString(2),
                            ReferencedTableName  = r.GetString(3),
                            ReferencedColumnName = r.GetString(4)
                        };

                        FKs.Add(fk.ColumnName, fk);
                    }
                }
            }
            catch (MySqlException ex)
            {
                MySqlSourceTrace.WriteAppErrorToLog(ex, null, Resources.ItemTemplateUtilities_RetrieveFkError, true);
            }

            // Gather referenceable columns
            foreach (ForeignKeyColumnInfo fk in FKs.Values)
            {
                fk.ReferenceableColumns = GetColumnsFromTableVanilla(fk.ReferencedTableName, con);
            }

            MyFKs = FKs;
        }