Beispiel #1
0
        private (string, string, string) SetUpTestFile(string fileName, [CallerMemberName] string caller = null)
        {
            var filePath = Path.Combine(TestFilesDirectory, fileName);

            var baseFileName = Path.GetFileName(fileName);
            var orgFile      = Path.Combine(TestTempPath, fileName);
            var crz3File     = (string)null;

            // create copy of base file
            if (File.Exists(orgFile) == false)
            {
                File.Copy(filePath, orgFile);
            }
            crz3File = new Migrator().MigrateFromV2ToV3(orgFile, true);


            var v2againPath = Path.Combine(TestTempPath, caller + "_again_" + fileName);

            using (var v2again = new DAL(v2againPath, true))
                using (var v3db = new CruiseDatastore_V3(crz3File))
                {
                    var cruiseID     = v3db.ExecuteScalar <string>("SELECT CruiseID FROM Cruise;");
                    var downMigrator = new DownMigrator();
                    downMigrator.MigrateFromV3ToV2(cruiseID, v3db, v2again);
                }

            return(orgFile, crz3File, v2againPath);
        }
Beispiel #2
0
        public void EnsureCanMigrate_CheckAllSubPopsHaveTDV_HasTDVs()
        {
            var v3Path = GetTempFilePathWithExt(".crz3");

            var init = new DatabaseInitializer
            {
                TreeDefaults = new[]
                {
                    new TreeDefaultValue {
                        SpeciesCode = "sp1", PrimaryProduct = "01"
                    },
                    new TreeDefaultValue {
                        SpeciesCode = "sp2", PrimaryProduct = "01"
                    },
                    new TreeDefaultValue {
                        SpeciesCode = "sp3", PrimaryProduct = "01"
                    },
                }
            };

            using var v3db = init.CreateDatabase();

            var result = DownMigrator.CheckAllSubPopsHavTDV(init.CruiseID, v3db);

            result.Should().BeEmpty();
        }
Beispiel #3
0
        public void ExpandContractSpecies_SpecificProd()
        {
            var fromPath = GetTempFilePath("ExpandContractSpecies_SpecificProd.crz3");
            var toPath   = GetTempFilePath("ExpandContractSpecies_SpecificProd.cruise");

            var specifProd = "01";

            var init = new DatabaseInitializer()
            {
                Species      = new[] { "sp1", },
                TreeDefaults = new[]
                {
                    new TreeDefaultValue {
                        SpeciesCode = "sp1", PrimaryProduct = specifProd, Recoverable = 1.1,
                    },
                    new TreeDefaultValue {
                        SpeciesCode = null, PrimaryProduct = specifProd, Recoverable = 1.2,
                    },
                    new TreeDefaultValue {
                        SpeciesCode = "sp1", PrimaryProduct = null, Recoverable = 1.3,
                    },
                    new TreeDefaultValue {
                        SpeciesCode = null, PrimaryProduct = null, Recoverable = 1.4,
                    },
                },
                Subpops = new SubPopulation[] { },
            };

            using var fromDb = init.CreateDatabaseFile(fromPath);
            using var toDb   = new DAL(toPath, true);

            var spProd = new Species_Product
            {
                CruiseID        = init.CruiseID,
                SpeciesCode     = "sp1",
                ContractSpecies = "something",
                PrimaryProduct  = specifProd,
            };

            fromDb.Insert(spProd);


            var downMigrator = new DownMigrator(new[] { new TreeDefaultValueDownMigrate(), });

            downMigrator.MigrateFromV3ToV2(init.CruiseID, fromDb, toDb);

            var tdvs = toDb.From <V2.Models.TreeDefaultValue>().Query().ToArray();

            // all TDVs with our specified product code should have a contract species
            tdvs.Where(x => x.PrimaryProduct == specifProd).Should().OnlyContain(x => x.ContractSpecies != null);
            // no TDVs without our specified product code should have a contract species
            tdvs.Where(x => x.PrimaryProduct != specifProd).Should().OnlyContain(x => x.ContractSpecies == null);
        }
Beispiel #4
0
        public void EnsureCanMigrate_CheckAllSubPopsHaveTDV_DoesntHasTDVs()
        {
            var v3Path = GetTempFilePathWithExt(".crz3");

            var init = new DatabaseInitializer
            {
                TreeDefaults = new TreeDefaultValue[] { },
            };

            using var v3db = init.CreateDatabase();

            var result = DownMigrator.CheckAllSubPopsHavTDV(init.CruiseID, v3db);

            result.Should().NotBeNullOrEmpty();
        }
