Esempio n. 1
0
        private static void LoadStarhammer()
        {
            ShipTemplate template = TemplateDatabase.AddShip("Starhammer2");

            template.SetName(Resources.Corvette_StarhammerName);
            template.SetDescription(Resources.Corvette_StarhammerDescription);
            template.SetClass("Corvette", "Destroyer");
            template.SetModel("battleship_destroyer_4_upgraded");
            template.SetRadarTrace("radar_dread.png");
            template.SetHull(200);
            template.SetShields(new float[] { 450, 350, 150, 150, 350 });
            template.SetSpeed(335, 6, 10);
            template.SetJumpDrive();
            // Arc, Dir, Range, CycleTime, Dmg
            template.SetupBeamWeapon(0, 60, -10, 2000, 8, 11);
            template.SetupBeamWeapon(1, 60, 10, 2000, 8, 11);
            template.SetupBeamWeapon(2, 60, -20, 1500, 8, 11);
            template.SetupBeamWeapon(3, 60, 20, 1500, 8, 11);

            template.SetMissleTubeCount(2, 10);
            template.SetupMissileMagazine(MissileWeaponTypes.HVLI, 20);
            template.SetupMissileMagazine(MissileWeaponTypes.Homing, 4);
            template.SetupMissileMagazine(MissileWeaponTypes.EMP, 2);
            template.RemoveTubeLoadTypes(1, MissileWeaponTypes.EMP);
        }
Esempio n. 2
0
        private static void LoadSupport()
        {
            ShipTemplate template = TemplateDatabase.AddShip("DefensePlatform");

            template.SetName(Resources.Corvette_DefensePlatformName);
            template.SetDescription(Resources.Corvette_DefensePlatformDescription);
            template.SetClass("Corvette", "Support");
            template.SetModel("space_station_4");
            template.SetRadarTrace("radartrace_smallstation.png");
            template.SetHull(150);
            template.SetShields(new float[] { 120, 120, 120, 120, 120, 120 });
            template.SetSpeed(0, 0.5f, 0);

            // Arc, Dir, Range, CycleTime, Dmg
            template.SetupBeamWeapon(0, 30, 0, 4000.0f, 1.5f, 20);
            template.SetupBeamWeapon(1, 30, 60, 4000.0f, 1.5f, 20);
            template.SetupBeamWeapon(2, 30, 120, 4000.0f, 1.5f, 20);
            template.SetupBeamWeapon(3, 30, 180, 4000.0f, 1.5f, 20);
            template.SetupBeamWeapon(4, 30, 240, 4000.0f, 1.5f, 20);
            template.SetupBeamWeapon(5, 30, 300, 4000.0f, 1.5f, 20);

            ShipTemplate.DockingPortInfo port = new ShipTemplate.DockingPortInfo();
            port.Legacy  = true;
            port.MaxSize = DockingClasses.Small;
            template.DockingPorts.Add(port);
        }
        protected TemplateRepository()
        {
            // set the db location
            dbLocation = DatabaseFilePath;

            // instantiate the database
            db = new TemplateDatabase (dbLocation);
        }
Esempio n. 4
0
        private static void UpdateStandardControl(XmlNodeList selectedNodes, TemplateDatabase templateDatabase, string typeWanted, ref List <string> errorMessages, ref List <string> dataLabels)
        {
            Debug.Assert(selectedNodes != null && selectedNodes.Count == 1, "Row update is supported for only a single XML element.");

            // assume the database is well formed and contains only a single row of the given standard type
            foreach (ControlRow control in templateDatabase.Controls)
            {
                if (control.Type == typeWanted)
                {
                    CodeTemplateImporter.UpdateControl(selectedNodes[0], templateDatabase, typeWanted, control, ref errorMessages, ref dataLabels);
                    return;
                }
            }

            throw new ArgumentOutOfRangeException(String.Format("Control of type {0} could not be found in database.", typeWanted));
        }
Esempio n. 5
0
        private void AddConnection()
        {
            frmOpenFile frm = new frmOpenFile();

            frm.AddFilter(new MyGxFilterGeoDatabases(), true);
            frm.Text = "选择数据库";
            if (frm.DoModalOpen() == DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;
                IGxDatabase database = frm.Items.get_Element(0) as IGxDatabase;
                if (database != null)
                {
                    ITemplateDatabase findDB =
                        _databases.FirstOrDefault(c => c.DatabaseName == (database as IGxObject).FullName);
                    if (findDB != null)
                    {
                        MessageService.Current.Warn("数据库已经连接,无需再次连接!");
                        return;
                    }
                    IFeatureWorkspace pWorkspace =
                        Yutai.ArcGIS.Common.Helpers.WorkspaceHelper.GetWorkspace((database as IGxObject).FullName);
                    if (pWorkspace == null)
                    {
                        return;
                    }
                    bool isExists1 = ((IWorkspace2)pWorkspace).get_NameExists(esriDatasetType.esriDTTable, "YT_TEMPLATE_FEATURECLASS");
                    // bool isExists2 = ((IWorkspace2)pWorkspace).get_NameExists(esriDatasetType.esriDTTable, "YT_TEMPLATE_FIELD");
                    bool isExists3 = ((IWorkspace2)pWorkspace).get_NameExists(esriDatasetType.esriDTTable, "YT_TEMPLATE_DOMAIN");
                    bool isExists4 = ((IWorkspace2)pWorkspace).get_NameExists(esriDatasetType.esriDTTable, "YT_TEMPLATE_DATASET");
                    ITemplateDatabase templateDatabase = new TemplateDatabase();
                    templateDatabase.DatabaseName = (database as IGxObject).FullName;
                    templateDatabase.Workspace    = pWorkspace;
                    _databases.Add(templateDatabase);
                    LoadDatabases();
                    //if (isExists4 && isExists1 && isExists3 && isExists2)
                    //{
                    //    this.txtDB.Text = BuildConnectionString((database as IGxObject).FullName);
                    //}
                    //else
                    //{
                    //    MessageService.Current.Warn("该数据库内没有地图制图模板数据!请重新选择!");
                    //}
                }
                Cursor.Current = Cursors.Default;
            }
            // LoadDatabases();
        }
Esempio n. 6
0
        private static void LoadAdders()
        {
            // MK5
            ShipTemplate template = TemplateDatabase.AddShip("AdderMk5");

            template.SetName(Resources.Fighter_AdderMk5Name);
            template.SetDescription(Resources.Fighter_AdderMk5Description);
            template.SetClass("Starfighter", "Gunship");
            template.SetModel("AdlerLongRangeScoutYellow");
            template.SetRadarTrace("radar_cruiser.png");
            template.SetHull(50);
            template.SetShields(30);
            template.SetSpeed(80, 28, 25);
            // Arc, Dir, Range, CycleTime, Dmg
            template.SetupBeamWeapon(0, 35, 0, 800, 5.0f, 2.0f);
            template.SetupBeamWeapon(1, 70, 30, 600, 5.0f, 2.0f);
            template.SetupBeamWeapon(2, 70, -35, 600, 5.0f, 2.0f);
            template.SetMissleTubeCount(1, 15);
            template.SetupMissileMagazine(MissileWeaponTypes.HVLI, 4);


            // MK4
            ShipTemplate variation = TemplateDatabase.CloneShip(template, "AdderMk4");

            variation.SetName(Resources.Fighter_AdderMk4Name);
            variation.SetDescription(Resources.Fighter_AdderMk4Description);
            variation.SetModel("AdlerLongRangeScoutBlue");
            variation.SetHull(40);
            variation.SetShields(20);
            variation.SetSpeed(60, 20, 20);
            variation.SetMissleTubeCount(1, 20);
            variation.ClearMagazines();
            variation.SetupMissileMagazine(MissileWeaponTypes.HVLI, 2);


            // MK6
            variation = TemplateDatabase.CloneShip(template, "AdderMk6");
            variation.SetName(Resources.Fighter_AdderMk6Name);
            variation.SetDescription(Resources.Fighter_AdderMk6Description);
            variation.SetupBeamWeapon(3, 35, 180, 600, 6.0f, 2.0f);
            variation.ClearMagazines();
            variation.SetupMissileMagazine(MissileWeaponTypes.HVLI, 8);
        }
