Example #1
0
        /// <summary>
        /// Gets an <see cref="EngineSeries"/> with the specified key from the cache. If the
        /// <see cref="EngineSeries"/> is not found in the cache, then it is fetched from the
        /// database and stored in the cache.
        /// </summary>
        private static EngineSeries GetEngineSeries(int seriesId, AppDatabase db, Dictionary <int, EngineSeries> cache)
        {
            EngineSeries series = null;

            if (!cache.TryGetValue(seriesId, out series))
            {
                series = db.Query <EngineSeries>("SELECT * FROM `EngineSeries` WHERE `Id`=@P0", seriesId).FirstOrDefault();
                cache.Add(seriesId, series);
            }

            return(series);
        }
Example #2
0
        /// <summary>
        /// Gets an <see cref="Engine"/> with the specified key from the cache. If the
        /// <see cref="Engine"/> is not found in the cache, then it is fetched from the
        /// database and stored in the cache.
        /// </summary>
        private static Engine GetEngine(int engineId, AppDatabase db, Dictionary <int, Engine> cache)
        {
            Engine engine = null;

            if (!cache.TryGetValue(engineId, out engine))
            {
                engine = db.Query <Engine>("SELECT * FROM `Engine` WHERE `Id`=@P0", engineId).FirstOrDefault();
                cache.Add(engineId, engine);
            }

            return(engine);
        }