Beispiel #5
0
        public void MigrateFromV3ToV2()
        {
            var initializer = new DatabaseInitializer();
            var fromPath    = GetTempFilePath("MigrateFromV3ToV2.crz3");
            var toPath      = GetTempFilePath("MigrateFromV3ToV2.cruise");

            using var fromDb = initializer.CreateDatabaseFile(fromPath);
            using var toDb   = new DAL(toPath, true);

            var downMigrator = new DownMigrator();

            downMigrator.MigrateFromV3ToV2(initializer.CruiseID, fromDb, toDb);

            ValidateMigration(fromDb, toDb);
        }
        public void MigrateTreeErrors_measureTree()
        {
            var toPath   = GetTempFilePath("MigrateTreeErrors_measureTree.cruise");
            var fromPath = GetTempFilePath("MigrateTreeErrors_measureTree.crz3");


            var init     = new DatabaseInitializer();
            var cruiseID = init.CruiseID;

            using var db = init.CreateDatabaseFile(fromPath);

            var tree = new Tree
            {
                CruiseID        = cruiseID,
                TreeID          = Guid.NewGuid().ToString(),
                CuttingUnitCode = "u1",
                StratumCode     = "st1",
                SampleGroupCode = "sg1",
                TreeNumber      = 1,
                CountOrMeasure  = "M",
            };

            db.Insert(tree);

            var tm = new TreeMeasurment
            {
                TreeID = tree.TreeID,
            };

            db.Insert(tm);


            using var toDb = new DAL(toPath, true);


            var downMigrator = new DownMigrator();

            downMigrator.MigrateFromV3ToV2(cruiseID, db, toDb);

            var errorLogs = toDb.From <CruiseDAL.V2.Models.ErrorLog>().Query().ToArray();

            errorLogs.Should().HaveCount(4);
            errorLogs.Should().Contain(x => x.Message == "Species Code Is Missing");
            errorLogs.Should().Contain(x => x.Message == "Live/Dead Value Is Missing");
            errorLogs.Should().Contain(x => x.Message == "Aleast One Height Parameter Must Be Greater Than 0");
            errorLogs.Should().Contain(x => x.Message == "DBH or DRC must be greater than 0");
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            Console.WriteLine(string.Join(',', args));

            try
            {
                if (args.Length > 0)
                {
                    var convertArg = args[0];
                    if (File.Exists(convertArg) == false)
                    {
                        throw new FileNotFoundException("invalid file path", convertArg);
                    }

                    var filePath  = Path.GetFullPath(convertArg);
                    var directory = Path.GetDirectoryName(filePath);
                    var fileName  = Path.GetFileNameWithoutExtension(filePath);
                    var extention = Path.GetExtension(filePath).ToLower();

                    if (extention == ".cruise" || extention == ".cut")
                    {
                        var v3Path = Path.Combine(directory, fileName + ".crz3");
                        Console.WriteLine($"Converting {filePath} --> {v3Path}");

                        using (var v2Db = new DAL(filePath))
                            using (var v3Db = new CruiseDatastore_V3())
                            {
                                new Migrator().MigrateFromV2ToV3(v2Db, v3Db, deviceID: "CruiseCLI");
                                v3Db.BackupDatabase(v3Path);
                            }
                    }
                    else if (extention == ".crz3")
                    {
                        var v2Path = Path.Combine(directory, fileName + ".cruise");
                        Console.WriteLine($"Converting {filePath} --> {v2Path}");

                        using (var v2Db = new DAL())
                            using (var v3Db = new CruiseDatastore_V3(filePath))
                            {
                                var cruiseIDs = v3Db.QueryScalar <string>("SELECT CruiseID FROM Cruise;").ToArray();

                                if (cruiseIDs.Length > 1)
                                {
                                    throw new InvalidOperationException("More than one cruise found");
                                }
                                var cruiseID = cruiseIDs.Single();

                                var downMigrator = new DownMigrator();

                                downMigrator.MigrateFromV3ToV2(cruiseID, v3Db, v2Db, createdBy: "CruiseCLI");
                                v2Db.BackupDatabase(v2Path);
                            }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Console.ReadLine();
            }
        }
Beispiel #8
0
        public void MigrateFromV3ToV2_With_FieldDefaults()
        {
            var initializer = new DatabaseInitializer();
            var fromPath    = GetTempFilePath("MigrateFromV3ToV2.crz3");
            var toPath      = GetTempFilePath("MigrateFromV3ToV2.cruise");

            using var fromDb = initializer.CreateDatabaseFile(fromPath);

            var sg = initializer.SampleGroups.First();

            fromDb.Insert(new TreeFieldSetup()
            {
                CruiseID         = initializer.CruiseID,
                SampleGroupCode  = sg.SampleGroupCode,
                StratumCode      = sg.StratumCode,
                Field            = "DBH",
                DefaultValueReal = 12.0,
            });

            fromDb.Insert(new TreeFieldSetup()
            {
                CruiseID         = initializer.CruiseID,
                StratumCode      = sg.StratumCode,
                Field            = "DBH",
                DefaultValueReal = 11.0,
            });

            fromDb.Insert(new TreeFieldSetup()
            {
                CruiseID         = initializer.CruiseID,
                StratumCode      = sg.StratumCode,
                Field            = "DRC",
                DefaultValueReal = 13.0,
            });

            var tree = new Tree()
            {
                CruiseID        = initializer.CruiseID,
                TreeID          = Guid.NewGuid().ToString(),
                TreeNumber      = 101,
                CuttingUnitCode = initializer.Units.First(),
                StratumCode     = sg.StratumCode,
                SampleGroupCode = sg.SampleGroupCode,
            };

            fromDb.Insert(tree);

            var tm = new TreeMeasurment
            {
                TreeID = tree.TreeID,
            };

            fromDb.Insert(tm);


            using var toDb = new DAL(toPath, true);

            var downMigrator = new DownMigrator();

            downMigrator.MigrateFromV3ToV2(initializer.CruiseID, fromDb, toDb);

            var treeAgain = toDb.From <V2.Models.Tree>().Where("TreeNumber = 101").Query().Single();

            treeAgain.Should().NotBeNull();
            treeAgain.DBH.Should().Be(12.0);
            treeAgain.DRC.Should().Be(13.0);

            ValidateMigration(fromDb, toDb);
        }
Beispiel #9
0
        public void RoundTripV2Migration_ignoreCountTreeRecordCount(string fileName)
        {
            var filePath      = Path.Combine(TestFilesDirectory, fileName);
            var reconvertPath = Path.Combine(TestTempPath, "again_" + fileName);

            Output.WriteLine(reconvertPath);

            // copy file to test temp dir
            var tempPath = Path.Combine(TestTempPath, fileName);

            File.Copy(filePath, tempPath, true);

            var v3Path = new Migrator().MigrateFromV2ToV3(tempPath, true);

            using (var v2db = new DAL(tempPath))
                using (var v3Database = new CruiseDatastore_V3(v3Path))
                {
                    var units        = v2db.From <V2.Models.CuttingUnit>().Query();
                    var strata       = v2db.From <V2.Models.Stratum>().Query().ToArray();
                    var samplegroups = v2db.From <V2.Models.SampleGroup>().Query();
                    var plots        = v2db.From <V2.Models.Plot>().Query();
                    var trees        = v2db.From <V2.Models.Tree>().Query();
                    var reports      = v2db.From <V2.Models.Reports>().Query();

                    var cruise   = v3Database.From <Cruise>().Query().Single();
                    var cruiseID = cruise.CruiseID;

                    using (var v2again = new DAL(reconvertPath, true))
                    {
                        var tableInfo = v2again.GetTableInfo("Sale");

                        var downMigrator = new DownMigrator();
                        downMigrator.MigrateFromV3ToV2(cruiseID, v3Database, v2again, "test");

                        var unitsAgain = v2again.From <V2.Models.CuttingUnit>().Query();
                        unitsAgain.Should().BeEquivalentTo(units, config => config
                                                           .Using <string>(x => x.Subject.Should().Be(x.Expectation?.Trim())).WhenTypeIs <string>()// ignore whitespace when type is string
                                                           .Excluding(x => x.TallyHistory)
                                                           );

                        //var strataAgain = v2again.From<V2.Models.Stratum>().Query();
                        //strataAgain.Should().Should().BeEquivalentTo(strata);

                        var samplegroupsAgain = v2again.From <V2.Models.SampleGroup>().Query();
                        samplegroupsAgain.Should().BeEquivalentTo(samplegroups, config => config
                                                                  .Excluding(x => x.SampleSelectorState)
                                                                  .Excluding(x => x.SampleSelectorType)
                                                                  .Excluding(x => x.TallyMethod)
                                                                  );

                        var plotsAgain = v2again.From <V2.Models.Plot>().Query();
                        plotsAgain.Should().BeEquivalentTo(plots,
                                                           config => config
                                                           .Excluding(x => x.Plot_GUID)                                                // Plot_Stratum doesn't have a guid
                                                           .Using <string>(ctx => ctx.Subject.Should().Be(ctx.Expectation ?? "False")) // v3 will auto populate IsEmpty with False if null
                                                           .When(info => info.SelectedMemberPath.Equals(nameof(V2.Models.Plot.IsEmpty))));

                        var treesAgain = v2again.From <V2.Models.Tree>().Query();
                        treesAgain.Should().BeEquivalentTo(trees, congig => congig
                                                           .Excluding(x => x.Tree_GUID)
                                                           .Excluding(x => x.TreeDefaultValue_CN)
                                                           .Excluding(x => x.ExpansionFactor)
                                                           .Excluding(x => x.TreeFactor)
                                                           .Excluding(x => x.PointFactor)
                                                           .Excluding(x => x.TreeCount) // tree count may get combined into the count tree table
                                                           .Excluding(x => x.HiddenPrimary)
                                                           );

                        var reportsAgain = v2again.From <V2.Models.Reports>().Query();
                        reportsAgain.Should().BeEquivalentTo(reports);
                    }
                }
        }
Beispiel #10
0
        public void RoundTripV2Migration(string fileName)
        {
            var filePath      = Path.Combine(TestFilesDirectory, fileName);
            var reconvertPath = Path.Combine(TestTempPath, "again_" + fileName);

            Output.WriteLine(reconvertPath);

            // copy file to test temp dir
            var tempPath = Path.Combine(TestTempPath, fileName);

            File.Copy(filePath, tempPath, true);

            var v3Path = new Migrator().MigrateFromV2ToV3(tempPath, true);

            using (var v2db = new DAL(tempPath))
                using (var v3Database = new CruiseDatastore_V3(v3Path))
                {
                    var units        = v2db.From <V2.Models.CuttingUnit>().Query();
                    var strata       = v2db.From <V2.Models.Stratum>().Query().ToArray();
                    var samplegroups = v2db.From <V2.Models.SampleGroup>().Query();
                    var plots        = v2db.From <V2.Models.Plot>().Query();
                    var trees        = v2db.From <V2.Models.Tree>().Query();
                    //                var countTrees = v2db.Query<TreeCNTTotals>(
                    //@"SELECT CuttingUnit_CN, SampleGroup_CN, ifnull(TreeDefaultValue_CN, 0) AS TreeDefaultValue_CN, Sum(TreeCount) AS TreeCount, sum(SumKPI) AS SumKPI FROM CountTree
                    //GROUP BY CuttingUnit_CN, SampleGroup_CN, ifnull(TreeDefaultValue_CN, 0);").ToArray();

                    var treeCounts = v2db.Query <TreeCNTTotals>(
                        @"SELECT cnt.CuttingUnit_CN, cnt.SampleGroup_CN, cnt.TreeDefaultValue_CN, cnt.TreeCount + sum(TreeCNTTotal) AS TreeCNT, cnt.SumKPI 
 FROM CountTree AS cnt
 JOIN (SELECT CuttingUnit_CN, SampleGroup_CN, TreeDefaultValue_CN, Sum(TreeCount) as TreeCNTTotal
    FROM Tree 
    GROUP BY CuttingUnit_CN, SampleGroup_CN, ifnull(TreeDefaultValue_CN, 0)) AS tcnt on tcnt.CuttingUnit_CN = cnt.CuttingUnit_CN
                        AND tcnt.SampleGroup_CN = cnt.SampleGroup_CN
                        AND (cnt.TreeDefaultValue_CN IS NULL OR ifnull(tcnt.TreeDefaultValue_CN, 0) = ifnull(cnt.TreeDefaultValue_CN, 0))

GROUP BY cnt.CuttingUnit_CN, cnt.SampleGroup_CN, cnt.TreeDefaultValue_CN
ORDER BY cnt.CuttingUnit_CN, cnt.SampleGroup_CN, cnt.TreeDefaultValue_CN;").ToArray();

                    var cruise   = v3Database.From <Cruise>().Query().Single();
                    var cruiseID = cruise.CruiseID;

                    using (var v2again = new DAL(reconvertPath, true))
                    {
                        var tableInfo = v2again.GetTableInfo("Sale");

                        var downMigrator = new DownMigrator();
                        downMigrator.MigrateFromV3ToV2(cruiseID, v3Database, v2again, "test");

                        //                    var countTreesAgain = v2again.Query<TreeCNTTotals>(
                        //@"SELECT CuttingUnit_CN, SampleGroup_CN, ifnull(TreeDefaultValue_CN, 0) AS TreeDefaultValue_CN, Sum(TreeCount) AS TreeCount, sum(SumKPI) AS SumKPI FROM CountTree
                        //GROUP BY CuttingUnit_CN, SampleGroup_CN, ifnull(TreeDefaultValue_CN, 0);").ToArray();


                        //                    var countTreeDiff = countTreesAgain.Except(countTrees).ToArray();
                        //                    countTreesAgain.Should().BeEquivalentTo(countTrees);

                        var treeCountsAgain = v2again.Query <TreeCNTTotals>(
                            @"SELECT cnt.CuttingUnit_CN, cnt.SampleGroup_CN, cnt.TreeDefaultValue_CN, cnt.TreeCount + sum(TreeCNTTotal) AS TreeCNT, cnt.SumKPI 
 FROM CountTree AS cnt
 JOIN (SELECT CuttingUnit_CN, SampleGroup_CN, TreeDefaultValue_CN, Sum(TreeCount) as TreeCNTTotal
    FROM Tree 
    GROUP BY CuttingUnit_CN, SampleGroup_CN, ifnull(TreeDefaultValue_CN, 0)) AS tcnt on tcnt.CuttingUnit_CN = cnt.CuttingUnit_CN
                        AND tcnt.SampleGroup_CN = cnt.SampleGroup_CN
                        AND (cnt.TreeDefaultValue_CN IS NULL OR ifnull(tcnt.TreeDefaultValue_CN, 0) = ifnull(cnt.TreeDefaultValue_CN, 0))
GROUP BY cnt.CuttingUnit_CN, cnt.SampleGroup_CN, cnt.TreeDefaultValue_CN
ORDER BY cnt.CuttingUnit_CN, cnt.SampleGroup_CN, cnt.TreeDefaultValue_CN;").ToArray();

                        var treeCountDiff = treeCountsAgain.Except(treeCounts).ToArray();
                        treeCountsAgain.Should().BeEquivalentTo(treeCounts);

                        var unitsAgain = v2again.From <V2.Models.CuttingUnit>().Query();
                        unitsAgain.Should().BeEquivalentTo(units, config => config
                                                           .Using <string>(x => x.Subject.Should().Be(x.Expectation?.Trim())).WhenTypeIs <string>()// ignore whitespace when type is string
                                                           .Excluding(x => x.TallyHistory)
                                                           );

                        //var strataAgain = v2again.From<V2.Models.Stratum>().Query();
                        //strataAgain.Should().Should().BeEquivalentTo(strata);

                        var samplegroupsAgain = v2again.From <V2.Models.SampleGroup>().Query();
                        samplegroupsAgain.Should().BeEquivalentTo(samplegroups, config => config
                                                                  .Excluding(x => x.SampleSelectorState)
                                                                  .Excluding(x => x.SampleSelectorType)
                                                                  .Excluding(x => x.TallyMethod)
                                                                  );

                        var plotsAgain = v2again.From <V2.Models.Plot>().Query();
                        plotsAgain.Should().BeEquivalentTo(plots,
                                                           config => config
                                                           .Excluding(x => x.Plot_GUID)                                                // Plot_Stratum doesn't have a guid
                                                           .Using <string>(ctx => ctx.Subject.Should().Be(ctx.Expectation ?? "False")) // v3 will auto populate IsEmpty with False if null
                                                           .When(info => info.SelectedMemberPath.Equals(nameof(V2.Models.Plot.IsEmpty))));

                        var treesAgain = v2again.From <V2.Models.Tree>().Query();
                        treesAgain.Should().BeEquivalentTo(trees, congig => congig
                                                           .Excluding(x => x.Tree_GUID)
                                                           .Excluding(x => x.TreeDefaultValue_CN)
                                                           .Excluding(x => x.ExpansionFactor)
                                                           .Excluding(x => x.TreeFactor)
                                                           .Excluding(x => x.PointFactor)
                                                           .Excluding(x => x.TreeCount) // tree count may get combined into the count tree table
                                                           );
                    }
                }
        }
Beispiel #11
0
        public void MigrateFromV3ToV2()
        {
            var fromPath = GetTempFilePath(" TreeDefaultValueDownMigrator_MigrateFromV3ToV2.crz3");
            var toPath   = GetTempFilePath(" TreeDefaultValueDownMigrator_MigrateFromV3ToV2.cruise");

            var initializer = new DatabaseInitializer()
            {
                Species      = new[] { "sp1", "sp2", "sp3" },
                TreeDefaults = new[]
                {
                    new TreeDefaultValue {
                        SpeciesCode = "sp1", PrimaryProduct = "01", Recoverable = 1.1,
                    },
                    new TreeDefaultValue {
                        SpeciesCode = null, PrimaryProduct = "01", Recoverable = 1.2,
                    },
                    new TreeDefaultValue {
                        SpeciesCode = "sp1", PrimaryProduct = null, Recoverable = 1.3,
                    },
                    new TreeDefaultValue {
                        SpeciesCode = null, PrimaryProduct = null, Recoverable = 1.4,
                    },
                },
                Subpops = new SubPopulation[] { },
            };

            using var fromDb = initializer.CreateDatabaseFile(fromPath);
            using var toDb   = new DAL(toPath, true);

            var downMigrator = new DownMigrator(new[] { new TreeDefaultValueDownMigrate(), });

            downMigrator.MigrateFromV3ToV2(initializer.CruiseID, fromDb, toDb);

            var prodCount = fromDb.From <LK_Product>().Count();
            var spCount   = initializer.Species.Count();

            // from the one TDV with explicitly set species and prod we should get two TDVs (one live one dead
            var tdvs = toDb.From <V2.Models.TreeDefaultValue>().Where("Species = @p1 AND PrimaryProduct = @p2").Query("sp1", "01").ToArray();

            tdvs.Should().HaveCount(2);
            tdvs.Should().OnlyContain(x => x.Recoverable == 1.1);

            // from the TDV with explicitly set product, we should have 2 TDVs for each species minus the one that was created with explicit sp and prod
            var tdvFromProd = toDb.From <V2.Models.TreeDefaultValue>().Where("PrimaryProduct = @p1 AND Species != @p2 ").Query("01", "sp1").ToArray();

            tdvFromProd.Should().HaveCount((int)((spCount - 1) * 2));
            tdvFromProd.Should().OnlyContain(x => x.Recoverable == 1.2);

            // from the TDV with explicitly set species, we should have 2 TDVs for each product minus the one that was created with explicit sp and prod
            var tdvFromSp = toDb.From <V2.Models.TreeDefaultValue>().Where("Species = @p1 AND PrimaryProduct != @p2").Query("sp1", "01").ToArray();

            tdvFromSp.Should().HaveCount((int)((prodCount - 1) * 2));
            tdvFromSp.Should().OnlyContain(x => x.Recoverable == 1.3);

            // from the TDV with neither species or product defined, we should get (sp -1 * prod - 1) * 2 TDVs
            var tdvFromAnyAny = toDb.From <V2.Models.TreeDefaultValue>().Where("Species != @p1 AND PrimaryProduct != @p2").Query("sp1", "01").ToArray();

            tdvFromAnyAny.Should().HaveCount((int)((spCount - 1) * (prodCount - 1) * 2));
            tdvFromAnyAny.Should().OnlyContain(x => x.Recoverable == 1.4);

            var expectedTDVcount = (1 + (spCount - 1) + (prodCount - 1) + ((spCount - 1) * (prodCount - 1))) * 2;
            var alltdv           = toDb.From <V2.Models.TreeDefaultValue>().Query().ToArray();

            alltdv.Should().HaveCount((int)expectedTDVcount);
        }
        public void CountTree_TreeBased_SingleTallyPop_SingleUnit()
        {
            var fromPath = GetTempFilePath(" CountTree_TreeBased_SingleTallyPop_SingleUnit_MigrateFromV3ToV2.crz3");
            var toPath   = GetTempFilePath(" CountTree_TreeBased_SingleTallyPop_SingleUnit_MigrateFromV3ToV2.cruise");

            var init = new DatabaseInitializer()
            {
                Units  = new[] { "u1" },
                Strata = new[] { new Stratum {
                                     StratumCode = "st1", Method = "STR"
                                 } },
                UnitStrata = new[] { new CuttingUnit_Stratum {
                                         StratumCode = "st1", CuttingUnitCode = "u1"
                                     } },
                SampleGroups = new[] { new SampleGroup {
                                           StratumCode = "st1", SampleGroupCode = "sg1", SamplingFrequency = 101, TallyBySubPop = false
                                       } },
                Subpops = new[] { new SubPopulation {
                                      StratumCode = "st1", SampleGroupCode = "sg1", SpeciesCode = "sp1", LiveDead = "L"
                                  } },
            };

            var expectedCountTreeCount = 1;

            using var fromdb = init.CreateDatabaseFile(fromPath);
            using var todb   = new DAL(toPath, true);

            var unit    = "u1";
            var stratum = "st1";
            var sg      = "sg1";

            var tallyLedgers = new TallyLedger[]
            {
                new TallyLedger {
                    CruiseID = init.CruiseID, CuttingUnitCode = "u1", StratumCode = "st1", SampleGroupCode = "sg1", TreeCount = 101, SpeciesCode = "sp1", LiveDead = "L"
                },
            };

            foreach (var tl in tallyLedgers)
            {
                tl.TallyLedgerID = Guid.NewGuid().ToString();
                fromdb.Insert(tl);
            }

            var tallyPops = fromdb.From <TallyPopulation>().Query().ToArray();

            tallyPops.Should().NotBeEmpty();

            var downMigrator = new DownMigrator();

            downMigrator.MigrateFromV3ToV2(init.CruiseID, fromdb, todb);

            var tls = fromdb.From <TallyLedger>().Query().ToArray();

            tls.Should().HaveCount(1);

            var countTrees = todb.From <V2.Models.CountTree>().Query().ToArray();

            countTrees.Should().HaveCount(expectedCountTreeCount);
            countTrees.Should().OnlyContain(x => x.TreeCount > 0);
        }
Beispiel #13
0
        }   //  end onEquations

        private void onFile(object sender, EventArgs e)
        {
            //  clear filename in case user wants to change files
            fileName = "";
            //  Create an instance of the open file dialog
            OpenFileDialog browseDialog = new OpenFileDialog();

            //  Set filter options and filter index
            browseDialog.Filter      = "Cruise Files - V2 |*.cruise|Cruise Files - V3|*.crz3|All Files|*.*";
            browseDialog.FilterIndex = 1;

            browseDialog.Multiselect = false;

            //  February 2017 -- nowhave the option to edit volume equations and selected reports
            //  on template files.  Need a flag indicating it is a template file so some
            //  tasks are skipped that would apply to just cruise files.
            templateFlag = 0;
            //  capture filename selected
            while (fileName == "" || fileName == null)
            {
                DialogResult dResult = browseDialog.ShowDialog();

                if (dResult == DialogResult.Cancel)
                {
                    return;
                }
                if (dResult == DialogResult.OK)
                {
                    fileName = browseDialog.FileName;
                    if (fileName.EndsWith(".cut") || fileName.EndsWith(".CUT"))
                    {
                        //  disable all buttons except equations and reports
                        menuButton2.BackgroundImage = Properties.Resources.button_image;
                        menuButton3.BackgroundImage = Properties.Resources.button_image;
                        processBtn.BackgroundImage  = Properties.Resources.disabled_button;
                        menuButton5.BackgroundImage = Properties.Resources.disabled_button;
                        menuButton2.Enabled         = true;
                        menuButton3.Enabled         = true;
                        processBtn.Enabled          = false;
                        menuButton5.Enabled         = false;

                        //  Have user enter a different file to preserve the regional tempalte file
                        DialogResult dr = MessageBox.Show("Do you want to use a different filename for any changes made?", "QUESTION", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dr == DialogResult.Yes)
                        {
                            //  show dialog to captue new filanem
                            EnterNewFilename enf = new EnterNewFilename();
                            enf.ShowDialog();
                            //  copy original file to new filename
                            string pathName = Path.GetDirectoryName(fileName);
                            pathName       += "\\";
                            newTemplateFile = enf.templateFilename;
                            newTemplateFile = newTemplateFile.Insert(0, pathName);
                            File.Copy(fileName, newTemplateFile, true);
                            fileName     = newTemplateFile;
                            DAL          = new DAL(newTemplateFile);
                            templateFlag = 1;
                        }
                        else if (dr == DialogResult.No)
                        {
                            //fileName = fileName;
                            DAL = new DAL(fileName);
                            if (fileName.EndsWith(".CUT") || fileName.EndsWith(".cut"))
                            {
                                newTemplateFile = fileName;
                                templateFlag    = 1;
                            }
                            else
                            {
                                templateFlag = 0;
                            }
                        }   //  endif
                    }
                    else if (!fileName.EndsWith(".cruise") && !fileName.EndsWith(".CRUISE"))
                    {
                        if (!fileName.EndsWith(".crz3") && !fileName.EndsWith(".CRZ3"))
                        {
                            //  is it a cruise file?
                            MessageBox.Show("File selected is not a cruise file.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else
                        {
                            DAL_V3 = new CruiseDatastore_V3(fileName);

                            string V2FileName = fileName.Replace(".crz3", "").Replace(".CRZ3", "");

                            //V2FileName = V2FileName + "WBTest.cruise";
                            V2FileName = V2FileName + ".process";

                            try
                            {
                                var cruiseIDs = DAL_V3.QueryScalar <string>("SELECT CruiseID FROM Cruise;").ToArray();
                                if (cruiseIDs.Length > 1)
                                {
                                    MessageBox.Show("File contains multiple cruises. \r\nOpening files with multiple cruises is not supported yet", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }

                                var cruiseID = cruiseIDs.First();

                                string cruiseV2Path = V2FileName;


                                CruiseDatastoreBuilder_V2 V2Builder = new CruiseDatastoreBuilder_V2();
                                Updater_V2 v2Updater = new Updater_V2();

                                CruiseDatastore myV2DAL = new DAL(cruiseV2Path, true);
                                //CruiseDatastore v2DB = new CruiseDatastore(cruiseV2Path, true, V2Builder, v2Updater);


                                DownMigrator myMyigrator = new DownMigrator();

                                string error_message = "";
                                if (myMyigrator.EnsureCanMigrate(cruiseID, DAL_V3, out error_message))
                                {
                                    //CONVERT LOGIC NEEDED HERE.
                                    myMyigrator.MigrateFromV3ToV2(cruiseID, DAL_V3, myV2DAL);
                                    fileName = V2FileName;
                                }//end if
                                else
                                {
                                    MessageBox.Show("This version 3 file has issues. \r\nError: " + error_message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }//end else
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("This version 3 file has issues. \r\n", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                        }
                    }   //  endif
                }
            }
            ;   //  end while

            if (templateFlag == 0)
            {
                //  check for fatal errors before doing anything else --  October 20145
                //fileName = fileName;
                DAL = new DAL(fileName);

                //open connection forces the connection to remain open not to close and open.  Might be good to re-work the process button click?
                DAL.OpenConnection();

                string[] errors;
                //               bool ithResult = bslyr.DAL.HasCruiseErrors(out errors);
                bool ithResult = false;
                if (ithResult)
                {
                    MessageBox.Show("This file has errors which affect processing.\nCannot continue until these are fixed in CruiseManager.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    menuButton2.BackgroundImage = Properties.Resources.disabled_button;
                    menuButton3.BackgroundImage = Properties.Resources.disabled_button;
                    processBtn.BackgroundImage  = Properties.Resources.disabled_button;
                    menuButton5.BackgroundImage = Properties.Resources.disabled_button;
                    menuButton2.Enabled         = false;
                    menuButton3.Enabled         = false;
                    processBtn.Enabled          = false;
                    menuButton5.Enabled         = false;
                    return;
                }   //  end check for fatal errors

                // if filename is not blank, enable remaining menu buttons
                if (fileName.Contains(".cruise") || fileName.Contains(".CRUISE") || fileName.Contains(".process") || fileName.Contains(".PROCESS"))
                {
                    menuButton2.BackgroundImage = Properties.Resources.button_image;
                    menuButton3.BackgroundImage = Properties.Resources.button_image;
                    processBtn.BackgroundImage  = Properties.Resources.button_image;
                    menuButton5.BackgroundImage = Properties.Resources.button_image;

                    menuButton2.Enabled = true;
                    menuButton3.Enabled = true;
                    processBtn.Enabled  = true;
                    menuButton5.Enabled = true;

                    //  need region number in order to hide volume button as well as region 9 button
                    List <SaleDO> saleList = new List <SaleDO>();
                    saleList      = DAL.From <SaleDO>().Read().ToList();
                    currentRegion = saleList[0].Region;
                } //  endif
            }     //  endif tempalteFlag
            //  add file name to title line at top
            if (fileName.Length > 35)
            {
                string tempName = "..." + fileName.Substring(fileName.Length - 35, 35);
                Text = tempName;
            } //  endif fileName
        }     //  end onFile