Esempio n. 7
0
        internal static void Load()
        {
            if (StateData.Exists("StandardShips.Stations.Loaded") || StateData.GetB("StandardShips.Stations.Ignore"))
            {
                return;
            }

            StateData.Set("StandardShips.Stations.Loaded", true);

            ShipTemplate template = TemplateDatabase.AddStation("SmallStation");

            template.SetName(Resources.SmallStationName);
            template.SetModel("space_station_4");
            template.SetDescription(Resources.SmallStationDescription);
            template.SetHull(150);
            template.SetShields(300);
            template.SetRadarTrace("radartrace_smallstation.png");

            template = TemplateDatabase.AddStation("MediumStation");
            template.SetName(Resources.MediumStationName);
            template.SetModel("space_station_3");
            template.SetDescription(Resources.MediumStationDescription);
            template.SetHull(400);
            template.SetShields(800);
            template.SetRadarTrace("radartrace_mediumstation.png");

            template = TemplateDatabase.AddStation("LargeStation");
            template.SetName(Resources.LargeStationName);
            template.SetModel("space_station_2");
            template.SetDescription(Resources.LargeStationDescription);
            template.SetHull(500);
            template.SetShields(new float[] { 1000, 1000, 1000 });
            template.SetRadarTrace("radartrace_largestation.png");

            template = TemplateDatabase.AddStation("HugeStation");
            template.SetName(Resources.HugeStationName);
            template.SetModel("space_station_1");
            template.SetDescription(Resources.HugeStationDescription);
            template.SetHull(800);
            template.SetShields(new float[] { 1200, 1200, 1200, 1200 });
            template.SetRadarTrace("radartrace_hugestation.png");
        }
Esempio n. 8
0
        private static void AddFreighter(string haul, string displayName, string description, int index, int baseModelIndex, bool jump)
        {
            string name    = displayName + (jump ? "JumpFreighter" : "Freighter") + index.ToString();
            string display = displayName + " " + (jump ? Resources.JumpFreighterBaseName : Resources.FreighterBaseName) + " " + index.ToString();

            ShipTemplate template = TemplateDatabase.AddShip(name);

            template.SetName(display);
            template.SetDescription(description);
            template.SetClass("Corvette", "Freighter");
            template.SetModel("transport_" + baseModelIndex.ToString() + "_" + index.ToString());
            template.SetRadarTrace("radartrace_smallstation.png");
            template.SetHull(150);
            template.SetShields(new float[] { 50, 50 });
            template.SetSpeed(60 - 5 * index, 6, 10);
            if (jump)
            {
                template.SetJumpDrive();
                template.SetJumpRanges(2000, 40000);
            }
        }
Esempio n. 9
0
        private static void LoadJumpCarrier()
        {
            ShipTemplate template = TemplateDatabase.AddShip("JumpCarrier");

            template.SetName(Resources.Corvette_JumpCarrierName);
            template.SetDescription(Resources.Corvette_JumpCarrierDescription);
            template.SetClass("Corvette", "Freighter");
            template.SetModel("transport_4_2");
            template.SetRadarTrace("radar_transport.png");
            template.SetHull(100);
            template.SetShields(new float[] { 50, 50 });
            template.SetSpeed(50, 6, 10);
            template.SetJumpDrive();
            template.SetJumpRanges(5000, 100 * 50000);

            for (int i = 0; i < 20; i++)
            {
                ShipTemplate.DockingPortInfo port = new ShipTemplate.DockingPortInfo();
                port.Legacy  = true;
                port.MaxSize = DockingClasses.Medium;
                template.DockingPorts.Add(port);
            }
        }
Esempio n. 10
0
        private static void LoadLindworm()
        {
            ShipTemplate template = TemplateDatabase.AddShip("Lindworm");

            template.SetName(Resources.Fighter_LindwormName);
            template.SetDescription(Resources.Fighter_LindwormDescription);
            template.SetClass("Starfighter", "Bomber");
            template.SetModel("LindwurmFighterYellow");
            template.SetRadarTrace("radar_fighter.png");
            template.SetHull(50);
            template.SetShields(20);
            template.SetSpeed(50, 15, 25);

            template.SetMissleTubeCount(3, 15);
            template.SetupMissileMagazine(MissileWeaponTypes.HVLI, 4);
            template.SetupMissileMagazine(MissileWeaponTypes.Homing, 1);

            template.SetMissileWeaponLoadingTypes(1, MissileWeaponTypes.HVLI);
            template.SetMissileWeaponLoadingTypes(2, MissileWeaponTypes.HVLI);

            template.SetMissleWeaponDirection(1, 1);
            template.SetMissleWeaponDirection(2, -1);
        }
Esempio n. 11
0
        public virtual int SpawnPlayableShip(string requester, string requestedType, string requestedName)
        {
            string typeToUse = requestedType;

            // something wants a new player ship to be spawned
            if (typeToUse == string.Empty)
            {
                typeToUse = GetPlayerShipTemplate();
            }

            ShipTemplate template = TemplateDatabase.GetTemplate(typeToUse) as ShipTemplate;

            if (!GetPlayableShips().Contains(template) && GetPlayableShips().Count > 0)
            {
                template = GetPlayableShips()[0];
            }

            Zone spawnZone = ZoneManager.FindZone(GetDefaultZoneName());

            if (spawnZone == null)
            {
                var zones = ZoneManager.GetZones();
                if (zones.Length == 0)
                {
                    return(-1); // no zones to spawn a ship in
                }
                spawnZone = zones[0];
            }

            var ship = new Ship(template);

            ship.Name = FilterShipName(requestedName, requestedType);

            spawnZone.Add(ship);

            return(ship.GUID);
        }
