Exemplo n.º 1
0
        /// <summary>
        /// Reverts the changes done to Excel cell values after the last commit.
        /// </summary>
        /// <param name="refreshFromDb">Flag indicating if instead of reverting the data back to the way it was when the editing session started, it is pulled to have the most recent version of it.</param>
        private void RevertDataChanges(bool refreshFromDb)
        {
            try
            {
                if (!refreshFromDb)
                {
                    _mySqlTable.RejectChanges();
                }
                else
                {
                    _mySqlTable.RefreshData();
                }
            }
            catch (Exception ex)
            {
                MiscUtilities.ShowCustomizedErrorDialog(Resources.EditDataRefreshErrorText, ex.Message);
            }

            Globals.ThisAddIn.SkipSelectedDataContentsDetection = true;
            EditingWorksheet.UnprotectEditingWorksheet(EditingWorksheet_Change, WorksheetProtectionKey);
            _editDataRange.Clear();
            ExcelInterop.Range topLeftCell = _editDataRange.Cells[1, 1];
            topLeftCell.Select();
            _editDataRange = _mySqlTable.ImportDataIntoExcelRange(topLeftCell);
            CommitChangesButton.Enabled = false;
            AddNewRowToEditingRange(false);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Retrieves information about a database that the application is currently connected to.
        /// </summary>
        /// <param name="databaseManager">Database manager object that handles the connection to
        /// the database.</param>
        /// <param name="commonDatabaseErrorCode">Structure holding the common database-related
        /// error codes.</param>
        /// <param name="oErrorInfo">Output parameter: Details of any error that may have
        /// occurred.</param>
        /// <returns>A structure containing the database metadata.</returns>
        public static DatabaseInfo GetDatabaseInfo <T>(DatabaseManager2 databaseManager,
                                                       CommonDatabaseErrorCode <T> commonDatabaseErrorCode, out ErrorInfo <T> oErrorInfo)
            where T : IComparable, IFormattable, IConvertible
        {
            DatabaseInfo  dbInfo    = new DatabaseInfo();
            ErrorInfo <T> errorInfo = new ErrorInfo <T>();

            lock (_lockGetDatabaseInfo)
            {
                try
                {
                    errorInfo.ErrorCode = commonDatabaseErrorCode.GeneralError;
                    errorInfo.Message   = string.Empty;
                    // Cannot convert generic type to int directly so cheat by using object.
                    object value = commonDatabaseErrorCode.Success;
                    errorInfo.DatabaseErrorValue = (int)value;

                    DataTable dbMetaData = databaseManager.GetDataTable("p_GetDatabaseInfo",
                                                                        out errorInfo.DatabaseErrorValue, out errorInfo.Message);

                    // Check for unrecognised error code from the database.
                    errorInfo.ErrorCode = BBError.ValidateDBErrorValue <T>(
                        errorInfo.DatabaseErrorValue, commonDatabaseErrorCode.GeneralDBError);

                    if (dbMetaData != null && dbMetaData.Rows.Count > 0)
                    {
                        dbInfo.DatabaseTitle   = (dbMetaData.Rows[0]["DatabaseTitle"]).ToString();
                        dbInfo.DatabaseVersion = (int)dbMetaData.Rows[0]["DatabaseVersion"];

                        // Check that database type is valid.
                        string       databaseTypeText = (dbMetaData.Rows[0]["DatabaseType"]).ToString();
                        DatabaseType databaseType     = DatabaseType.NotFound;
                        if (MiscUtilities.ValidateEnumValue <DatabaseType>(databaseTypeText,
                                                                           out databaseType))
                        {
                            dbInfo.DatabaseType = databaseType;
                            errorInfo.ErrorCode = commonDatabaseErrorCode.Success;
                        }
                        else
                        {
                            dbInfo.DatabaseType = DatabaseType.Invalid;
                            errorInfo.ErrorCode = commonDatabaseErrorCode.InvalidType;
                        }
                    }
                    else
                    {
                        dbInfo.DatabaseType = DatabaseType.NotFound;
                        errorInfo.ErrorCode = commonDatabaseErrorCode.NoInfo;
                    }
                }
                catch
                {
                    errorInfo.ErrorCode = commonDatabaseErrorCode.GeneralError;
                }
            }

            oErrorInfo = errorInfo;
            return(dbInfo);
        }
        /// <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);
            }
        }