Example #3
0
        private bool ImportSoundPack(AppDatabase db)
        {
            // Define folder path
            string folderName = folderNameBox.Text.MakeFileNameSafe();
            string folderPath = Path.Combine(Program.RootPath, "sounds", Package.PackageTypeFolderName, folderName);

            // Delete old data
            if (!NewPackage)
            {
                // Delete the old sounds
                switch (Package.SoundType)
                {
                case SoundType.Engine:
                    var ep = (EngineSoundPackage)Package;
                    foreach (var sound in ep.EngineSounds)
                    {
                        db.EngineSounds.Remove(sound);
                    }
                    break;

                case SoundType.Truck:
                    var tp = (TruckSoundPackage)Package;
                    foreach (var sound in tp.TruckSounds)
                    {
                        db.TruckSounds.Remove(sound);
                    }
                    break;

                default:
                    throw new Exception("Invalid sound type");
                }
            }

            // Delete existing data if it is there.
            if (Directory.Exists(folderPath))
            {
                string       query = String.Empty;
                SoundPackage existing;

                // Fetch existing sound from database
                switch (Package.SoundType)
                {
                // Add or update the existing package
                case SoundType.Engine:
                    query    = "SELECT * FROM `EngineSoundPackage` WHERE `FolderName` = @P0";
                    existing = db.Query <EngineSoundPackage>(query, folderNameBox.Text).FirstOrDefault();
                    break;

                case SoundType.Truck:
                    query    = "SELECT * FROM `TruckSoundPackage` WHERE `FolderName` = @P0";
                    existing = db.Query <TruckSoundPackage>(query, folderNameBox.Text).FirstOrDefault();
                    break;

                default:
                    throw new Exception("Invalid sound type");
                }

                // If the folder name is already in use, and (is new package OR the existing package ID does not match the current)
                if (existing != null && (NewPackage || Package.Id != existing.Id))
                {
                    var result = MessageBox.Show(
                        $"The sound folder chosen belongs to the sound package \"{existing?.Name}\"! "
                        + "Do you want to replace the existing sound package with this one?",
                        "Verification", MessageBoxButtons.YesNo, MessageBoxIcon.Warning
                        );

                    // Quit if the user see's the error in his ways
                    if (result != DialogResult.Yes)
                    {
                        return(false);
                    }

                    // Delete the old sound
                    switch (Package.SoundType)
                    {
                    // Add or update the existing package
                    case SoundType.Engine:
                        db.EngineSoundPackages.Remove((EngineSoundPackage)existing);
                        break;

                    case SoundType.Truck:
                        db.TruckSoundPackages.Remove((TruckSoundPackage)existing);
                        break;

                    default:
                        throw new Exception("Invalid sound type");
                    }
                }
            }

            // Wrap in a transaction
            using (var trans = db.BeginTransaction())
            {
                try
                {
                    // Add or update the existing package
                    switch (Package.SoundType)
                    {
                    // Add or update the existing package
                    case SoundType.Engine:
                        db.EngineSoundPackages.AddOrUpdate((EngineSoundPackage)Package);
                        break;

                    case SoundType.Truck:
                        db.TruckSoundPackages.AddOrUpdate((TruckSoundPackage)Package);
                        break;

                    default:
                        throw new Exception("Invalid sound type");
                    }

                    // Re-open the Sound package ZipFile
                    using (var reader = new SoundPackageReader(PackageFilePath, Package.SoundType))
                    {
                        // Save sounds in the database
                        reader.InstallPackage(db, Package, folderPath, true);
                    }

                    // Commit and return
                    trans.Commit();
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
            }

            return(true);
        }
Example #4
0
        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            // Check UnitName
            // Check for a valid identifier string
            if (!SiiFileBuilder.IsValidUnitName(unitNameBox.Text))
            {
                // Tell the user this isnt allowed
                MessageBox.Show(
                    "Invalid Engine Sii Unit Name. Tokens must be 1 to 12 characters in length, seperated by a dot, "
                    + "and contain alpha-numeric or underscores only",
                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning
                    );

                return;
            }

            // Check engine name
            if (engineNameBox.Text.Length < 2 || engineNameBox.Text.Contains('"'))
            {
                // Tell the user this isnt allowed
                MessageBox.Show(
                    "Invalid Engine Name string. The name must be at least 2 characters long and contain no quotes",
                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning
                    );

                return;
            }

            // Set new attribute values
            Engine.SeriesId                 = ((EngineSeries)engineModelBox.SelectedItem).Id;
            Engine.UnitName                 = unitNameBox.Text.Trim();
            Engine.Name                     = engineNameBox.Text.Trim();
            Engine.Price                    = (int)priceBox.Value;
            Engine.Unlock                   = (int)unlockBox.Value;
            Engine.Horsepower               = (int)horsepowerBox.Value;
            Engine.PeakRpm                  = (int)peakRPMBox.Value;
            Engine.IdleRpm                  = (int)idleRpmBox.Value;
            Engine.RpmLimit                 = (int)rpmLimitBox.Value;
            Engine.RpmLimitNeutral          = (int)neutralRpmBox.Value;
            Engine.BrakeStrength            = brakeStrengthBox.Value;
            Engine.BrakePositions           = (int)brakePositionsBox.Value;
            Engine.BrakeDownshift           = automaticDSCheckBox.Checked;
            Engine.MinRpmRange_LowGear      = (int)rpmRangeBox1.Value;
            Engine.MaxRpmRange_LowGear      = (int)rpmRangeBox2.Value;
            Engine.MinRpmRange_HighGear     = (int)rpmRangeBox3.Value;
            Engine.MaxRpmRange_HighGear     = (int)rpmRangeBox4.Value;
            Engine.LowRpmRange_PowerBoost   = (int)rpmRangeBox5.Value;
            Engine.HighRpmRange_PowerBoost  = (int)rpmRangeBox6.Value;
            Engine.ResistanceTorque         = (int)resistanceBox.Value;
            Engine.FuelConsumption          = Math.Round(consumptionBox.Value / 100, 2);
            Engine.NoAdbluePowerLimit       = adBlueNoPowerLimit.Value;
            Engine.AdblueConsumption        = adBlueConsumption.Value;
            Engine.LowRpmRange_EngineBrake  = (int)engineBrakeLow.Value;
            Engine.HighRpmRange_EngineBrake = (int)engineBrakeHigh.Value;
            Engine.Defaults                 = fileDefaultsTextBox.Lines;
            Engine.Overrides                = fileOverridesTextBox.Lines;
            Engine.Comment                  = fileCommentTextBox.Lines;
            Engine.Conflicts                = conflictsTextBox.Lines;

            // Torque metrics
            if (Program.Config.UnitSystem == UnitSystem.Imperial)
            {
                Engine.Torque = (int)torqueBox.Value;
            }
            else
            {
                Engine.NewtonMetres = (int)torqueBox.Value;
            }

            // Figure out the filename
            if (!String.IsNullOrWhiteSpace(filenameTextBox.Text))
            {
                Engine.FileName = filenameTextBox.Text.Trim();
            }

            // Validate and Save
            using (AppDatabase db = new AppDatabase())
                using (SQLiteTransaction trans = db.BeginTransaction())
                {
                    // Verify that the series.Id and engine.UnitName are unique
                    string query  = "SELECT * FROM `Engine` WHERE `SeriesId`=@P0 AND `UnitName`=@P1";
                    var    engine = db.Query <Engine>(query, Engine.SeriesId, Engine.UnitName).FirstOrDefault();
                    if (engine != null && (NewEngine || engine.Id != Engine.Id))
                    {
                        // Tell the user this isnt allowed
                        MessageBox.Show(
                            $"The selected Engine Series already contains an engine with the Sii Unit Name of \""
                            + Engine.UnitName + "\"! Please select a different Engine Series or change the Sii "
                            + "Unit Name to something unique.",
                            "Unique Constraint Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning
                            );
                        return;
                    }

                    // Wrap database changes in a try-catch block so we can Rollback on error
                    try
                    {
                        // Update or Add engine
                        db.Engines.AddOrUpdate(Engine);

                        // If pre-existing engine, delete all changed data
                        if (!NewEngine)
                        {
                            // Delete any and all TorueRatios from thed database
                            if (RatiosChanged)
                            {
                                foreach (TorqueRatio ratio in Engine.TorqueRatios)
                                {
                                    db.TorqueRatios.Remove(ratio);
                                }
                            }

                            // Set Conflicts
                            if (ConflictsChanged)
                            {
                                // Remove old
                                foreach (var conflict in Engine.TransmissionConflicts)
                                {
                                    db.AccessoryConflicts.Remove(conflict);
                                }
                            }

                            // Set Suitables
                            if (SuitablesChanged)
                            {
                                foreach (var item in Engine.SuitableTransmissions)
                                {
                                    db.SuitableAccessories.Remove(item);
                                }
                            }

                            // Set compatible trucks
                            if (TrucksChanged)
                            {
                                foreach (var item in Engine.ItemOf)
                                {
                                    db.TruckEngines.Remove(item);
                                }
                            }
                        }

                        // Add conflicts
                        if ((NewEngine || ConflictsChanged) && conflictListView.CheckedItems.Count > 0)
                        {
                            var ids = conflictListView.CheckedItems.Cast <ListViewItem>().Select(x => (int)x.Tag);
                            foreach (var item in ids)
                            {
                                db.AccessoryConflicts.Add(new AccessoryConflict()
                                {
                                    EngineId       = Engine.Id,
                                    TransmissionId = item
                                });
                            }
                        }

                        // Add suitible fors
                        if ((NewEngine || SuitablesChanged) && suitsListView.CheckedItems.Count > 0)
                        {
                            var ids = suitsListView.CheckedItems.Cast <ListViewItem>().Select(x => (int)x.Tag);
                            foreach (var item in ids)
                            {
                                db.SuitableAccessories.Add(new SuitableAccessory()
                                {
                                    EngineId       = Engine.Id,
                                    TransmissionId = item
                                });
                            }
                        }

                        // Add new truck engines
                        if ((NewEngine || TrucksChanged) && truckListView.CheckedItems.Count > 0)
                        {
                            var ids = truckListView.CheckedItems.Cast <ListViewItem>().Select(x => (int)x.Tag);
                            foreach (var item in ids)
                            {
                                db.TruckEngines.Add(new TruckEngine()
                                {
                                    EngineId = Engine.Id,
                                    TruckId  = item
                                });
                            }
                        }

                        // Add the new torque ratios
                        if (NewEngine || RatiosChanged)
                        {
                            foreach (TorqueRatio ratio in Ratios.OrderBy(x => x.RpmLevel))
                            {
                                ratio.EngineId = Engine.Id;
                                db.TorqueRatios.AddOrUpdate(ratio);
                            }
                        }

                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();

                        // Tell the user about the failed validation error
                        MessageBox.Show(ex.Message, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

            this.DialogResult = DialogResult.OK;
        }
Example #5
0
        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            // Check UnitName
            // Check for a valid identifier string
            if (!SiiFileBuilder.IsValidUnitName(unitNameBox.Text))
            {
                // Tell the user this isnt allowed
                MessageBox.Show(
                    "Invalid Transmission Sii Unit Name. Tokens must be 1 to 12 characters in length, seperated by a dot, "
                    + "and contain alpha-numeric or underscores only",
                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning
                    );

                return;
            }

            // Check engine name
            if (transNameBox.Text.Length < 2 || transNameBox.Text.Contains('"'))
            {
                // Tell the user this isnt allowed
                MessageBox.Show(
                    "Invalid Transmission Name string! The name must be at least 2 characters long and contain no quotes",
                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning
                    );

                return;
            }

            // Set new attribute values
            Transmission.SeriesId          = ((TransmissionSeries)seriesModelBox.SelectedItem).Id;
            Transmission.UnitName          = unitNameBox.Text.Trim();
            Transmission.Name              = transNameBox.Text.Trim();
            Transmission.Price             = (int)priceBox.Value;
            Transmission.Unlock            = (int)unlockBox.Value;
            Transmission.DifferentialRatio = diffRatio.Value;
            Transmission.Defaults          = fileDefaultsTextBox.Lines;
            Transmission.Comment           = fileCommentTextBox.Lines;
            Transmission.Conflicts         = conflictsTextBox.Lines;
            Transmission.SuitableFor       = suitablesTextBox.Lines;
            Transmission.Retarder          = (hasRetarder.Checked) ? (int)retardPositions.Value : 0;
            Transmission.StallTorqueRatio  = (hasTorqueConverter.Checked) ? stallRatio.Value : 0.0m;

            // Figure out the filename
            if (!String.IsNullOrWhiteSpace(filenameTextBox.Text))
            {
                Transmission.FileName = filenameTextBox.Text.Trim();
            }

            // Validate and Save
            using (AppDatabase db = new AppDatabase())
                using (SQLiteTransaction trans = db.BeginTransaction())
                {
                    // Verify that the series.Id and engine.UnitName are unique
                    string query  = "SELECT * FROM `Transmission` WHERE `SeriesId`=@P0 AND `UnitName`=@P1";
                    var    eTrans = db.Query <Transmission>(query, Transmission.SeriesId, Transmission.UnitName).FirstOrDefault();
                    if (eTrans != null && (NewTransmission || eTrans.Id != Transmission.Id))
                    {
                        // Tell the user this isnt allowed
                        MessageBox.Show(
                            $"The selected Transmission Series already contains a transmission with the Sii Unit Name of \""
                            + Transmission.UnitName + "\"! Please select a different Transmission Series or change the Sii "
                            + "Unit Name to something unique.",
                            "Unique Constraint Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning
                            );
                        return;
                    }

                    // Wrap database changes in a try-catch block so we can Rollback on error
                    try
                    {
                        // Update the current engine
                        db.Transmissions.AddOrUpdate(Transmission);

                        // If pre-existing transmission, delete all changed data
                        if (!NewTransmission)
                        {
                            // Delete any and all TorueRatios from the database
                            if (GearsChanged)
                            {
                                foreach (var gear in Transmission.Gears)
                                {
                                    db.TransmissionGears.Remove(gear);
                                }
                            }

                            // Set Conflicts
                            if (ConflictsChanged)
                            {
                                foreach (var conflict in Transmission.EngineConflicts)
                                {
                                    db.AccessoryConflicts.Remove(conflict);
                                }
                            }

                            // Set Suitables
                            if (SuitablesChanged)
                            {
                                foreach (var item in Transmission.SuitableEngines)
                                {
                                    db.SuitableAccessories.Remove(item);
                                }
                            }

                            // Set Conflicts
                            if (TrucksChanged)
                            {
                                foreach (var item in Transmission.ItemOf)
                                {
                                    db.TruckTransmissions.Remove(item);
                                }
                            }
                        }

                        // Add conflicts if any
                        if ((NewTransmission || ConflictsChanged) && conflictListView.CheckedItems.Count > 0)
                        {
                            var ids = conflictListView.CheckedItems.Cast <ListViewItem>().Select(x => (int)x.Tag);
                            foreach (var item in ids)
                            {
                                db.AccessoryConflicts.Add(new AccessoryConflict()
                                {
                                    EngineId       = item,
                                    TransmissionId = Transmission.Id
                                });
                            }
                        }

                        // Add suitible fors if any
                        if ((NewTransmission || SuitablesChanged) && suitsListView.CheckedItems.Count > 0)
                        {
                            var ids = suitsListView.CheckedItems.Cast <ListViewItem>().Select(x => (int)x.Tag);
                            foreach (var item in ids)
                            {
                                db.SuitableAccessories.Add(new SuitableAccessory()
                                {
                                    EngineId       = item,
                                    TransmissionId = Transmission.Id
                                });
                            }
                        }

                        // Add trucks if any
                        if ((NewTransmission || TrucksChanged) && truckListView.CheckedItems.Count > 0)
                        {
                            var ids = truckListView.CheckedItems.Cast <ListViewItem>().Select(x => (int)x.Tag);
                            foreach (var item in ids)
                            {
                                db.TruckTransmissions.Add(new TruckTransmission()
                                {
                                    TruckId        = item,
                                    TransmissionId = Transmission.Id
                                });
                            }
                        }

                        // Add the new torque ratios
                        if (NewTransmission || GearsChanged)
                        {
                            int i = 0;
                            foreach (var gear in ReverseGears.OrderBy(x => x.Ratio))
                            {
                                gear.TransmissionId = Transmission.Id;
                                gear.GearIndex      = i++;
                                db.TransmissionGears.Add(gear);
                            }
                            foreach (var gear in ForwardGears.OrderByDescending(x => x.Ratio))
                            {
                                gear.TransmissionId = Transmission.Id;
                                gear.GearIndex      = i++;
                                db.TransmissionGears.Add(gear);
                            }
                        }

                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();

                        // Tell the user about the failed validation error
                        MessageBox.Show(ex.Message, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

            this.DialogResult = DialogResult.OK;
        }