Esempio n. 12
0
        public static void Import(string filePath, TemplateDatabase templateDatabase, out List <string> conversionErrors)
        {
            ThrowIf.IsNullArgument(templateDatabase, nameof(templateDatabase));
            conversionErrors = new List <string>();

            // Collect all the data labels as we come across them, as we have to ensure that a new data label doesn't have the same name as an existing one
            List <string> dataLabels = new List <string>();

            // Load the XML document (the code template file)
            // Follows CA3075  pattern for loading
            XmlDocument xmlDoc = new XmlDocument()
            {
                XmlResolver = null
            };

            System.IO.StringReader sreader = new System.IO.StringReader(File.ReadAllText(filePath));
            XmlReader reader = XmlReader.Create(sreader, new XmlReaderSettings()
            {
                XmlResolver = null
            });

            xmlDoc.Load(reader);

            // merge standard controls which existed in code templates
            // MarkForDeletion and Relative path weren't available in code templates
            // NOTE THAT WE NEED TO UPDATE THIS TO NEWER DELETEFLAG
            XmlNodeList selectedNodes = xmlDoc.SelectNodes(Constant.ImageXml.FilePath); // Convert the File type

            CodeTemplateImporter.UpdateStandardControl(selectedNodes, templateDatabase, Constant.DatabaseColumn.File, ref conversionErrors, ref dataLabels);

            selectedNodes = xmlDoc.SelectNodes(Constant.ImageXml.FolderPath); // Convert the Folder type
            CodeTemplateImporter.UpdateStandardControl(selectedNodes, templateDatabase, Constant.DatabaseColumn.Folder, ref conversionErrors, ref dataLabels);

            selectedNodes = xmlDoc.SelectNodes(Constant.ImageXml.DatePath); // Convert the Date type
            CodeTemplateImporter.UpdateStandardControl(selectedNodes, templateDatabase, Constant.DatabaseColumn.Date, ref conversionErrors, ref dataLabels);

            selectedNodes = xmlDoc.SelectNodes(Constant.ImageXml.TimePath); // Convert the Time type
            CodeTemplateImporter.UpdateStandardControl(selectedNodes, templateDatabase, Constant.DatabaseColumn.Time, ref conversionErrors, ref dataLabels);

            selectedNodes = xmlDoc.SelectNodes(Constant.ImageXml.ImageQualityPath); // Convert the Image Quality type
            CodeTemplateImporter.UpdateStandardControl(selectedNodes, templateDatabase, Constant.DatabaseColumn.ImageQuality, ref conversionErrors, ref dataLabels);

            // no flag controls to import
            // import notes
            selectedNodes = xmlDoc.SelectNodes(Constant.ImageXml.NotePath);
            for (int index = 0; index < selectedNodes.Count; index++)
            {
                ControlRow note = templateDatabase.AddUserDefinedControl(Constant.Control.Note);
                CodeTemplateImporter.UpdateControl(selectedNodes[index], templateDatabase, Constant.Control.Note, note, ref conversionErrors, ref dataLabels);
            }

            // import choices
            selectedNodes = xmlDoc.SelectNodes(Constant.ImageXml.FixedChoicePath);
            for (int index = 0; index < selectedNodes.Count; index++)
            {
                ControlRow choice = templateDatabase.AddUserDefinedControl(Constant.Control.FixedChoice);
                CodeTemplateImporter.UpdateControl(selectedNodes[index], templateDatabase, Constant.Control.FixedChoice, choice, ref conversionErrors, ref dataLabels);
            }

            // import counters
            selectedNodes = xmlDoc.SelectNodes(Constant.ImageXml.CounterPath);
            for (int index = 0; index < selectedNodes.Count; index++)
            {
                ControlRow counter = templateDatabase.AddUserDefinedControl(Constant.Control.Counter);
                CodeTemplateImporter.UpdateControl(selectedNodes[index], templateDatabase, Constant.Control.Counter, counter, ref conversionErrors, ref dataLabels);
            }
            if (reader != null)
            {
                reader.Dispose();
            }
        }
Esempio n. 13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            // Add the console logger.
            loggerFactory.AddConsole(Configuration.GetSection("Logging")).AddDebug();
            loggerFactory.AddFile("/var/log/webui/webui-{Date}.txt");

            var _logger = loggerFactory.CreateLogger("Configure");

            ConfigurationParser.ParseConfiguration(loggerFactory);
            var clusters = ConfigurationParser.GetConfiguration("DLClusters") as Dictionary <string, object>;

            if (Object.ReferenceEquals(clusters, null))
            {
                throw new ArgumentException("There are no DLClusters in the configuration file");
            }
            Clusters = new Dictionary <string, DLCluster>();
            Database = new Dictionary <string, ClusterContext>();
            string defaultClusterName = null;

            foreach (var pair in clusters)
            {
                var clusterName   = pair.Key;
                var clusterConfig = pair.Value as Dictionary <string, object>;
                _logger.LogInformation("Configure cluster {0}", clusterName);
                if (Object.ReferenceEquals(clusterConfig, null))
                {
                    throw new ArgumentException("Configuration for cluster {0} is not provided as a JSon dictionary", clusterName);
                }
                var clusterInfo = new DLCluster();
                clusterInfo.ClusterName = clusterName;
                clusterInfo.ClusterId   = clusterConfig["ClusterId"] as string;
                if (clusterConfig.ContainsKey("AdminGroups"))
                {
                    var lst = ConfigurationParser.ParseConfigurationAsList(clusterConfig["AdminGroups"]);
                    // Convert to Dictionary for fast checkin
                    clusterInfo.AdminGroups = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);
                    foreach (var group in lst)
                    {
                        clusterInfo.AdminGroups[group] = true;
                    }
                }
                else
                {
                    clusterInfo.AdminGroups = new Dictionary <string, bool>();
                }
                if (clusterConfig.ContainsKey("AuthorizedGroups"))
                {
                    var lst = ConfigurationParser.ParseConfigurationAsList(clusterConfig["AuthorizedGroups"]);
                    clusterInfo.AuthorizedGroups = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);
                    foreach (var group in lst)
                    {
                        clusterInfo.AuthorizedGroups[group] = true;
                    }
                }
                else
                {
                    clusterInfo.AuthorizedGroups = new Dictionary <string, bool>();
                }
                if (clusterConfig.ContainsKey("RegisterGroups"))
                {
                    var lst = ConfigurationParser.ParseConfigurationAsList(clusterConfig["RegisterGroups"]);
                    clusterInfo.RegisterGroups = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);
                    foreach (var group in lst)
                    {
                        clusterInfo.RegisterGroups[group] = true;
                    }
                }
                else
                {
                    clusterInfo.RegisterGroups = new Dictionary <string, bool>();
                }

                clusterInfo.DataFolderAccessPoint = clusterConfig["DataFolderAccessPoint"] as string;
                clusterInfo.WorkFolderAccessPoint = clusterConfig["WorkFolderAccessPoint"] as string;
                clusterInfo.Restapi            = clusterConfig["Restapi"] as string;
                clusterInfo.SQLDatabaseForUser = clusterConfig["SQLDatabaseForUser"] as string;
                clusterInfo.SQLHostname        = clusterConfig["SQLHostname"] as string;
                clusterInfo.SQLPassword        = clusterConfig["SQLPassword"] as string;
                clusterInfo.SQLUsername        = clusterConfig["SQLUsername"] as string;
                var isDefault = clusterConfig.ContainsKey("Default") && (clusterConfig["Default"] as string).ToLower() == "true";
                if (isDefault)
                {
                    defaultClusterName = clusterName;
                }
                _logger.LogDebug("ClusterId: {0}", clusterInfo.ClusterId);
                _logger.LogDebug("DataFolderAccessPoint: {0}", clusterInfo.DataFolderAccessPoint);
                _logger.LogDebug("WorkFolderAccessPoint: {0}", clusterInfo.WorkFolderAccessPoint);
                _logger.LogDebug("Restapi: {0}", clusterInfo.Restapi);
                _logger.LogDebug("SQLDatabaseForUser: {0}", clusterInfo.SQLDatabaseForUser);
                _logger.LogDebug("SQLHostname: {0}", clusterInfo.SQLHostname);
                _logger.LogDebug("SQLPassword: {0}", clusterInfo.SQLPassword);
                _logger.LogDebug("SQLUsername: {0}", clusterInfo.SQLUsername);
                Clusters[clusterName] = clusterInfo;
                var connectionUsers = String.Format("Server={0};Database={1}{2};User Id={3};Password={4}",
                                                    clusterInfo.SQLHostname,
                                                    clusterInfo.SQLDatabaseForUser,
                                                    clusterInfo.ClusterId,
                                                    clusterInfo.SQLUsername,
                                                    clusterInfo.SQLPassword);
                var optionsBuilderUsers = new DbContextOptionsBuilder <ClusterContext>();
                optionsBuilderUsers.UseSqlServer(connectionUsers);
                var userDatabase = new ClusterContext(optionsBuilderUsers.Options);
                userDatabase.Database.EnsureCreated();
                Database[clusterName] = userDatabase;
            }

            var templateDb      = ConfigurationParser.GetConfiguration("MasterTemplates") as Dictionary <string, object>;
            var templatesMaster = new TemplateDatabase();

            templatesMaster.SQLDatabaseForTemplates = templateDb["SQLDatabaseForTemplates"] as string;
            templatesMaster.SQLHostname             = templateDb["SQLHostname"] as string;
            templatesMaster.SQLPassword             = templateDb["SQLPassword"] as string;
            templatesMaster.SQLUsername             = templateDb["SQLUsername"] as string;
            var connectionTemplatesMaster = String.Format("Server={0};Database={1};User Id={2};Password={3}",
                                                          templatesMaster.SQLHostname,
                                                          templatesMaster.SQLDatabaseForTemplates,
                                                          templatesMaster.SQLUsername,
                                                          templatesMaster.SQLPassword);
            var optionsBuilderTemplatesMaster = new DbContextOptionsBuilder <ClusterContext>();

            optionsBuilderTemplatesMaster.UseSqlServer(connectionTemplatesMaster);
            var templateMasterDatabase = new ClusterContext(optionsBuilderTemplatesMaster.Options);
            var created     = templateMasterDatabase.Database.EnsureCreated();
            var entryArries = templateMasterDatabase.Template.Select(x => x.Template).ToArray();
            var dic         = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);

            foreach (var entry in entryArries)
            {
                dic.Add(entry, true);
            }
            var nEntries = entryArries.Length;

            _logger.LogInformation("# of entries in Master-Templates: {0}", nEntries);
            MasterDatabase = templateMasterDatabase;

            var template_file = "./Master-Templates.json";

            if (File.Exists(template_file))
            {
                int ncount = 0;
                _logger.LogInformation("Entries in template file: {0}", template_file);
                var list = new List <Tuple <string, string> >();
                using (var file = File.OpenText(template_file))
                    using (var reader = new JsonTextReader(file))
                    {
                        foreach (var templateTok in (JArray)JToken.ReadFrom(reader))
                        {
                            var template = (JObject)templateTok;
                            var TName    = template["Name"].Value <string>();
                            var TJson    = template["Json"].Value <string>();
                            _logger.LogInformation("{0}: {1}, {2}", ncount, TName, TJson);
                            list.Add(new Tuple <string, string>(TName, TJson));
                            ncount++;
                            // var sql = @"INSERT INTO dbo.Template (Template, Json, Type) VALUES ({0}, {1}, job)";
                            // MasterDatabase.Database.ExecuteSqlCommand(sql, TName, TJson);
                        }
                    }
                if (ncount > nEntries)
                {
                    // Trigger ingestion logic
                    foreach (var entry in list)
                    {
                        if (!dic.ContainsKey(entry.Item1))
                        {
                            TemplateEntry entryAdd = new TemplateEntry(entry.Item1, null, entry.Item2, "job");
                            MasterDatabase.Template.Add(entryAdd);
                        }
                    }
                    MasterDatabase.SaveChanges();
                }
            }

            if (String.IsNullOrEmpty(defaultClusterName))
            {
                defaultClusterName = Clusters.Keys.First <string>();
            }
            Clusters[""] = Clusters[defaultClusterName];
            _logger.LogDebug("Default Cluster: {0}", defaultClusterName);

            // Configure error handling middleware.
            app.UseExceptionHandler("/Home/Error");

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            // Configure the OWIN pipeline to use cookie auth.
            var cookieOpt = new CookieAuthenticationOptions();

            //cookieOpt.AutomaticAuthenticate = true;
            // cookieOpt.CookieName = "dlws-auth";
            //cookieOpt.CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
            // cookieOpt.AuthenticationScheme = "Cookies";
            app.UseCookieAuthentication(cookieOpt);

            var deployAuthenticationConfig = ConfigurationParser.GetConfiguration("DeployAuthentications") as Dictionary <string, object>;
            var deployAuthentication       = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);

            foreach (var pair in deployAuthenticationConfig)
            {
                deployAuthentication[pair.Value as string] = true;
            }
            int numDeployedAuthentication = deployAuthentication.Count;

            var authentication = ConfigurationParser.GetConfiguration("Authentications") as Dictionary <string, object>;

            AuthenticationSchemes = new Dictionary <string, OpenIDAuthentication>();
            foreach (var pair in authentication)
            {
                bool bUse = (numDeployedAuthentication == 0 || deployAuthentication.ContainsKey(pair.Key));
                if (bUse)
                {
                    var authenticationScheme = pair.Key;
                    var authenticationConfig = pair.Value;
                    var openIDOpt            = new OpenIDAuthentication(authenticationScheme, authenticationConfig, loggerFactory);
                    AuthenticationSchemes[authenticationScheme] = openIDOpt;
                    app.UseOpenIdConnectAuthentication(openIDOpt);
                }
            }

            // Configure the OWIN pipeline to use OpenID Connect auth.
            app.UseSession();
            // Configure MVC routes
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Esempio n. 14
0
 protected override void Context()
 {
     sut = new TemplateDatabase();
 }