Exemplo n.º 4
0
        public CableInfo(Database.DbElement aCable)
        {
            //if given cable is valid in db:
            if (aCable.IsValid)
            {
                //get name of given cable
                mCableName = aCable.GetAsString(Database.DbAttributeInstance.NAMN);

                //get cable component name
                if (aCable.IsAttributeValid(Database.DbAttributeInstance.SPRE))
                {
                    Database.DbElement _spref = aCable.GetElement(Database.DbAttributeInstance.SPRE);
                    if (_spref.IsValid)
                    {
                        mComponentName = _spref.GetAsString(Database.DbAttributeInstance.NAMN);
                    }
                }

                Database.DbElement _staref = aCable.GetElement(Database.DbAttributeInstance.STAREF);
                if (_staref.IsValid)
                {
                    if (_staref.GetElementType() == Database.DbElementTypeInstance.SCELCONNECTION)
                    {
                        mStartElconn = MiscUtilities.GetElemPresName(_staref);
                        mStartEqui   = MiscUtilities.GetElemPresName(_staref.Owner);
                    }
                    else
                    {
                        mStartEqui = MiscUtilities.GetElemPresName(_staref);
                    }
                }

                Database.DbElement _endref = aCable.GetElement(Database.DbAttributeInstance.ENDREF);
                if (_endref.IsValid)
                {
                    if (_endref.GetElementType() == Database.DbElementTypeInstance.SCELCONNECTION)
                    {
                        mEndElconn = MiscUtilities.GetElemPresName(_endref);
                        mEndEqui   = MiscUtilities.GetElemPresName(_endref.Owner);
                    }
                    else
                    {
                        mEndEqui = MiscUtilities.GetElemPresName(_endref);
                    }
                }

                Database.DbElement [] _cores = aCable.Members(Database.DbElementTypeInstance.SCCORE);

                //get informaton about cores
                foreach (Database.DbElement _core in _cores)
                {
                    CoreInfo _coreInf = new CoreInfo(_core, this);
                    mCores.Add(_coreInf);
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Event delegate method fired when the <see cref="AddRelatedTablesToolStripMenuItem"/> context menu item is clicked.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void AddRelatedTablesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectedTableOrView = MiscUtilities.GetSelectedDbTableOrView(sender) as DbTable;

            if (selectedTableOrView == null)
            {
                return;
            }

            AddRelatedTablesToRelatedTablesListView(selectedTableOrView, false, true);
            RelatedTablesListView.Sort();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        /// <remarks>
        /// Credits to enohka for this method.
        /// See more at: http://github.com/enohka/moddingSuite
        /// </remarks>
        protected virtual EdataHeader ReadHeader(Stream stream)
        {
            EdataHeader header;

            var buffer = new byte[Marshal.SizeOf(typeof(EdataHeader))];

            stream.Read(buffer, 0, buffer.Length);

            header = MiscUtilities.ByteArrayToStructure <EdataHeader>(buffer);

            return(header);
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            MiscUtilities util = new MiscUtilities();

            Console.WriteLine(util.KiloToPounds(1.0));
            Console.WriteLine(util.PoundsToKilo(2.2));
            Console.WriteLine(util.TemperatureFtoC(32.0));
            Console.WriteLine(util.TemperatureCtoF(100.0));
            Console.WriteLine(util.CalculateBMI(75, 2, true));
            Console.WriteLine(util.CalculateBMI(150, 68, false));

            Console.Read();
        }
        /// <remarks>
        /// Method based on enohka's code.
        /// See more at: http://github.com/enohka/moddingSuite
        /// </remarks>
        protected virtual void WriteHeader(Stream target, EdataFile edataFile)
        {
            //var sourceEdataHeader = edataFile.Header;
            //var headerPart = new byte[sourceEdataHeader.FileOffset];
            //sourceEdata.Read(headerPart, 0, headerPart.Length);
            //newEdata.Write(headerPart, 0, headerPart.Length);

            var sourceEdataHeader = edataFile.Header;

            byte[] rawHeader = MiscUtilities.StructToBytes(sourceEdataHeader);
            target.Write(rawHeader, 0, rawHeader.Length);
            target.Write(edataFile.PostHeaderData, 0, edataFile.PostHeaderData.Length);
        }
        protected virtual ProxyHeader ReadHeader(Stream source, uint offset = 0)
        {
            ProxyHeader header;

            var buffer = new byte[Marshal.SizeOf(typeof(ProxyHeader))];

            source.Seek(0, SeekOrigin.Begin);
            source.Read(buffer, 0, buffer.Length);

            header = MiscUtilities.ByteArrayToStructure <ProxyHeader>(buffer);

            return(header);
        }
Exemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        /// <remarks>
        /// Credits to enohka for this code.
        /// See more at: http://github.com/enohka/moddingSuite
        /// </remarks>
        public virtual TgvImage Read(String filePath)
        {
            var file = new TgvImage();

            byte[] rawDDSData = File.ReadAllBytes(filePath);
            using (var ms = new MemoryStream(rawDDSData))
            {
                var buffer = new byte[4];
                ms.Read(buffer, 0, buffer.Length);

                if (BitConverter.ToUInt32(buffer, 0) != DDSFormat.MagicHeader)
                {
                    throw new ArgumentException("Wrong DDS magic");
                }

                buffer = new byte[Marshal.SizeOf(typeof(DDSFormat.Header))];
                ms.Read(buffer, 0, buffer.Length);

                var header = MiscUtilities.ByteArrayToStructure <DDSFormat.Header>(buffer);
                header.MipMapCount = 1;

                DDSHelper.ConversionFlags conversionFlags;
                var format = DDSHelper.GetDXGIFormat(ref header.PixelFormat, out conversionFlags);

                //read only the main content mipmap
                uint minMipByteLength = DDSMipMapUilities.GetMinimumMipMapSizeForFormat(header.PixelFormat);
                uint mipByteLength    = (uint)DDSMipMapUilities.GetMipMapBytesCount((int)header.Width, (int)header.Height, format);
                mipByteLength = Math.Max(minMipByteLength, mipByteLength);

                buffer = new byte[mipByteLength];
                ms.Read(buffer, 0, buffer.Length);

                var mip = new TgvMipMap();
                mip.Content   = buffer;
                mip.Length    = mipByteLength;
                mip.MipSize   = header.Width * header.Height;
                mip.MipWidth  = header.Width;
                mip.MipHeight = header.Height;

                file.MipMapCount = (ushort)header.MipMapCount;
                file.MipMaps.Add(mip);
                file.Height            = header.Height;
                file.ImageHeight       = header.Height;
                file.Width             = header.Width;
                file.ImageWidth        = header.Width;
                file.Format            = format;
                file.PixelFormatString = TgvUtilities.GetTgvFromPixelFormat(format);
            }

            return(file);
        }
Exemplo n.º 11
0
        private void RemoveEntries(Dictionary <byte[], TradDictEntry> dictionary)
        {
            foreach (var entryHash in Command.RemovedEntries)
            {
                var hash = MiscUtilities.HexByteStringToByteArray(entryHash);

                if (!dictionary.Remove(hash))
                {
                    var warning = String.Format("RemoveEntry operation failed " +
                                                "because entry with the given hash \"{0}\" wasn't found.", entryHash);
                    Common.Logging.LoggerFactory.Create(this.GetType()).Warn(warning);
                }
            }
        }
        protected ContentFileType ResolveFileType(byte[] binData)
        {
            foreach (var containerType in KnownContainerTypes)
            {
                if (MiscUtilities.ComparerByteArrays(
                        containerType.MagicBytes,
                        binData.Take(containerType.MagicBytes.Length).ToArray()))
                {
                    return(containerType);
                }
            }

            return(ContentFileType.Unknown);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Event delegate method fired when the <see cref="PreviewDataToolStripMenuItem"/> context menu item is clicked.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void PreviewDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var previewTableOrView = MiscUtilities.GetSelectedDbTableOrView(sender);

            if (previewTableOrView == null)
            {
                return;
            }

            using (var previewDialog = new PreviewTableViewDialog(previewTableOrView, false))
            {
                previewDialog.ShowDialog();
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// public constructor
        /// </summary>
        /// <param name="aCore">database core element to get information from</param>
        public CoreInfo(Database.DbElement aCore, CableInfo aCableInfo)
        {
            mStartElconn = aCableInfo.StartElconn;
            mStartEqui   = aCableInfo.StartEqui;
            mEndElconn   = aCableInfo.EndElconn;
            mEndEqui     = aCableInfo.EndEqui;

            if (aCore.IsValid)
            {
                // get core name
                mCoreName = aCore.GetAsString(Database.DbAttributeInstance.NAMN);

                // get information about elements connected to core head
                Database.DbElement _elconn = aCore.GetElement(Database.DbAttributeInstance.STAREF);
                if (_elconn.IsValid)
                {
                    mStartElconn = MiscUtilities.GetElemPresName(_elconn);
                    mStartEqui   = MiscUtilities.GetElemPresName(_elconn.Owner);
                }

                int _point = aCore.GetInteger(Database.DbAttributeInstance.STAPOI);
                if (_point == 0)
                {
                    mStartPin = UNSET_TEXT;
                }
                else
                {
                    mStartPin = string.Format(PIN_TEMPLATE, _point.ToString());
                }

                // get information about elements connected to core tail
                _elconn = aCore.GetElement(Database.DbAttributeInstance.ENDREF);
                if (_elconn.IsValid)
                {
                    mEndElconn = MiscUtilities.GetElemPresName(_elconn);
                    mEndEqui   = MiscUtilities.GetElemPresName(_elconn.Owner);
                }

                _point = aCore.GetInteger(Database.DbAttributeInstance.ENDPOI);
                if (_point == 0)
                {
                    mEndPin = UNSET_TEXT;
                }
                else
                {
                    mEndPin = string.Format(PIN_TEMPLATE, _point.ToString());
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Checks to see if the error value returned from a call to the database is a valid
        /// error code.
        /// </summary>
        /// <typeparam name="TErrorCodeEnum">Type of the error code enum that the database error
        /// value should be a member of.</typeparam>
        /// <param name="dbErrorValue">Error value returned from a call to the database.</param>
        /// <param name="defaultErrorCode">Error code that is returned if the database error
        /// value is not valid.</param>
        /// <returns>Error code enum.  If the database error value is valid it is converted to
        /// an error code enum.  If it is not valid the default error code is returned.</returns>
        public static TErrorCodeEnum ValidateDBErrorValue <TErrorCodeEnum>(int dbErrorValue,
                                                                           TErrorCodeEnum defaultErrorCode)
            where TErrorCodeEnum : IComparable, IFormattable, IConvertible
        {
            lock (_lockValidateDBErrorValue)
            {
                TErrorCodeEnum errorCode = default(TErrorCodeEnum);
                if (MiscUtilities.ValidateEnumValue <TErrorCodeEnum>(dbErrorValue, out errorCode))
                {
                    return(errorCode);
                }

                return(defaultErrorCode);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="headerData"></param>
        /// <returns></returns>
        protected ContentFileType GetFileTypeFromHeaderData(byte[] headerData)
        {
            foreach (var knownType in KnownContentFileTypes)
            {
                byte[] headerMagic = new byte[knownType.Value.Length];
                Array.Copy(headerData, headerMagic, knownType.Value.Length);

                if (MiscUtilities.ComparerByteArrays(headerMagic, knownType.Value))
                {
                    return(knownType.Key);
                }
            }

            return(ContentFileType.Unknown);
        }
        /// <summary>
        /// Event delegate method fired when the <see cref="RenameMappingButton"/> button is clicked.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void RenameMappingButton_Click(object sender, EventArgs e)
        {
            if (_selectedMapping == null)
            {
                return;
            }

            int    indexForName = 1;
            string proposedMappingName;

            do
            {
                proposedMappingName = _selectedMapping.TableName + "Mapping" + (indexForName > 1 ? indexForName.ToString(CultureInfo.InvariantCulture) : string.Empty);
                indexForName++;
            }while (Mappings.Any(mapping => mapping.Name == proposedMappingName));

            string newName;

            using (var newColumnMappingDialog = new AppendNewColumnMappingDialog(proposedMappingName))
            {
                DialogResult dr = newColumnMappingDialog.ShowDialog();
                if (dr == DialogResult.Cancel)
                {
                    return;
                }

                MappingsChanged = true;
                newName         = newColumnMappingDialog.ColumnMappingName;
            }

            // Show error if name already exists
            if (Mappings.Count(t => string.Compare(t.Name, newName, StringComparison.InvariantCultureIgnoreCase) == 0) > 0)
            {
                MiscUtilities.ShowCustomizedErrorDialog(Resources.MappingNameAlreadyExistsTitle, Resources.MappingNameAlreadyExistsDetail);
                return;
            }

            _selectedMapping.Name = newName;
            RefreshMappingList();
            ListViewItem item = MappingsListView.FindItemWithText(string.Format("{0} ({1}.{2})", newName, _selectedMapping.SchemaName, _selectedMapping.TableName));

            if (item != null)
            {
                MappingsListView.Items[item.Index].Selected = true;
            }

            MappingsListView.Focus();
        }
Exemplo n.º 18
0
        public bool UpdateCharacter(Character original, Character newValues)
        {
            bool success      = false;
            var  itemToUpdate = _testCollection.Where(charac => charac.FirstName == original.FirstName && charac.LastName == original.LastName &&
                                                      charac.Age == original.Age && charac.City == original.City && charac.State == original.State && charac.ZipCode == original.ZipCode &&
                                                      charac.StreetAddress == original.StreetAddress).FirstOrDefault();

            if (itemToUpdate != null)
            {
                MiscUtilities.Copy(itemToUpdate, newValues);
                success = true;
            }


            return(success);
        }
Exemplo n.º 19
0
        protected Boolean BackupCastDatabase(int JobKey, String JobFileName, String RawJobFileName)
        {
            Dictionary <String, Object> sqlParameters = new Dictionary <string, object>();

            sqlParameters.Add(":inprogress", true);
            sqlParameters.Add(":scanrequested", true);
            sqlParameters.Add(":jobstatus", "Ready");
            sqlParameters.Add(":statusdescription", String.Format("Backup Started: {0:MMMM d, yyyy HH:mm:ss}", DateTime.Now));
            sqlParameters.Add(":machinename", Environment.MachineName);
            sqlParameters.Add(":jobkey", JobKey);

            JobFileName = _tokens.Resolve("Scheduler", "BackupDatabase", "Missing the Scheduler/BackupDatabase attribute with the name of the backup definition. SQL query. Please add the name of the backup definition to the settings file under SchedulerSettings/Tokens/Scheduler BackupDatabase");
            // Look for backup database request
            DataTable dt = SqlUtilities.GetData(_ConnectionString, _SqlNextDbBackup);

            if ((dt == null) || (dt.Rows.Count == 0))
            {
                return(false);
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                try
                {
                    JobKey = MiscUtilities.ObjectToInteger(dt.Rows[0]["pkey"], "No primary key is definied");
                    sqlParameters[":jobkey"] = JobKey;
                    RunJava(JobKey, JobFileName, RawJobFileName);

                    // Job finished update record.
                    sqlParameters[":jobstatus"]         = "Backup Completed";
                    sqlParameters[":statusdescription"] = String.Format("Backup Completed: {0:MMMM d, yyyy HH:mm:ss}", DateTime.Now);
                }
                catch (Exception ex)
                {
                    LocalLog.AddLine("Database Backup Error: " + ex.Message);
                    sqlParameters[":jobstatus"] = "Error";
                    String message = String.Format("Recorded: {0:MMMM d, yyyy HH:mm:ss}, Message: {1} ", DateTime.Now, ex.Message);
                    if (message.Length > 99)
                    {
                        message = message.Substring(0, 99);
                    }
                    sqlParameters[":statusdescription"] = message;
                }
                SqlUtilities.ExcecuteNonQuery(_ConnectionString, _SqlUpdateInProgressStatus, sqlParameters);
            }
            return(false);
        }
Exemplo n.º 20
0
        public void SetHeights(int x, int z, Serializable2DFloatArray heights, int heightRes, Serializable2DFloatArray stencil = null)
        {
            if (heights == null)
            {
                return;
            }
            if (Heights == null || Heights.Width != heightRes || Heights.Height != heightRes)
            {
                Heights = new Serializable2DFloatArray(heightRes, heightRes);
            }
            var width  = heights.Width;
            var height = heights.Height;

            for (var u = x; u < x + width; ++u)
            {
                for (var v = z; v < z + height; ++v)
                {
                    var hx = u - x;
                    var hz = v - z;
                    try
                    {
                        var heightsSample = heights[hx, hz];
                        heightsSample = Mathf.Clamp01(heightsSample);
                        if (stencil == null)
                        {
                            Heights[u, v] = heightsSample;
                        }
                        else
                        {
                            float val;
                            int   key;
                            MiscUtilities.DecompressStencil(stencil[u, v], out key, out val);
                            Heights[u, v] = Mathf.Lerp(Heights[u, v], heightsSample, val);
                        }
                    }
                    catch (IndexOutOfRangeException e)
                    {
                        Debug.LogError(string.Format("x {0} y {1}", hx, hz));
                        throw e;
                    }
                }
            }

#if UNITY_EDITOR
            UnityEditor.EditorUtility.SetDirty(this);
#endif
        }
Exemplo n.º 21
0
        /// <summary>
        /// Event delegate method fired when the <see cref="RenameMappingButton"/> button is clicked.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void RenameMappingButton_Click(object sender, EventArgs e)
        {
            if (_selectedMapping == null)
            {
                return;
            }

            string newName;

            using (var newColumnMappingDialog = new AppendNewColumnMappingDialog(Mappings, _selectedMapping.TableName))
            {
                var dr = newColumnMappingDialog.ShowDialog();
                if (dr == DialogResult.Cancel)
                {
                    return;
                }

                newName = newColumnMappingDialog.ColumnMappingName;
                if (string.IsNullOrEmpty(newName))
                {
                    // Should not get to this part of the code, if this is reached it means there is an issue in the logic above generating a mapping name.
                    MiscUtilities.ShowCustomizedErrorDialog("Error", Resources.AppendColumnMappingEmptyError);
                    return;
                }

                if (string.Equals(_selectedMapping.Name, newName, StringComparison.OrdinalIgnoreCase))
                {
                    // User input exactly the same name, so no renaming was actually done.
                    return;
                }

                MappingsChanged = true;
            }

            _selectedMapping.Name = newName;
            RefreshMappingList();
            var item = MappingsListView.FindItemWithText($"{newName} ({_selectedMapping.SchemaName}.{_selectedMapping.TableName})");

            if (item != null)
            {
                MappingsListView.Items[item.Index].Selected = true;
            }

            MappingsListView.Focus();
        }
Exemplo n.º 22
0
        /// <summary>
        /// Refreshes the dialog controls' values.
        /// </summary>
        /// <param name="useDefaultValues">Controls are set to their default values if <c>true</c>. Current stored values in application settings are used otherwise.</param>
        private void RefreshControlValues(bool useDefaultValues = false)
        {
            var settings = Settings.Default;

            QueryTimeoutNumericUpDown.Maximum = ConnectionTimeoutNumericUpDown.Maximum;
            GeometryAsTextFormatType spatialFormat;

            if (useDefaultValues)
            {
                ConnectionTimeoutNumericUpDown.Value     = Math.Min(ConnectionTimeoutNumericUpDown.Maximum, MiscUtilities.GetPropertyDefaultValueByName <uint>(settings, "GlobalConnectionConnectionTimeout"));
                QueryTimeoutNumericUpDown.Value          = MiscUtilities.GetPropertyDefaultValueByName <uint>(settings, "GlobalConnectionCommandTimeout");
                UseOptimisticUpdatesCheckBox.Checked     = MiscUtilities.GetPropertyDefaultValueByName <bool>(settings, "EditUseOptimisticUpdate");
                PreviewSqlQueriesRadioButton.Checked     = MiscUtilities.GetPropertyDefaultValueByName <bool>(settings, "GlobalSqlQueriesPreviewQueries");
                ShowExecutedSqlQueryRadioButton.Checked  = MiscUtilities.GetPropertyDefaultValueByName <bool>(settings, "GlobalSqlQueriesShowQueriesWithResults");
                RestoreSavedEditSessionsCheckBox.Checked = MiscUtilities.GetPropertyDefaultValueByName <bool>(settings, "EditSessionsRestoreWhenOpeningWorkbook");
                ReuseWorksheetsRadioButton.Checked       = MiscUtilities.GetPropertyDefaultValueByName <bool>(settings, "EditSessionsReuseWorksheets");
                PreviewTableDataCheckBox.Checked         = MiscUtilities.GetPropertyDefaultValueByName <bool>(settings, "EditPreviewMySqlData");
                OpeningWorkbookRadioButton.Checked       = MiscUtilities.GetPropertyDefaultValueByName <bool>(settings, "GlobalImportDataRestoreWhenOpeningWorkbook");
                SpatialTextFormatComboBox.SelectedValue  = Enum.TryParse(MiscUtilities.GetPropertyDefaultValueByName <string>(settings, "GlobalSpatialDataAsTextFormat"), out spatialFormat)
            ? spatialFormat
            : GeometryAsTextFormatType.None;
                ToleranceForFloatAndDoubleTextBox.Text = MiscUtilities.GetPropertyDefaultValueByName <decimal>(settings, "GlobalEditToleranceForFloatAndDouble").ToString(CultureInfo.CurrentCulture);
            }
            else
            {
                ConnectionTimeoutNumericUpDown.Value     = Math.Min(ConnectionTimeoutNumericUpDown.Maximum, settings.GlobalConnectionConnectionTimeout);
                QueryTimeoutNumericUpDown.Value          = settings.GlobalConnectionCommandTimeout;
                UseOptimisticUpdatesCheckBox.Checked     = settings.EditUseOptimisticUpdate;
                PreviewSqlQueriesRadioButton.Checked     = settings.GlobalSqlQueriesPreviewQueries;
                ShowExecutedSqlQueryRadioButton.Checked  = settings.GlobalSqlQueriesShowQueriesWithResults;
                RestoreSavedEditSessionsCheckBox.Checked = settings.EditSessionsRestoreWhenOpeningWorkbook;
                ReuseWorksheetsRadioButton.Checked       = settings.EditSessionsReuseWorksheets;
                PreviewTableDataCheckBox.Checked         = settings.EditPreviewMySqlData;
                OpeningWorkbookRadioButton.Checked       = settings.GlobalImportDataRestoreWhenOpeningWorkbook;
                SpatialTextFormatComboBox.SelectedValue  = Enum.TryParse(settings.GlobalSpatialDataAsTextFormat, out spatialFormat)
            ? spatialFormat
            : GeometryAsTextFormatType.None;
                ToleranceForFloatAndDoubleTextBox.Text = settings.GlobalEditToleranceForFloatAndDouble.ToString(CultureInfo.CurrentCulture);
            }

            NoSqlStatementsRadioButton.Checked     = !PreviewSqlQueriesRadioButton.Checked && !ShowExecutedSqlQueryRadioButton.Checked;
            CreateNewWorksheetsRadioButton.Checked = !ReuseWorksheetsRadioButton.Checked;
            ShowingSidebarRadioButton.Checked      = !OpeningWorkbookRadioButton.Checked;
            _manageConnectionInfosDialog?.RefreshControlValues(useDefaultValues);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Event delegate method fired when the <see cref="TablesViewsContextMenuStrip"/> context menu is being opened.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void TablesViewsContextMenuStrip_Opening(object sender, CancelEventArgs e)
        {
            ListView listView;
            var      dbView = MiscUtilities.GetSelectedDbTableOrView(sender, out listView);

            if (listView == null)
            {
                return;
            }

            bool showRelatedTablesItems = listView != TablesViewsListView;
            bool dbViewIsSelected       = dbView != null;

            AddRelatedTablesToolStripMenuItem.Visible = dbViewIsSelected && showRelatedTablesItems;
            PreviewDataToolStripMenuItem.Visible      = dbViewIsSelected;
            SelectAllToolStripMenuItem.Visible        = showRelatedTablesItems;
            SelectNoneToolStripMenuItem.Visible       = showRelatedTablesItems;
        }
Exemplo n.º 24
0
 public void UpdateRevision(bool refreshExportName)
 {
     sheetRevision = sheet.get_Parameter(
         BuiltInParameter.SHEET_CURRENT_REVISION).AsString();
     sheetRevisionDescription = sheet.get_Parameter(
         BuiltInParameter.SHEET_CURRENT_REVISION_DESCRIPTION).AsString();
     sheetRevisionDate = sheet.get_Parameter(
         BuiltInParameter.SHEET_CURRENT_REVISION_DATE).AsString();
     sheetRevisionDateTime = MiscUtilities.ToDateTime(sheetRevisionDate);
     if (refreshExportName)
     {
         SetExportName();
     }
     NotifyPropertyChanged(nameof(SheetRevision));
     NotifyPropertyChanged(nameof(SheetRevisionDescription));
     NotifyPropertyChanged(nameof(SheetRevisionDate));
     NotifyPropertyChanged(nameof(FullExportName));
 }
        /// <summary>
        /// Event delegate method fired when the <see cref="ImportAdvancedOptionsDialog"/> is being closed.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void ExportAdvancedOptionsDialog_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult == DialogResult.Cancel)
            {
                return;
            }

            Settings.Default.ExportLimitPreviewRowsQuantity      = (int)PreviewRowsQuantityNumericUpDown.Value;
            Settings.Default.ExportDetectDatatype                = DetectDatatypeCheckBox.Checked;
            Settings.Default.ExportAddBufferToVarchar            = AddBufferToVarCharCheckBox.Checked;
            Settings.Default.ExportAutoIndexIntColumns           = AutoIndexIntColumnsCheckBox.Checked;
            Settings.Default.ExportAutoAllowEmptyNonIndexColumns = AutoAllowEmptyNonIndexColumnsCheckBox.Checked;
            Settings.Default.ExportShowAllMySqlDataTypes         = ShowAllDataTypesCheckBox.Checked;
            Settings.Default.ExportUseFormattedValues            = UseFormattedValuesCheckBox.Checked;
            Settings.Default.ExportSqlQueriesCreateIndexesLast   = CreateTableIndexesLastCheckBox.Checked;
            Settings.Default.ExportGenerateMultipleInserts       = GenerateMultipleInsertsCheckBox.Checked;
            MiscUtilities.SaveSettings();
        }
        protected override void ExecuteCommandsLogic(CmdsExecutionData data)
        {
            if (!data.ContainerFile.ContainsContentFileWithPath(data.ContentPath))
            {
                TgvImage image = DDSFileToTgv(data.ModificationSourcePath, !Command.UseMipMaps);
                //Trzeba mieć na to oko, czy nie powoduje problemów, bo przy replace była używana checksuma starego obrazka.
                image.SourceChecksum = !String.IsNullOrEmpty(Command.Checksum)
                    ? MiscUtilities.HexByteStringToByteArray(Command.Checksum)
                    : image.ComputeContentChecksum();
                image.IsCompressed = Command.UseCompression;

                var newContentFile = new EdataContentFile();
                newContentFile.Path = data.ContentPath;
                newContentFile.LoadCustomContent(TgvToBytes(image, !Command.UseMipMaps));

                data.ContainerFile.AddContentFile(newContentFile);
            }
            else if (Command.OverwriteIfExist)
            {
                var contentFile = data.ContainerFile.GetContentFileByPath(data.ContentPath);

                //To nie będzie potrzebne tutaj jeśli nie bedzie trzeba ładować i wykorzystywać starego obrazka.
                if (contentFile.FileType != ContentFileType.Image)
                {
                    throw new CmdExecutionFailedException(
                              String.Format("Invalid targetContentPath: \"{0}\". It doesn't target an image content file.", data.ContentPath),
                              DefaultExecutionErrorMsg);
                }

                //Ładowanie starego obrazka nie będzie potrzebne jeśli bedzie pewnośc ze recznie wygenerowana checkusma jest ok.
                //Ok, tu kiedyś było odczytywanie starych danych z starego obrazka, teraz checksuma jest generowana na nowo,
                //żeby uniknac konieczności ładowania tych starych danych, bo nie sa potrzeben przy dodawaniu, a tutaj były by potrzebne
                //i trudno to rozwiązać przy założeniu ze dane są ładowane na zewnątrz.

                //TgvImage oldTgv = BytesToTgv(contentFile.Content);
                TgvImage image = DDSFileToTgv(data.ModificationSourcePath, !Command.UseMipMaps);
                image.SourceChecksum = !String.IsNullOrEmpty(Command.Checksum)
                    ? MiscUtilities.HexByteStringToByteArray(Command.Checksum)
                    : image.ComputeContentChecksum();
                image.IsCompressed = Command.UseCompression;

                contentFile.LoadCustomContent(TgvToBytes(image, !Command.UseMipMaps));
            }
        }
Exemplo n.º 27
0
        private void RenameEntries(Dictionary <byte[], TradDictEntry> dictionary)
        {
            foreach (var entryToRename in Command.RenamedEntries)
            {
                var hash = MiscUtilities.HexByteStringToByteArray(entryToRename.Key);

                TradDictEntry entry;
                if (dictionary.TryGetValue(hash, out entry))
                {
                    entry.Content = entryToRename.Value;
                }
                else
                {
                    var warning = String.Format("RenameEntry operation failed because " +
                                                "entry with the given hash \"{0}\" wasn't found.", entryToRename.Key);
                    Common.Logging.LoggerFactory.Create(this.GetType()).Warn(warning);
                }
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Sets the appearance of <see cref="MySqlListViewNode"/> objects appearing in the <see cref="SchemasList"/>.
        /// </summary>
        /// <param name="refreshSchemasList">Flag indicating whether the <see cref="SchemasList"/> must be refreshed after resetting the appearance.</param>
        private void SetItemsAppearance(bool refreshSchemasList)
        {
            var displayCollations = DisplaySchemaCollationsToolStripMenuItem.Checked;

            if (Settings.Default.SchemasDisplayCollations != displayCollations)
            {
                Settings.Default.SchemasDisplayCollations = displayCollations;
                MiscUtilities.SaveSettings();
            }

            SchemasList.ClearHeaderNodes();
            SchemasList.SetItemsAppearance(displayCollations, false);
            SchemasList.AddHeaderNode("Schemas");
            SchemasList.AddHeaderNode("System Schemas");
            if (refreshSchemasList)
            {
                RefreshSchemasToolStripMenuItem_Click(null, EventArgs.Empty);
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Sets the value of the global optimistic update for all sessions property and updates the context menu options accordingly.
        /// </summary>
        /// <param name="value">The new value of the property.</param>
        /// <param name="saveInSettings">Flag indicating whether the new value must be saved in the settings file.</param>
        private void SetUseOptimisticUpdateForAllSessions(bool value, bool saveInSettings)
        {
            _updatingUSeOptimisticUpdateSetting = true;
            if (saveInSettings)
            {
                Settings.Default.EditUseOptimisticUpdate = value;
                MiscUtilities.SaveSettings();
            }

            ForAllSessionsToolStripMenuItem.Checked = value;
            if (value)
            {
                _useOptimisticUpdateForThisSession           = true;
                ForThisSessionToolStripMenuItem.Checked      = true;
                UseOptimisticUpdateToolStripMenuItem.Checked = true;
            }

            _updatingUSeOptimisticUpdateSetting = false;
        }
Exemplo n.º 30
0
        long LeadingZerosSpeedLoop(long loopCount)
        {
            long sum = 0;

            for (long i = 0; i < loopCount; i++)
            {
                // long val = testValueLevel + (i & 0x8000);
                long val = testValueLevel;
                sum += MiscUtilities.numberOfLeadingZeros(val);
                sum += MiscUtilities.numberOfLeadingZeros(val);
                sum += MiscUtilities.numberOfLeadingZeros(val);
                sum += MiscUtilities.numberOfLeadingZeros(val);
                sum += MiscUtilities.numberOfLeadingZeros(val);
                sum += MiscUtilities.numberOfLeadingZeros(val);
                sum += MiscUtilities.numberOfLeadingZeros(val);
                sum += MiscUtilities.numberOfLeadingZeros(val);
            }
            return(sum);
        }