Esempio n. 15
0
 public virtual List <ShipTemplate> GetPlayableShips()
 {
     return(TemplateDatabase.GetAllShipsThatMatch((x) => x.IsPlayable));
 }
Esempio n. 16
0
        private static void LoadHorrents()
        {
            ShipTemplate template = TemplateDatabase.AddShip("HornetMk1");

            template.SetName(Resources.Fighter_HornetName);
            template.SetDescription(Resources.Fighter_HornetDescription);
            template.SetClass("Starfighter", "Interceptor");
            template.SetModel("WespeScoutYellow");
            template.SetRadarTrace("radar_fighter.png");
            template.SetHull(30);
            template.SetShields(20);
            template.SetSpeed(120, 30, 25);
            template.SetDefaultAI("fighter");
            // Arc, Dir, Range, CycleTime, Dmg
            template.SetupBeamWeapon(0, 30, 0, 700.0f, 4.0f, 2);

            template.SetFuelCapcity(400);

            template.SetReairCrew(1);

            template.AddRoom(3, 0, 1, 1, ShipSystemTypes.Maneuver);
            template.AddRoom(1, 0, 2, 1, ShipSystemTypes.Beams);
            template.AddRoom(0, 1, 1, 2, ShipSystemTypes.Shields(2));
            template.AddRoom(1, 1, 2, 2, ShipSystemTypes.Reactor);
            template.AddRoom(3, 1, 2, 1, ShipSystemTypes.FTL);
            template.AddRoom(3, 2, 2, 1, ShipSystemTypes.Jump);
            template.AddRoom(5, 1, 1, 2, ShipSystemTypes.Shields(1));
            template.AddRoom(1, 3, 2, 1, ShipSystemTypes.Missiles);
            template.AddRoom(3, 3, 1, 1, ShipSystemTypes.Sublight);

            template.AddDoor(2, 1, true);
            template.AddDoor(3, 1, true);
            template.AddDoor(1, 1, false);
            template.AddDoor(3, 1, false);
            template.AddDoor(3, 2, false);
            template.AddDoor(3, 3, true);
            template.AddDoor(2, 3, true);
            template.AddDoor(5, 1, false);
            template.AddDoor(5, 2, false);


            // mk2 upgrade
            ShipTemplate variation = TemplateDatabase.CloneShip(template, "HornetMk2");

            variation.SetName(Resources.Fighter_HornetMk2Name);
            variation.SetDescription(Resources.Fighter_HornetMk2Description);
            variation.SetModel("WespeScoutRed");
            variation.SetHull(35);
            variation.SetShields(22);
            variation.SetSpeed(125, 32, 25);
            variation.SetupBeamWeapon(0, 30, 0, 900.0f, 4.0f, 2.5f);


            // mk 3 player variant
            variation = TemplateDatabase.CloneShip(template, "HornetMk3P");
            variation.SetName(Resources.Fighter_HornetMk3Name);
            variation.SetDescription(Resources.Fighter_HornetMk3Description);

            variation.SetHull(70);
            variation.SetShields(60);
            variation.SetSpeed(125, 32, 25);
            variation.SetupBeamWeapon(0, 30, 0, 900.0f, 4.0f, 2.5f);
            variation.SetupBeamWeapon(1, 30, -5, 900.0f, 4.0f, 2.5f);
        }
Esempio n. 17
0
        public void evaluateRecords(Core.Database.IRecordEnumerable <TInputRecord> inputDatabase, TemplateDatabase templateDatabase, Core.Evaluation.Results.Results results)
        {
            onProgressChanged(new ProgressReport("Records evaluation started"));

            Dictionary <string, Dictionary <int, Core.Database.TemplateDatabase.TemplateRecord> > cache = new Dictionary <string, Dictionary <int, Core.Database.TemplateDatabase.TemplateRecord> >();

            //onProgressChanged(new ProgressReport("Create cache"));
            //List<TemplateCacheRecord> cache = new List<TemplateCacheRecord>();

            foreach (var block in evaluationSettings.getEvaluatedBlockIterator())
            {
                block.resetTemplates();
                cache.Add(block.Name, new Dictionary <int, Core.Database.TemplateDatabase.TemplateRecord>());
                foreach (Core.Database.TemplateDatabase.TemplateRecord templateRecord in templateDatabase.getCollections().getRecords())
                {
                    cache[block.Name].Add(
                        block.pushTemplate(
                            templateRecord.PersistentTemplate.getSubtemplate(block.Name)),
                        templateRecord
                        );
                }
            }

            int total = inputDatabase.getRecords().Count() * evaluationSettings.getEvaluatedBlockIterator().Count();
            int act   = 0;

            foreach (TInputRecord r in inputDatabase.getRecords())
            {
                string message = "Records evaluation ";
                message += ".";
                onProgressChanged(new ProgressReport(message, act, total));

                //create input data
                TInputData inputData = this.evaluationSettings.getInputDataCreator().createInputData(r);

                message += ".";
                onProgressChanged(new ProgressReport(message, act, total));

                foreach (var block in evaluationSettings.getEvaluatedBlockIterator())
                {
                    act++;

                    block.setInputData(inputData);

                    foreach (KeyValuePair <int, Core.Database.TemplateDatabase.TemplateRecord> pair in cache[block.Name])
                    {
                        //compare
                        MatchingScore matchingScore = block.computeMatchingScore(pair.Key);

                        //store result
                        Result result = new Result(new Record(pair.Value), new Record(r));
                        result.setMatchingScore(block.Name, matchingScore);

                        results.addResult(result);
                    }

                    message += ".";
                    onProgressChanged(new ProgressReport(message, act, total));
                }
            }
        }
Esempio n. 18
0
        private static void LoadAtlantis()
        {
            ShipTemplate template = TemplateDatabase.AddShip("AtlantisAI");

            template.SetName(Resources.Corvette_AtlantisX32Name);
            template.SetDescription(Resources.Corvette_AtlantisX32Description);
            template.SetClass("Corvette", "Destroyer");
            template.SetModel("battleship_destroyer_1_upgraded");
            template.SetRadarTrace("radar_dread.png");
            template.SetHull(100);
            template.SetShields(new float[] { 200, 200, 200, 200 });
            template.SetSpeed(30, 3.5f, 5);
            template.SetJumpDrive();
            // Arc, Dir, Range, CycleTime, Dmg
            template.SetupBeamWeapon(0, 100, -20, 1500.0f, 6.0f, 8);
            template.SetupBeamWeapon(1, 100, 20, 1500.0f, 6.0f, 8);
            template.SetupBeamWeapon(2, 100, 180, 1500.0f, 6.0f, 8);
            template.SetMissleTubeCount(4, 10);
            template.SetupMissileMagazine(MissileWeaponTypes.HVLI, 20);
            template.SetupMissileMagazine(MissileWeaponTypes.Homing, 20);
            template.SetMissleWeaponDirection(0, -90);
            template.SetMissleWeaponDirection(1, -90);
            template.SetMissleWeaponDirection(2, 90);
            template.SetMissleWeaponDirection(3, 90);

            template.AddRoom(1, 0, 2, 1, ShipSystemTypes.Maneuver);
            template.AddRoom(1, 1, 2, 1, ShipSystemTypes.Beams);
            template.AddRoom(2, 2, 2, 1);
            template.AddRoom(0, 3, 1, 2, ShipSystemTypes.Shields(1));
            template.AddRoom(1, 3, 2, 2, ShipSystemTypes.Reactor);
            template.AddRoom(3, 3, 2, 2, ShipSystemTypes.FTL);
            template.AddRoom(5, 3, 1, 2, ShipSystemTypes.Jump);
            template.AddRoom(6, 3, 2, 1);
            template.AddRoom(6, 4, 2, 1);
            template.AddRoom(8, 3, 1, 2, ShipSystemTypes.Shields(0));
            template.AddRoom(2, 5, 2, 1);
            template.AddRoom(1, 6, 2, 1, ShipSystemTypes.Missiles);
            template.AddRoom(1, 7, 2, 1, ShipSystemTypes.Sublight);

            template.AddDoor(1, 1, true);
            template.AddDoor(2, 2, true);
            template.AddDoor(3, 3, true);
            template.AddDoor(1, 3, false);
            template.AddDoor(3, 4, false);
            template.AddDoor(3, 5, true);
            template.AddDoor(2, 6, true);
            template.AddDoor(1, 7, true);
            template.AddDoor(5, 3, false);
            template.AddDoor(6, 3, false);
            template.AddDoor(6, 4, false);
            template.AddDoor(8, 3, false);
            template.AddDoor(8, 4, false);


            // player version
            var variation = TemplateDatabase.CloneShip(template, "AtlantisPlayer");

            variation.SetName(Resources.Corvette_AtlantisX32PName);
            variation.SetPlayable();
            variation.SetDescription(Resources.Corvette_AtlantisX32PDescription);
            variation.SetShields(new float[] { 200, 200 });
            variation.SetHull(250);
            variation.SetSpeed(90, 10, 20);
            variation.SetCombatManeuvers(400, 250);

            variation.RemoveBeamWeapon(2);
            variation.SetupMissileMagazine(MissileWeaponTypes.HVLI, 12);
            variation.SetupMissileMagazine(MissileWeaponTypes.Homing, 12);
            variation.SetupMissileMagazine(MissileWeaponTypes.Nuke, 4);
            variation.SetupMissileMagazine(MissileWeaponTypes.Mine, 8);
            variation.SetupMissileMagazine(MissileWeaponTypes.EMP, 6);

            variation.SetMissleTubeCount(5, 8);
            for (int i = 0; i < 4; i++)
            {
                variation.RemoveTubeLoadTypes(i, MissileWeaponTypes.Mine);
            }

            variation.SetMissileWeaponLoadingTypes(4, MissileWeaponTypes.Mine);
        }
Esempio n. 19
0
        private static void UpdateControl(XmlNode selectedNode, TemplateDatabase templateDatabase, string typeWanted, ControlRow control, ref List <string> errorMessages, ref List <string> dataLabels)
        {
            XmlNodeList selectedData = selectedNode.SelectNodes(Constant.ImageXml.Data);

            control.DefaultValue = GetColumn(selectedData, Constant.Control.DefaultValue);              // Default
            control.Width        = Int32.Parse(GetColumn(selectedData, Constant.Control.TextBoxWidth)); // Width

            // The tempTable should have defaults filled in at this point for labels, datalabels, and tooltips
            // Thus if we just get empty values, we should use those defaults rather than clearing them
            string label = GetColumn(selectedData, Constant.Control.Label);

            if (!String.IsNullOrEmpty(label))
            {
                control.Label = label;
            }

            string controlType = typeWanted;

            if (EditorControls.IsStandardControlType(typeWanted) == false)
            {
                controlType = GetColumn(selectedData, Constant.Control.DataLabel);
                if (String.IsNullOrWhiteSpace(controlType))
                {
                    controlType = label; // If there is no data label, use the label's value into it.
                }

                // string dataLabel = Regex.Replace(controlType, @"\s+", String.Empty);    // remove any white space that may be there
                string dataLabel = Regex.Replace(controlType, "[^a-zA-Z0-9_]", String.Empty);  // only allow alphanumeric and '_'.
                if (!dataLabel.Equals(controlType, StringComparison.InvariantCulture))
                {
                    errorMessages.Add("illicit characters: '" + controlType + "' changed to '" + dataLabel + "'");
                    controlType = dataLabel;
                }

                foreach (string sqlKeyword in EditorConstant.ReservedSqlKeywords)
                {
                    if (String.Equals(sqlKeyword, dataLabel, StringComparison.OrdinalIgnoreCase))
                    {
                        errorMessages.Add("reserved word:    '" + controlType + "' changed to '" + controlType + "_'");
                        controlType += "_";
                        break;
                    }
                }
            }

            // Now set the actual data label

            // First, check to see if the datalabel already exsists in the list, i.e., its not a unique key
            // If it doesn't, keep trying to add an integer to its end to make it unique.
            int    j = 0;
            string temp_datalabel = controlType;

            while (dataLabels.Contains(temp_datalabel))
            {
                temp_datalabel = controlType + j.ToString();
            }
            if (!controlType.Equals(temp_datalabel, StringComparison.InvariantCulture))
            {
                errorMessages.Add("duplicate data label:" + Environment.NewLine + "   '" + controlType + "' changed to '" + temp_datalabel + "'");
                controlType = temp_datalabel;
            }

            if (!String.IsNullOrEmpty(controlType))
            {
                if (controlType.Equals("Delete", StringComparison.InvariantCulture))
                {
                    controlType = Constant.ControlDefault.DeleteFlagLabel; // Delete is a reserved word!
                }
                control.DataLabel = controlType;
            }
            else
            {
                // If the data label was empty, the priority is to use the non-empty label contents
                // otherwise we stay with the default contents of the data label filled in previously
                label = Regex.Replace(label, @"\s+", String.Empty);
                if (!string.IsNullOrEmpty(label))
                {
                    control.DataLabel = label;
                }
            }
            dataLabels.Add(controlType); // and add it to the list of data labels seen

            string tooltip = GetColumn(selectedData, Constant.Control.Tooltip);

            if (!String.IsNullOrEmpty(tooltip))
            {
                control.Tooltip = tooltip;
            }

            // If there is no value supplied for Copyable, default is false for these data types (as they are already filled in by the system).
            // Counters are also not copyable be default, as we expect counts to change image by image. But there are cases where they user may want to alter this.
            bool defaultCopyable = true;

            if (EditorControls.IsStandardControlType(typeWanted))
            {
                defaultCopyable = false;
            }
            control.Copyable = ConvertToBool(TextFromNode(selectedData, 0, Constant.Control.Copyable), defaultCopyable);

            // If there is no value supplied for Visibility, default is true (i.e., the control will be visible in the interface)
            control.Visible = ConvertToBool(TextFromNode(selectedData, 0, Constant.Control.Visible), true);

            // if the type has a list, we have to do more work.
            if (typeWanted == Constant.DatabaseColumn.ImageQuality)
            {
                // For Image Quality, use the new list (longer than the one in old templates)
                control.List = Constant.ImageQuality.ListOfValues;
            }
            else if (typeWanted == Constant.DatabaseColumn.ImageQuality || typeWanted == Constant.Control.FixedChoice)
            {
                // Load up the menu items
                control.List = String.Empty; // For others, generate the list from what is stored

                XmlNodeList nodes     = selectedData[0].SelectNodes(Constant.Control.List + Constant.ImageXml.Slash + Constant.ImageXml.Item);
                bool        firstTime = true;
                foreach (XmlNode node in nodes)
                {
                    if (firstTime)
                    {
                        control.List = node.InnerText; // also clears the list's default values
                    }
                    else
                    {
                        control.List += "|" + node.InnerText;
                    }
                    firstTime = false;
                }
            }

            templateDatabase.SyncControlToDatabase(control);
        }
Esempio n. 20
0
 public static Ship FromRandomTemplate(ShipCategoryFinder finder)
 {
     return(FromTemplate(TemplateDatabase.RandomShip(TemplateDatabase.GetAllShipsThatMatch(finder))));
 }
Esempio n. 21
0
        // Given
        // - a path to a .tdb file  (specifying the root folder)
        // - a list of ddbFiles (which must be located in sub-folders relative to the root folder)
        // create a .ddb File in the root folder that merges data found in the .ddbFiles into it, in particular, the tables:
        // - DataTable
        // - Detections
        // If fatal errors occur in the merge, abort
        // Return the relevant error messages in the ErrorsAndWarnings object.
        // Note: if a merged .ddb File already exists in that root folder, it will be backed up and then over-written

        public async static Task <ErrorsAndWarnings> TryMergeDatabasesAsync(string tdbFile, List <string> sourceDDBFilePaths, IProgress <ProgressBarArguments> progress)
        {
            ErrorsAndWarnings errorMessages = new ErrorsAndWarnings();

            string rootFolderPath         = Path.GetDirectoryName(tdbFile);
            string destinationDDBFileName = Constant.File.MergedFileName;
            string destinationDDBFilePath = Path.Combine(rootFolderPath, destinationDDBFileName);
            string rootFolderName         = rootFolderPath.Split(Path.DirectorySeparatorChar).Last();


            if (sourceDDBFilePaths == null)
            {
                errorMessages.Errors.Add("No databases (.ddb files) were found in the sub-folders, so there was nothing to merge.");
                return(errorMessages);
            }

            // if the mergedatabase file was previously created, it may be included in the source list.
            // So just skip over it, as it no longer exists and we don't actually want it
            sourceDDBFilePaths.RemoveAll(Item => Item == destinationDDBFilePath);

            if (sourceDDBFilePaths.Count == 0)
            {
                errorMessages.Errors.Add("No databases (.ddb files) were found in the sub-folders, so there was nothing to merge.");
                return(errorMessages);
            }

            // Check to see if we can actually open the template.
            // As we can't have out parameters in an async method, we return the state and the desired templateDatabase as a tuple
            // Original form: if (!(await TemplateDatabase.TryCreateOrOpenAsync(templateDatabasePath, out this.templateDatabase).ConfigureAwait(true))
            Tuple <bool, TemplateDatabase> tupleResult = await TemplateDatabase.TryCreateOrOpenAsync(tdbFile).ConfigureAwait(true);

            TemplateDatabase templateDatabase = tupleResult.Item2;

            if (!tupleResult.Item1)
            {
                // notify the user the template couldn't be loaded rather than silently doing nothing
                errorMessages.Errors.Add("Could not open the template .tdb file: " + tdbFile);
                return(errorMessages);
            }

            // if the merge file exists, move it to the backup folder as we will be overwriting it.
            bool backupMade = false;

            if (File.Exists(destinationDDBFilePath))
            {
                // Backup the old merge file by moving it to the backup folder
                // Note that we do the move instead of copy as we will be overwriting the file anyways
                backupMade = FileBackup.TryCreateBackup(destinationDDBFilePath, true);
            }

            FileDatabase fd = await FileDatabase.CreateEmptyDatabase(destinationDDBFilePath, templateDatabase).ConfigureAwait(true);

            fd.Dispose();
            fd = null;

            // Open the database
            SQLiteWrapper destinationDDB = new SQLiteWrapper(destinationDDBFilePath);

            // Get the DataLabels from the DataTable in the main database.
            // We will later check to see if they match their counterparts in each database to merge in
            List <string> mergedDDBDataLabels = destinationDDB.SchemaGetColumns(Constant.DBTables.FileData);

            int sourceDDBFilePathsCount = sourceDDBFilePaths.Count;

            for (int i = 0; i < sourceDDBFilePathsCount; i++)
            {
                if (sourceDDBFilePaths[i].Equals(destinationDDBFilePath))
                {
                    // if the mergedatabase file was previously created, it may be included in the source list.
                    // So just skip over it, as it no longer exists and we don't actually want it
                    continue;
                }

                // Try to merge each database into the merged database
                await Task.Run(() =>
                {
                    // Report progress, introducing a delay to allow the UI thread to update and to make the progress bar linger on the display
                    progress.Report(new ProgressBarArguments((int)((i + 1) / (double)sourceDDBFilePathsCount * 100.0),
                                                             String.Format("Merging {0}/{1} databases. Please wait...", i + 1, sourceDDBFilePathsCount),
                                                             "Merging...",
                                                             false, false));
                    Thread.Sleep(250);
                    ListComparisonEnum listComparisonEnum = MergeDatabases.InsertSourceDataBaseTablesintoDestinationDatabase(destinationDDB, sourceDDBFilePaths[i], rootFolderPath, mergedDDBDataLabels);
                    if (listComparisonEnum != ListComparisonEnum.Identical)
                    {
                        string message = listComparisonEnum == ListComparisonEnum.ElementsDiffer
                        ? "Its template uses different data labels"
                        : "Its template has the same data labels, but in a different order";
                        string trimmedPath = sourceDDBFilePaths[i].Substring(rootFolderPath.Length + 1);
                        errorMessages.Warnings.Add(String.Format("'{0}' was skipped. {1}", trimmedPath, message));
                    }
                }).ConfigureAwait(true);
            }
            // After the merged database is constructed, set the Folder column to the current root folder
            if (!String.IsNullOrEmpty(rootFolderName))
            {
                destinationDDB.ExecuteNonQuery(Sql.Update + Constant.DBTables.FileData + Sql.Set + Constant.DatabaseColumn.Folder + Sql.Equal + Sql.Quote(rootFolderName));
            }

            // After the merged database is constructed, reset fields in the ImageSetTable to the defaults i.e., first row, selection all,
            if (!String.IsNullOrEmpty(rootFolderName))
            {
                destinationDDB.ExecuteNonQuery(Sql.Update + Constant.DBTables.ImageSet + Sql.Set + Constant.DatabaseColumn.MostRecentFileID + Sql.Equal + "1");
                destinationDDB.ExecuteNonQuery(Sql.Update + Constant.DBTables.ImageSet + Sql.Set + Constant.DatabaseColumn.Selection + Sql.Equal + ((int)FileSelectionEnum.All).ToString());
                destinationDDB.ExecuteNonQuery(Sql.Update + Constant.DBTables.ImageSet + Sql.Set + Constant.DatabaseColumn.SortTerms + Sql.Equal + Sql.Quote(Constant.DatabaseValues.DefaultSortTerms));
            }
            if (backupMade && (errorMessages.Errors.Any() || errorMessages.Warnings.Any()))
            {
                errorMessages.Warnings.Add(String.Format("Note: A backup of your original {0} can be found in the {1} folder", destinationDDBFileName, Constant.File.BackupFolder));
            }
            return(errorMessages);
        }
Esempio n. 22
0
        // Load the specified database template and then the associated images.
        // templateDatabasePath is the Fully qualified path to the template database file.
        // Returns true only if both the template and image database file are loaded (regardless of whether any images were loaded) , false otherwise
        private async Task <bool> TryOpenTemplateAndBeginLoadFoldersAsync(string templateDatabasePath)
        {
            // Try to create or open the template database
            // First, check the file path length and notify the user the template couldn't be loaded because its path is too long
            if (IsCondition.IsPathLengthTooLong(templateDatabasePath))
            {
                Mouse.OverrideCursor = null;
                Dialogs.TemplatePathTooLongDialog(this, templateDatabasePath);
                return(false);
            }
            // Second, check to see if we can actually open it.
            // As we can't have out parameters in an async method, we return the state and the desired templateDatabase as a tuple
            Tuple <bool, TemplateDatabase> tupleResult = await TemplateDatabase.TryCreateOrOpenAsync(templateDatabasePath).ConfigureAwait(true);

            this.templateDatabase = tupleResult.Item2;
            if (!tupleResult.Item1)
            {
                // Notify the user the template couldn't be loaded rather than silently doing nothing
                Mouse.OverrideCursor = null;
                Dialogs.TemplateFileNotLoadedAsCorruptDialog(this, templateDatabasePath);
                return(false);
            }

            // The .tdb templateDatabase should now be loaded
            // Try to get the image database file path
            // importImages will be true if its a new image database file, (meaning we should later ask the user to try to import some images)
            if (this.TrySelectDatabaseFile(templateDatabasePath, out string fileDatabaseFilePath, out bool importImages) == false)
            {
                // No image database file was selected
                return(false);
            }

            // Check the file path length of the .ddb file and notify the user the ddb couldn't be loaded because its path is too long
            if (IsCondition.IsPathLengthTooLong(fileDatabaseFilePath))
            {
                Mouse.OverrideCursor = null;
                Dialogs.DatabasePathTooLongDialog(this, fileDatabaseFilePath);
                return(false);
            }

            // Check the expected file path length of the backup files, and warn the user if backups may not be made because thier path is too long
            if (IsCondition.IsBackupPathLengthTooLong(templateDatabasePath) || IsCondition.IsBackupPathLengthTooLong(fileDatabaseFilePath))
            {
                Mouse.OverrideCursor = null;
                Dialogs.BackupPathTooLongDialog(this);
            }

            // Before fully loading an existing image database,
            // - upgrade the template tables if needed for backwards compatability (done automatically)
            // - compare the controls in the .tdb and .ddb template tables to see if there are any added or missing controls
            TemplateSyncResults templateSyncResults = new Database.TemplateSyncResults();
            bool backUpJustMade = false;

            using (FileDatabase fileDB = await FileDatabase.UpgradeDatabasesAndCompareTemplates(fileDatabaseFilePath, this.templateDatabase, templateSyncResults).ConfigureAwait(true))
            {
                // A file database was available to open
                if (fileDB != null)
                {
                    if (templateSyncResults.ControlSynchronizationErrors.Count > 0 || (templateSyncResults.ControlSynchronizationWarnings.Count > 0 && templateSyncResults.SyncRequiredAsDataLabelsDiffer == false))
                    {
                        // There are unresolvable syncronization issues. Report them now as we cannot use this template.
                        // Depending on the user response, we either abort Timelapse or use the template found in the ddb file
                        Mouse.OverrideCursor = null;
                        Dialog.TemplateSynchronization templatesNotCompatibleDialog;

                        templatesNotCompatibleDialog = new Dialog.TemplateSynchronization(templateSyncResults.ControlSynchronizationErrors, templateSyncResults.ControlSynchronizationWarnings, this);
                        bool?result = templatesNotCompatibleDialog.ShowDialog();
                        if (result == false)
                        {
                            // user indicates exiting rather than continuing.
                            Application.Current.Shutdown();
                            return(false);
                        }
                        else
                        {
                            templateSyncResults.UseTemplateDBTemplate           = templatesNotCompatibleDialog.UseNewTemplate;
                            templateSyncResults.SyncRequiredAsChoiceMenusDiffer = templateSyncResults.ControlSynchronizationWarnings.Count > 0;
                        }
                    }
                    else if (templateSyncResults.SyncRequiredAsDataLabelsDiffer)
                    {
                        // If there are any new or missing columns, report them now
                        // Depending on the user response, set the useTemplateDBTemplate to signal whether we should:
                        // - update the template and image data columns in the image database
                        // - use the old template
                        Mouse.OverrideCursor = null;
                        TemplateChangedAndUpdate templateChangedAndUpdate = new TemplateChangedAndUpdate(templateSyncResults, this);
                        bool?result1 = templateChangedAndUpdate.ShowDialog();
                        templateSyncResults.UseTemplateDBTemplate = result1 == true;
                    }
                    else if (templateSyncResults.SyncRequiredAsNonCriticalFieldsDiffer)
                    {
                        // Non critical differences in template, so these don't need reporting
                        templateSyncResults.UseTemplateDBTemplate = true;
                    }
                    backUpJustMade = fileDB.mostRecentBackup != DateTime.MinValue;
                }
                else if (File.Exists(fileDatabaseFilePath) == true)
                {
                    // The .ddb file (which exists) is for some reason unreadable.
                    // It is likely due to an empty or corrupt or otherwise unreadable database in the file.
                    // Raise an error message
                    bool isEmpty = File.Exists(fileDatabaseFilePath) && new FileInfo(fileDatabaseFilePath).Length == 0;
                    Mouse.OverrideCursor = null;
                    Dialogs.DatabaseFileNotLoadedAsCorruptDialog(this, fileDatabaseFilePath, isEmpty);
                    return(false);
                }
                ;
            }

            // At this point:
            // - for backwards compatability, all old databases will have been updated (if needed) to the current version standard
            // - we should have a valid template and image database loaded
            // - we know if the user wants to use the old or the new template
            // So lets load the database for real. The useTemplateDBTemplate signals whether to use the template stored in the DDB, or to use the TDB template.
            FileDatabase fileDatabase = await FileDatabase.CreateOrOpenAsync(fileDatabaseFilePath, this.templateDatabase, this.State.CustomSelectionTermCombiningOperator, templateSyncResults, backUpJustMade).ConfigureAwait(true);

            // The next test is to test and syncronize (if needed) the default values stored in the fileDB table schema to those stored in the template
            Dictionary <string, string> columndefaultdict = fileDatabase.SchemaGetColumnsAndDefaultValues(Constant.DBTables.FileData);

            char[] quote = { '\'' };
            foreach (KeyValuePair <string, string> pair in columndefaultdict)
            {
                ControlRow row = this.templateDatabase.GetControlFromTemplateTable(pair.Key);
                if (row != null && pair.Value.Trim(quote) != row.DefaultValue)
                {
                    // If even one default is different between the schema default and the template default, update the entire file table.
                    fileDatabase.UpgradeFileDBSchemaDefaultsFromTemplate();
                    break;
                }
            }
            // Check to see if the root folder stored in the database is the same as the actual root folder. If not, ask the user if it should be changed.
            this.CheckAndCorrectRootFolder(fileDatabase);

            // Check to see if there are any missing folders as specified by the relative paths. For those missing, ask the user to try to locate those folders.
            int missingFoldersCount = TimelapseWindow.GetMissingFolders(fileDatabase).Count;

            if (missingFoldersCount > 0)
            {
                Dialogs.MissingFoldersInformationDialog(this, missingFoldersCount);
            }

            // Generate and render the data entry controls, regardless of whether there are actually any files in the files database.
            this.DataHandler = new DataEntryHandler(fileDatabase);
            this.DataEntryControls.CreateControls(fileDatabase, this.DataHandler);
            this.SetUserInterfaceCallbacks();
            this.MarkableCanvas.DataEntryControls = this.DataEntryControls; // so the markable canvas can access the controls
            this.DataHandler.ThumbnailGrid        = this.MarkableCanvas.ThumbnailGrid;
            this.DataHandler.MarkableCanvas       = this.MarkableCanvas;

            this.Title = Constant.Defaults.MainWindowBaseTitle + " (" + Path.GetFileName(fileDatabase.FilePath) + ")";
            this.State.MostRecentImageSets.SetMostRecent(templateDatabasePath);
            this.RecentFileSets_Refresh();

            // Record the version number of the currently executing version of Timelapse only if its greater than the one already stored in the ImageSet Table.
            // This will indicate the latest timelapse version that is compatable with the database structure.
            string currentVersionNumberAsString = VersionChecks.GetTimelapseCurrentVersionNumber().ToString();

            if (VersionChecks.IsVersion1GreaterThanVersion2(currentVersionNumberAsString, this.DataHandler.FileDatabase.ImageSet.VersionCompatability))
            {
                this.DataHandler.FileDatabase.ImageSet.VersionCompatability = currentVersionNumberAsString;
                this.DataHandler.FileDatabase.UpdateSyncImageSetToDatabase();
            }

            // Create an index on RelativePath, File,and RelativePath/File if it doesn't already exist
            // This is really just a version check in case old databases don't have the index created,
            // Newer databases (from 2.2.4.4 onwards) will have these indexes created and updated whenever images are loaded or added for the first time.
            // If the index exists, this is a very cheap operation so there really is no need to do it by a version number check.
            this.DataHandler.FileDatabase.IndexCreateForFileAndRelativePathIfNotExists();

            // If this is a new image database, try to load images (if any) from the folder...
            if (importImages)
            {
                this.TryBeginImageFolderLoad(this.FolderPath, this.FolderPath);
            }
            else
            {
                await this.OnFolderLoadingCompleteAsync(false).ConfigureAwait(true);
            }
            return(true);
        }
Esempio n. 23
0
        private void HandleShipRequest(object sender, ShipMessage msg)
        {
            ShipPeer    peer    = sender as ShipPeer;
            ShipRequest request = msg as ShipRequest;

            JoinShipResponce responce = new JoinShipResponce();

            PlayerShip shipToLink = null;

            if (peer.LinkedShip != null)
            {
                shipToLink = peer.LinkedShip;
            }
            else
            {
                if (request.Join)
                {
                    shipToLink = PlayerShips.Find((x) => x.LinkedShip.GUID == request.RequestedShipID);
                    if (shipToLink == null || shipToLink.Locked && shipToLink.Password != request.Password)
                    {
                        responce.Error   = true;
                        responce.Message = "NoShipToJoin";
                        peer.Send(responce);
                        return; // nope!
                    }
                    else
                    {
                        if (!shipToLink.ControlingPeers.Contains(peer))
                        {
                            shipToLink.ControlingPeers.Add(peer);
                        }

                        peer.LinkedShip = shipToLink;
                    }
                }
            }

            if (shipToLink == null)
            {
                var template = TemplateDatabase.GetTemplate(request.RequestedShipID);
                int shipID   = ActiveScenario.SpawnPlayableShip(peer.Connection.RemoteUniqueIdentifier.ToString(), template == null ? string.Empty : template.Name, request.Name);

                var ship = ZoneManager.GetFirstMatch(new PlayableShipFinder(shipID)) as Ship;

                shipToLink            = new PlayerShip();
                shipToLink.LinkedShip = ship;
                shipToLink.ControlingPeers.Add(peer);
                shipToLink.Locked   = request.Password != string.Empty;
                shipToLink.Password = request.Password;

                peer.LinkedShip = shipToLink;
                PlayerShips.Add(shipToLink);
            }

            // send back the responce with the ship they are on
            responce.Error   = false;
            responce.Message = shipToLink.LinkedShip.Name;
            responce.ShipID  = shipToLink.LinkedShip.GUID;
            peer.Send(responce);

            // send an info and status update
        }