/// <summary>
 /// Opens the instance of a database, and loads it location to memory.
 /// </summary>
 /// <param name="aDB">Database to open</param>
 /// <returns>True if successful. False if a failure detected.</returns>
 private bool OpenDataBaseFile(Databases aDB)
 {
     bool lReturnValue = false;
     try 
     {
         switch (aDB)
         {
             case Databases.dCONFIG:
                 gSQLIteCon = new SQLiteConnection(@"Data Source=C:\POS\Data\posconfig.posdb");
                 gSQLIteCon.Open();
                 lReturnValue = true;
                 break;
             case Databases.dITEMS:
                 gSQLIteCon = new SQLiteConnection(@"Data Source=C:\POS\Data\posdb.posdb");
                 gSQLIteCon.Open();
                 lReturnValue = true;
                 break;
             default:
                 lReturnValue = false;
                 AppLog.Log("Unable to open requested database" + aDB.ToString(), false);
                 break;
         }
     }
     catch (SystemException ex)
     {
         AppLog.Log(ex.Message.ToString(), false);
     }
     return lReturnValue;
 }
示例#2
0
        public DBManager(Databases db)
        {
            switch (ConType)
            {
                case SqlEngine.MsSql:
                    dbFactory = DbProviderFactories.GetFactory("System.Data.SqlClient");
                    break;

                case SqlEngine.MySql:
                    dbFactory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
                    break;

                default:
                    throw new ArgumentOutOfRangeException("Database type isn't within range.");
            }

            switch (db)
            {
                case Databases.Auth:
                    dbConString = AuthConString;
                    break;
                case Databases.Game:
                    dbConString = GameConString;
                    break;
                case Databases.User:
                    dbConString = UserConString;
                    break;
                default:
                    ConsoleUtils.ShowError("Invalid database type.");
                    break;
            }

            targetDb = db;

            if (dbFactory != null)
            {
                using (DbConnection dbCon = dbFactory.CreateConnection())
                {
                    dbCon.ConnectionString = dbConString;

                    dbBuilder = dbFactory.CreateCommandBuilder();

                    try
                    {
                        dbCon.Open();
                        using (DataTable tbl = dbCon.GetSchema(DbMetaDataCollectionNames.DataSourceInformation))
                        {
                            dbParameterMarkerFormat = tbl.Rows[0][DbMetaDataColumnNames.ParameterMarkerFormat] as string;
                        }
                        dbCon.Close();

                        if (!string.IsNullOrEmpty(dbParameterMarkerFormat)) { dbParameterMarkerFormat = "{0}"; }

                        ConsoleUtils.ShowDebug("DBManager Instance Initialized.");
                    }
                    catch (Exception ex) { ConsoleUtils.ShowError(ex.Message); }
                }
            }
        }
 public ProfileData Bind(Databases.io_contacts.Views.DataContracts.Profiles.GetUserProfile.UserProfile userProfile)
 {
     _entityContactKey = userProfile.EntityContactKey;
     _entityLocationName = userProfile.EntityLocationName;
     _firstName = userProfile.FirstName;
     _lastName = userProfile.LastName;
     _title = userProfile.Title;
     _email = userProfile.Email;
     return this;
 }
        public static bool IsSupport(ApplicationSerers appServer,
                                     Databases database)
        {
            switch (appServer)
            {
                case ApplicationSerers.GlassFish:
                    return true;

                case ApplicationSerers.Tomcat:
                    return database == Databases.MySQL;

                case ApplicationSerers.JBoss:
                    return database == Databases.DB2 || database == Databases.PostgreSQL;

                default:
                    return false;
            }
        }
示例#5
0
        public static void Init()
        {
            var db = new DbConnection(Config.GetDatabasePath(), DbProtection.GetDatabaseKey());

            CryptoKeys = new CryptoKeys { Db = db };
            Databases = new Databases { Db = db };
            DatabasesEntries = new DatabasesEntries { Db = db };
            DatabasesEntriesData = new DatabasesEntriesData { Db = db };
            DatabasesEntriesDataSync = new DatabasesEntriesDataSync { Db = db };
            DatabasesEntriesDataVersions = new DatabasesEntriesDataVersions { Db = db };
            DatabasesEntries = new DatabasesEntries { Db = db };
            DatabasesGroups = new DatabasesGroups { Db = db };
            DatabasesGroupsMeta = new DatabasesGroupsMeta { Db = db };
            DatabasesGroupsMetaSync = new DatabasesGroupsMetaSync { Db = db };
            DatabasesGroupsMetaVersions = new DatabasesGroupsMetaVersions { Db = db };
            DatabasesMeta = new DatabasesMeta { Db = db };
            DatabasesMetaSync = new DatabasesMetaSync { Db = db };
            DatabasesMetaVersions = new DatabasesMetaVersions { Db = db };
            ServerAccounts = new ServerAccounts { Db = db };
            ServerManagementAccounts = new ServerManagementAccounts { Db = db };
        }
示例#6
0
    public void ChangeToArmyMode(bool calledByChangeModeOrderProcessor = false)
    {
        if (calledByChangeModeOrderProcessor && this.OnPrepareToConvertToArmyDelegate != null)
        {
            this.OnPrepareToConvertToArmyDelegate();
        }
        WorldPosition worldPosition = this.KaijuGarrison.WorldPosition;

        this.LeaveCurrentRegion();
        SimulationDescriptor value = this.SimulationDescriptorDatabase.GetValue(Kaiju.KaijuGarrisonModeDescriptor);

        if (value != null)
        {
            base.RemoveDescriptor(value);
        }
        SimulationDescriptor value2 = this.SimulationDescriptorDatabase.GetValue(Kaiju.KaijuArmyModeDescriptor);

        if (value2 != null)
        {
            base.AddDescriptor(value2, false);
        }
        this.Refresh(false);
        this.KaijuArmy.ClearAllUnits();
        this.TransferUnitsToArmy();
        this.KaijuArmy.Refresh(false);
        this.KaijuGarrison.Refresh(false);
        this.GameEntityRepositoryService.Unregister(this.KaijuGarrison);
        this.Empire.RemoveChild(this.KaijuGarrison);
        this.Empire.Refresh(false);
        this.KaijuArmy.SetWorldPosition(WorldPosition.Invalid);
        this.KaijuArmy.MoveTo(worldPosition);
        this.GameEntityRepositoryService.Register(this.KaijuArmy);
        this.Empire.AddChild(this.KaijuArmy);
        this.KaijuArmy.Empire = this.Empire;
        this.KaijuArmy.Refresh(false);
        this.KaijuGarrison.Refresh(false);
        if (this.MajorEmpire != null && !this.MajorEmpire.IsEliminated && this.MajorEmpire.GetAgency <DepartmentOfDefense>().TechnologyDefinitionShipState == DepartmentOfScience.ConstructibleElement.State.Researched)
        {
            IDatabase <SimulationDescriptor> database = Databases.GetDatabase <SimulationDescriptor>(false);
            SimulationDescriptor             descriptor;
            if (database != null && database.TryGetValue(PathfindingContext.MovementCapacitySailDescriptor, out descriptor))
            {
                if (!this.KaijuArmy.SimulationObject.Tags.Contains(PathfindingContext.MovementCapacitySailDescriptor))
                {
                    this.KaijuArmy.AddDescriptor(descriptor, true);
                }
                foreach (Unit unit in this.KaijuArmy.Units)
                {
                    if (!unit.SimulationObject.Tags.Contains(PathfindingContext.MovementCapacitySailDescriptor))
                    {
                        unit.AddDescriptor(descriptor, true);
                    }
                }
            }
        }
        this.KaijuArmy.Refresh(false);
        this.ShowKaijuArmyInMap();
        this.KaijuGarrison.OnConvertedToArmy();
        this.KaijuArmy.OnConvertedToArmy();
        this.ComputeNextTurnToSpawnUnits(false);
        if (this.OnConvertedToArmyDelegate != null)
        {
            this.OnConvertedToArmyDelegate();
        }
        this.CallRefreshProvidedRegionEffects();
        this.KaijuArmy.ForceWorldOrientation(this.WorldOrientation);
    }
        public void SetCommand()
        {
            CreateDatabase = new RelayCommand(() =>
            {
                var vm = new NewDatabaseSettingsViewModel();
                MessengerInstance.Send(new MessageBase(vm, "NewDbSettingsWindowOpen"));

                if (string.IsNullOrEmpty(vm.Path))
                {
                    return;
                }

                var db = new DbViewModel();
                db.CreateDatabase(vm.Path, vm.Type, vm.CharSet);
                db.LoadDatabase(vm.Path);
                Databases.Add(db);
                _history.DataAdd(vm.Path);
            });

            LoadDatabase = new RelayCommand <string>(async(path) =>
            {
                if (string.IsNullOrEmpty(path))
                {
                    return;
                }
                if (!File.Exists(path))
                {
                    return;
                }
                var db     = new DbViewModel();
                var isLoad = await Task.Run(() =>
                {
                    return(db.LoadDatabase(path));
                });
                if (isLoad)
                {
                    Databases.Add(db);
                    _history.DataAdd(path);
                }
            });

            ExecuteQuery = new RelayCommand(async() =>
            {
                if (CurrentDatabase == null || !CurrentDatabase.CanExecute())
                {
                    return;
                }
                if (TagSelectedValue.IsNewResult && 0 < Datasource[0].Result.Count)
                {
                    Datasource[0].Pined = true;
                }
                var QueryResult = Datasource[0];
                QueryResult.Result.Clear();
                await Task.Run(() =>
                {
                    var inf = new QueryInfo {
                        ShowExecutePlan = TagSelectedValue.IsShowExecutionPlan
                    };
                    QueryResult.GetExecuteResult(inf, CurrentDatabase.ConnectionString, TagSelectedValue.Query);
                });
            });

            DropFile = new RelayCommand <string>((string path) =>
            {
                InputPath = path;
                RaisePropertyChanged(nameof(InputPath));
            });

            DbListDropFile = new RelayCommand <string>((string path) =>
            {
                LoadDatabase.Execute(path);
            });

            SetSqlTemplate = new RelayCommand <SqlKind>((SqlKind sqlKind) =>
            {
                TagSelectedValue.Query = CreateSqlSentence(SelectedTableItem, sqlKind);
                RaisePropertyChanged(nameof(Queries));
            });

            ExecLimitedSql = new RelayCommand <string>((count) =>
            {
                TagSelectedValue.Query = CreateSqlSentence(SelectedTableItem, SqlKind.Select, int.Parse(count));
                RaisePropertyChanged(nameof(Queries));
                ExecuteQuery.Execute(null);
            });

            ExecSqlTemplate = new RelayCommand <SqlKind>((SqlKind sqlKind) =>
            {
                SetSqlTemplate.Execute(sqlKind);
                ExecuteQuery.Execute(null);
            });

            ShutdownDatabase = new RelayCommand(() => { Databases.Remove(CurrentDatabase); });

            ChangeConfig = new RelayCommand(() =>
            {
                if (CurrentDatabase == null)
                {
                    return;
                }
                var vm = new ConnectionSettingsViewModel(CurrentDatabase.DbInfo);
                MessengerInstance.Send(new MessageBase(vm, "WindowOpen"));
            });

            ShowEntity = new RelayCommand(() =>
            {
                if (CurrentDatabase == null)
                {
                    return;
                }
                var vm = new EntityRelationshipViewModel(CurrentDatabase);
                MessengerInstance.Send(new MessageBase(vm, "EintityWindowOpen"));
            });

            AddTab = new RelayCommand(() =>
            {
                TagSelectedValue.Header = $"Query{Queries.Count}";
                Queries.Add(QueryTabViewModel.GetNewInstance());
                RaisePropertyChanged(nameof(Queries));
            });

            DeleteTabItem = new RelayCommand(() =>
            {
                var item         = TagSelectedValue;
                var idx          = Queries.IndexOf(item);
                TagSelectedIndex = idx - 1;
                RaisePropertyChanged(nameof(TagSelectedIndex));
                Queries.Remove(item);
            });

            LoadHistry = new RelayCommand(() => _history.LoadData(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)));

            SaveHistry = new RelayCommand(() => _history.SaveData(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)));

            OpenGitPage = new RelayCommand(() => System.Diagnostics.Process.Start("https://github.com/degarashi0913/FAManagementStudio"));

            PinedCommand = new RelayCommand(() =>
            {
                Datasource[0].Header = $"Pin{Datasource.Count}";
                Datasource.Insert(0, new QueryResultViewModel("Result"));
                SelectedResultIndex = 0;
                RaisePropertyChanged(nameof(SelectedResultIndex));
            }, () => 0 < Datasource[0].Result.Count);

            ReleasePinCommand = new RelayCommand <QueryResultViewModel>((data) =>
            {
                Datasource.Remove(data);
            });

            SetSqlDataTemplate = new RelayCommand <string>((s) =>
            {
                var table  = GetTreeViewTableName(CurrentDatabase, SelectedTableItem);
                var result = "";
                if (s == "table")
                {
                    result = table.GetDdl(CurrentDatabase);
                }
                else if (s == "insert")
                {
                    if (table is TableViewViewModel)
                    {
                        return;
                    }
                    var colums           = table.Colums.Select(x => x.ColumName).ToArray();
                    var escapedColumsStr = string.Join(", ", colums.Select(x => EscapeKeyWord(x)).ToArray());

                    var insertTemplate = $"insert into {table.TableName} ({escapedColumsStr})";

                    var qry = new QueryInfo();
                    var res = qry.ExecuteQuery(CurrentDatabase.ConnectionString, CreateSelectStatement(table.TableName, colums, 0)).First();

                    var sb = new StringBuilder();

                    foreach (DataRow row in res.View.Rows)
                    {
                        sb.Append(insertTemplate + " values(");
                        sb.Append(string.Join(", ", row.ItemArray.Select(x => x.GetType() == typeof(string) ? $"\'{x}\'" : $"{x}").ToArray()));
                        sb.AppendLine(");");
                    }
                    result = sb.ToString();
                }

                var idx            = Queries.IndexOf(TagSelectedValue);
                Queries[idx].Query = result;
                RaisePropertyChanged(nameof(Queries));
            });

            ShowPathSettings = new RelayCommand(() =>
            {
                var vm = new BasePathSettingsViewModel(QueryProjects);
                MessengerInstance.Send(new MessageBase(vm, "BasePathSettingsWindowOpen"));
            });

            ProjectItemOpen = new RelayCommand <object>((obj) =>
            {
                var item = obj as QueryProjectFileViewModel;
                if (item == null)
                {
                    return;
                }
                var idx = Queries.IndexOf(TagSelectedValue);
                try
                {
                    Queries[idx].Header = Path.GetFileNameWithoutExtension(item.FullPath);
                    Queries[idx].Query  = Queries[idx].FileLoad(item.FullPath, Encoding.UTF8);
                }
                catch (IOException) { }
            });
            ProjectItemDrop = new RelayCommand <string>((string path) =>
            {
                QueryProjects.Add(QueryProjectViewModel.GetData(path).First());
                AppSettingsManager.QueryProjectBasePaths.Add(path);
            });
        }
示例#8
0
 public CodeParser(Databases dtbs, IndentationManager oldIndentation)
 {
     fdtb = dtbs.fdtb;
     cdtb = dtbs.cdtb;
     sdtb = dtbs.sdtb;
     indent = oldIndentation;
     block = new CodeBlock();
 }
示例#9
0
        public async Task SkipExportingTheServerWideExternalReplication2()
        {
            var backupPath = NewDataPath(suffix: "BackupFolder");

            using (var store = GetDocumentStore())
            {
                var putConfiguration1 = new ServerWideExternalReplication
                {
                    Name     = "1",
                    Disabled = true,
                    TopologyDiscoveryUrls = new[] { store.Urls.First() }
                };

                var putConfiguration2 = new ServerWideExternalReplication
                {
                    Name     = "2",
                    Disabled = true,
                    TopologyDiscoveryUrls = new[] { store.Urls.First() }
                };

                await store.Maintenance.Server.SendAsync(new PutServerWideExternalReplicationOperation(putConfiguration1));

                await store.Maintenance.Server.SendAsync(new PutServerWideExternalReplicationOperation(putConfiguration2));

                var dbName = $"db/{Guid.NewGuid()}";
                var csName = $"cs/{Guid.NewGuid()}";

                var connectionString = new RavenConnectionString
                {
                    Name     = csName,
                    Database = dbName,
                    TopologyDiscoveryUrls = new[] { "http://127.0.0.1:12345" }
                };

                var result = await store.Maintenance.SendAsync(new PutConnectionStringOperation <RavenConnectionString>(connectionString));

                Assert.NotNull(result.RaftCommandIndex);

                await store.Maintenance.SendAsync(new UpdateExternalReplicationOperation(new ExternalReplication(dbName, csName)
                {
                    Disabled = true
                }));

                var databaseRecord = await store.Maintenance.Server.SendAsync(new GetDatabaseRecordOperation(store.Database));

                Assert.Equal(3, databaseRecord.ExternalReplications.Count);

                var serverWideBackupConfiguration = new ServerWideBackupConfiguration
                {
                    Disabled                   = false,
                    FullBackupFrequency        = "0 2 * * 0",
                    IncrementalBackupFrequency = "0 2 * * 1",
                    LocalSettings              = new LocalSettings
                    {
                        FolderPath = backupPath
                    }
                };

                await store.Maintenance.Server.SendAsync(new PutServerWideBackupConfigurationOperation(serverWideBackupConfiguration));

                var record = await store.Maintenance.Server.SendAsync(new GetDatabaseRecordOperation(store.Database));

                var backup       = record.PeriodicBackups.First();
                var backupTaskId = backup.TaskId;

                await store.Maintenance.SendAsync(new StartBackupOperation(true, backupTaskId));

                string backupDirectory = null;
                var    value           = WaitForValue(() =>
                {
                    var status      = store.Maintenance.Send(new GetPeriodicBackupStatusOperation(backupTaskId)).Status;
                    backupDirectory = status?.LocalBackup.BackupDirectory;
                    return(status?.LastEtag);
                }, 0);

                Assert.Equal(0, value);

                var files = Directory.GetFiles(backupDirectory)
                            .Where(BackupUtils.IsBackupFile)
                            .OrderBackups()
                            .ToArray();

                var databaseName  = GetDatabaseName() + "restore";
                var restoreConfig = new RestoreBackupConfiguration
                {
                    BackupLocation        = backupDirectory,
                    DatabaseName          = databaseName,
                    LastFileNameToRestore = files.OrderBackups().Last()
                };

                var restoreOperation = new RestoreBackupOperation(restoreConfig);
                store.Maintenance.Server.Send(restoreOperation)
                .WaitForCompletion(TimeSpan.FromSeconds(30));

                // new server should have only 0 external replications
                var server = GetNewServer();

                using (Databases.EnsureDatabaseDeletion(databaseName, store))
                    using (var store2 = GetDocumentStore(new Options
                    {
                        CreateDatabase = false,
                        ModifyDatabaseName = s => databaseName,
                        Server = server
                    }))
                    {
                        store2.Maintenance.Server.Send(restoreOperation)
                        .WaitForCompletion(TimeSpan.FromSeconds(30));

                        var record2 = await store2.Maintenance.Server.SendAsync(new GetDatabaseRecordOperation(databaseName));

                        Assert.Equal(1, record2.ExternalReplications.Count);
                    }
            }
        }
示例#10
0
 public Writer(Databases dtbs)
 {
     cdtb = dtbs.cdtb;
     fdtb = cdtb.functionDatabase;
     sdtb = dtbs.sdtb;
     this.dtbs = dtbs;
 }
示例#11
0
        public async Task ReplicateRevisionTombstones()
        {
            var revisionsAgeLimit = TimeSpan.FromSeconds(10);

            Action <RevisionsConfiguration> modifyConfiguration = configuration =>
                                                                  configuration.Collections["Users"] = new RevisionsCollectionConfiguration
            {
                Disabled = false,
                MinimumRevisionAgeToKeep = revisionsAgeLimit
            };

            using (var store1 = GetDocumentStore())
                using (var store2 = GetDocumentStore())
                {
                    //setup revisions on both stores and setup replication
                    await RevisionsHelper.SetupRevisions(Server.ServerStore, store1.Database, modifyConfiguration);

                    await RevisionsHelper.SetupRevisions(Server.ServerStore, store2.Database, modifyConfiguration);

                    await SetupReplicationAsync(store1, store2);

                    // create some revisions on store1
                    using (var session = store1.OpenAsyncSession())
                    {
                        await session.StoreAsync(new User
                        {
                            Name = "Aviv"
                        }, "users/1-A");

                        await session.SaveChangesAsync();
                    }

                    for (int i = 2; i <= 10; i++)
                    {
                        using (var session = store1.OpenAsyncSession())
                        {
                            var user = await session.LoadAsync <User>("users/1-A");

                            user.Name = "Aviv" + i;
                            await session.SaveChangesAsync();
                        }
                    }

                    // wait for replication
                    WaitForMarker(store1, store2);

                    // wait until revisions are expired
                    await Task.Delay(revisionsAgeLimit);

                    // modify document
                    using (var session = store1.OpenAsyncSession())
                    {
                        var user = await session.LoadAsync <User>("users/1-A");

                        user.Name = "Grisha";
                        await session.SaveChangesAsync();
                    }

                    WaitForMarker(store1, store2);

                    // expired revisions should be deleted
                    // assert that both stores have 10 revision tombstones

                    foreach (var store in new[] { store1, store2 })
                    {
                        var documentDatabase = await Databases.GetDocumentDatabaseInstanceFor(store);

                        using (documentDatabase.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext ctx))
                            using (ctx.OpenReadTransaction())
                            {
                                var tombstones = documentDatabase.DocumentsStorage.GetTombstonesFrom(ctx, 0, 0, int.MaxValue).ToList();
                                Assert.Equal(10, tombstones.Count);

                                foreach (var tombstone in tombstones)
                                {
                                    Assert.Equal(Tombstone.TombstoneType.Revision, tombstone.Type);
                                }
                            }
                    }
                }
        }
示例#12
0
    public IEnumerator WriteConfigurationFile()
    {
        global::WorldGeneratorConfiguration worldGeneratorConfiguration = new global::WorldGeneratorConfiguration();

        Amplitude.Unity.Session.Session session = null;
        ISessionService service = Services.GetService <ISessionService>();

        if (service != null)
        {
            session = service.Session;
        }
        IDatabase <WorldGeneratorOptionDefinition> database = Databases.GetDatabase <WorldGeneratorOptionDefinition>(false);

        if (database != null)
        {
            WorldGenerator.< > c__DisplayClass0_0 CS$ < > 8__locals1 = new WorldGenerator.< > c__DisplayClass0_0();
            System.Random random = new System.Random();
            WorldGeneratorOptionDefinition worldGeneratorOptionDefinition;
            if (session.GetLobbyData <string>("SeedChoice", null) == "User" && database.TryGetValue("SeedNumber", out worldGeneratorOptionDefinition))
            {
                Amplitude.Diagnostics.Assert(worldGeneratorOptionDefinition.ItemDefinitions.Length == 1);
                Amplitude.Diagnostics.Assert(worldGeneratorOptionDefinition.ItemDefinitions[0].KeyValuePairs.Length == 1);
                int seed;
                if (int.TryParse(worldGeneratorOptionDefinition.ItemDefinitions[0].KeyValuePairs[0].Value, out seed))
                {
                    random = new System.Random(seed);
                }
            }
            Dictionary <OptionDefinition, OptionDefinition.ItemDefinition> dictionary = new Dictionary <OptionDefinition, OptionDefinition.ItemDefinition>();
            WorldGenerator.< > c__DisplayClass0_0 CS$ < > 8__locals2 = CS$ < > 8__locals1;
            OptionDefinition[] values = database.GetValues();
            CS$ < > 8__locals2.optionDefinitions = values;
            for (int i = 0; i < CS$ < > 8__locals1.optionDefinitions.Length; i++)
            {
                if (CS$ < > 8__locals1.optionDefinitions[i] is WorldGeneratorOptionDefinition)
                {
                    OptionDefinition.ItemDefinition itemDefinition = null;
                    if (session != null)
                    {
                        string itemName = session.GetLobbyData <string>(CS$ < > 8__locals1.optionDefinitions[i].Name, CS$ < > 8__locals1.optionDefinitions[i].DefaultName);
                        if (!string.IsNullOrEmpty(itemName))
                        {
                            itemDefinition = Array.Find <OptionDefinition.ItemDefinition>(CS$ < > 8__locals1.optionDefinitions[i].ItemDefinitions, (OptionDefinition.ItemDefinition iterator) => iterator.Name == itemName);
                            if (itemName == "Random")
                            {
                                OptionDefinition.ItemDefinition[] array = (from iterator in CS$ < > 8__locals1.optionDefinitions[i].ItemDefinitions
                                                                           where iterator.Name != "Custom" && iterator.Name != "Random"
                                                                           select iterator).ToArray <OptionDefinition.ItemDefinition>();
                                if (array.Length != 0)
                                {
                                    List <OptionDefinition.ItemDefinition> list = new List <OptionDefinition.ItemDefinition>();
                                    list.AddRange(array);
                                    for (int j = array.Length - 1; j >= 0; j--)
                                    {
                                        if (array[j].OptionDefinitionConstraints != null)
                                        {
                                            bool flag = true;
                                            foreach (OptionDefinitionConstraint optionDefinitionConstraint in from iterator in array[j].OptionDefinitionConstraints
                                                     where iterator.Type == OptionDefinitionConstraintType.Conditional
                                                     select iterator)
                                            {
                                                if (string.IsNullOrEmpty(optionDefinitionConstraint.OptionName))
                                                {
                                                    flag = false;
                                                    break;
                                                }
                                                string lobbyData = session.GetLobbyData <string>(optionDefinitionConstraint.OptionName, null);
                                                if (string.IsNullOrEmpty(lobbyData))
                                                {
                                                    Amplitude.Diagnostics.LogWarning("Unhandled constraint on option '{0}' from option definition '{1}', item '{2}'.", new object[]
                                                    {
                                                        optionDefinitionConstraint.OptionName,
                                                        CS$ < > 8__locals1.optionDefinitions[i].Name,
                                                        itemDefinition.Name
                                                    });
示例#13
0
 public bool DatabaseExists(string databaseName)
 {
     return(Databases.Any(d => d.Name.Equals(databaseName, StringComparison.InvariantCultureIgnoreCase)));
 }
        private void SaveInfo_Click(object sender, EventArgs e)
        {
            #region 保存信息
            if (this.CheckCookie())
            {
                GeneralConfigInfo configInfo = GeneralConfigs.GetConfig();
                Hashtable         HT         = new Hashtable();
                HT.Add("最大在线人数", maxonlines.Text);
                HT.Add("搜索时间限制", searchctrl.Text);
                foreach (DictionaryEntry de in HT)
                {
                    if (!Utils.IsInt(de.Value.ToString()))
                    {
                        base.RegisterStartupScript("", "<script>alert('输入错误:" + de.Key.ToString().Trim() + ",只能是0或者正整数');window.location.href='global_safecontrol.aspx';</script>");
                        return;
                    }
                }

                if (fulltextsearch.SelectedValue == "1")
                {
                    string msg = "";
                    configInfo.Fulltextsearch = Databases.TestFullTextIndex(ref msg);
                }
                else
                {
                    configInfo.Fulltextsearch = 0;
                }

                configInfo.Nocacheheaders        = Convert.ToInt16(nocacheheaders.SelectedValue);
                configInfo.Maxonlines            = Convert.ToInt32(maxonlines.Text);
                configInfo.Searchctrl            = Convert.ToInt32(searchctrl.Text);
                configInfo.Statscachelife        = Convert.ToInt16(statscachelife.Text);
                configInfo.Guestcachepagetimeout = Convert.ToInt16(guestcachepagetimeout.Text);
                configInfo.Oltimespan            = Convert.ToInt16(oltimespan.Text);
                configInfo.Topiccachemark        = Convert.ToInt16(topiccachemark.Text);
                if (showauthorstatusinpost.SelectedValue == "1")
                {
                    configInfo.Onlinetimeout = 0 - Convert.ToInt32(onlinetimeout.Text);
                }
                else
                {
                    configInfo.Onlinetimeout = TypeConverter.StrToInt(onlinetimeout.Text);
                }
                //configInfo.Secques = Convert.ToInt32(secques.SelectedValue);
                //configInfo.Postinterval = Convert.ToInt32(postinterval.Text);
                //configInfo.Maxspm = Convert.ToInt32(maxspm.Text);



                GeneralConfigs.Serialiaze(configInfo, Server.MapPath("../../config/general.config"));
                Urls.config = configInfo;
                if (configInfo.Aspxrewrite == 1)
                {
                    AdminForums.SetForumsPathList(true, configInfo.Extname);
                }
                else
                {
                    AdminForums.SetForumsPathList(false, configInfo.Extname);
                }
                Discuz.Cache.DNTCache.GetCacheService().RemoveObject("/Forum/ForumList");
                Discuz.Forum.TopicStats.SetQueueCount();
                Caches.ReSetConfig();
                AdminVistLogs.InsertLog(this.userid, this.username, this.usergroupid, this.grouptitle, this.ip, "基本设置", "");
                base.RegisterStartupScript("PAGE", "window.location.href='global_siteoptimization.aspx';");
            }
            #endregion
        }
示例#15
0
 public BlockParser(Databases dtbs, IndentationManager manager)
 {
     started = false;
     this.dtbs = dtbs;
     dtb = dtbs.cdtb;
     indent = manager;
 }
示例#16
0
    protected override State Execute(AIBehaviorTree aiBehaviorTree, params object[] parameters)
    {
        Army army;

        if (base.GetArmyUnlessLocked(aiBehaviorTree, "$Army", out army) != AIArmyMission.AIArmyMissionErrorCode.None)
        {
            return(State.Failure);
        }
        if (this.currentTicket != null)
        {
            if (!this.currentTicket.Raised)
            {
                return(State.Running);
            }
            bool flag = this.currentTicket.PostOrderResponse == PostOrderResponse.PreprocessHasFailed || this.currentTicket.PostOrderResponse == PostOrderResponse.AuthenticationHasFailed;
            this.currentTicket = null;
            if (flag)
            {
                aiBehaviorTree.ErrorCode = 1;
                return(State.Failure);
            }
            return(State.Success);
        }
        else
        {
            if (!aiBehaviorTree.Variables.ContainsKey(this.DestinationVarName))
            {
                aiBehaviorTree.LogError("{0} not set", new object[]
                {
                    this.DestinationVarName
                });
                return(State.Failure);
            }
            City       city       = (City)aiBehaviorTree.Variables[this.DestinationVarName];
            ArmyAction armyAction = null;
            if (city != null)
            {
                if (!ELCPUtilities.CanTeleportToCity(city, army, this.worldPositionningService.GetRegion(army.WorldPosition), this.worldPositionningService, this.encounterRepositoryService))
                {
                    return(State.Failure);
                }
                List <ArmyAction>   list  = new List <ArmyAction>(new List <ArmyAction>(Databases.GetDatabase <ArmyAction>(false).GetValues()).FindAll((ArmyAction match) => match is ArmyAction_Teleport));
                List <StaticString> list2 = new List <StaticString>();
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].CanExecute(army, ref list2, new object[0]))
                    {
                        armyAction = list[i];
                        break;
                    }
                }
                if (armyAction != null)
                {
                    armyAction.Execute(army, aiBehaviorTree.AICommander.Empire.PlayerControllers.AI, out this.currentTicket, null, new object[]
                    {
                        city
                    });
                    return(State.Running);
                }
            }
            Diagnostics.LogError("ELCP: AIBehaviorTreeNode_Action_TeleportToCity failed for {0}/{1} {5} -> {6}, {2} {3} {4}", new object[]
            {
                army.LocalizedName,
                army.Empire,
                army.GetPropertyBaseValue(SimulationProperties.Movement),
                city != null,
                armyAction != null,
                army.WorldPosition,
                (city != null) ? city.WorldPosition.ToString() : "null"
            });
            return(State.Failure);
        }
    }
示例#17
0
        /// <summary>
        /// Connect to SQL Server and fill in the GUI to provide options for the check
        /// </summary>
        public bool Connect()
        {
            Databases.Clear();
            ConnectionStringBuilder.ConnectTimeout = 10;
            using (var cn = new SqlConnection(ConnectionStringBuilder.ConnectionString))
            {
                try
                {
                    cn.Open();
                }
                catch (SqlException)
                {
                    MessageBox.Show(App.Localized["msgErrorNotConnected"], App.Localized["msgNotConnected"], MessageBoxButton.OK, MessageBoxImage.Error);
                    return(false);
                }

                var qry = $"SELECT Name, compatibility_level FROM sys.databases WHERE database_id > 4 ORDER BY name OPTION (RECOMPILE); {_infos.Query}";
                using (var cmd = new SqlCommand(qry, cn))
                {
                    SqlDataReader rd;
                    try
                    {
                        rd = cmd.ExecuteReader();
                    }
                    catch (SqlException e)
                    {
                        var msg = $"{App.Localized["msgSqlErrorInQuery"]} ({qry}).\n{App.Localized["msgError"]} {e.Number} : {e.Message}";
                        MessageBox.Show(msg, App.Localized["msgSqlError"], MessageBoxButton.OK, MessageBoxImage.Error);
                        SimpleLog.Error(msg);
                        return(false);
                    }
                    while (rd.Read())
                    {
                        Databases.Add(new SqlServer.Database()
                        {
                            Checked            = false,
                            Name               = rd.GetString(0),
                            CompatibilityLevel = (SqlServer.DatabaseCompatibilityLevel)rd.GetByte(1) // danger ! TryParse ??
                        });
                    }

                    rd.NextResult();
                    _infos.Set(rd);
                    _statsCleared = _infos.StartTime;
                    rd.Close();
                    ServerInfos = $"SQL Server version {_infos.ProductVersion}, Edition {_infos.Edition}";
                    OnPropertyChanged("ServerInfos");
                }
                cn.Close();
                // OutputPath
                OutputPath = $@"{_outputRoot}{ConnectionStringBuilder.DataSource.Replace("\\", ".")}\";
                Directory.CreateDirectory(OutputPath);

                // we need to change the output path of the manager
                _ce.OutputPath = OutputPath;

                SimpleLog.SetLogFile(logDir: OutputPath, check: false);
                SimpleLog.Info(_infos.ToString());

                OnPropertyChanged("Databases");

                // status
                StatusText = $"{App.Localized["msgConnectedTo"]} {ConnectionStringBuilder.DataSource} ({_infos.MachineName}), SQL Server {_infos.ProductVersion} {_infos.Edition}";
                OnPropertyChanged("StatusText");
                IsConnected = true;
                return(true);
            }
        }
示例#18
0
        private void setupPaths_Data(string pathRadiusIV)
        {
            if (!isDataStructure(pathRadiusIV))
            {
                throw new ArgumentException("Bone provided is not a radius for a data");
            }

            _db = Databases.DATA;

            string fname = Path.GetFileNameWithoutExtension(pathRadiusIV);
            string ext   = Path.GetExtension(pathRadiusIV);

            _ivFolderPath     = Path.GetDirectoryName(pathRadiusIV);
            _neutralSeriesNum = fname.Substring(3, 2);
            _side             = fname.Substring(5, 1).ToUpper();

            _neutralSeries = "S" + _neutralSeriesNum + _side;


            //now setup bonenames & paths
            for (int i = 0; i < _bnames.Length; i++)
            {
                _bpaths[i] = Path.Combine(_ivFolderPath, _bnames[i] + _neutralSeriesNum + _side + ext);
            }

            /* Finding the subject path
             * - Try and find the directory of the neutral series and then set the
             * subject path to its parent directory.
             */


            //first check if the neutral series path contains the IV files
            if (Path.GetFileName(_ivFolderPath).ToUpper().Equals(_neutralSeries))
            {
                _subjectPath = Path.GetDirectoryName(_ivFolderPath);
            }
            //else check to see if its one level above
            else if (Path.GetFileName(Path.GetDirectoryName(_ivFolderPath)).ToUpper().Equals(_neutralSeries))
            {
                _subjectPath = Path.GetDirectoryName(Path.GetDirectoryName(_ivFolderPath));
            }
            else
            {
                throw new ArgumentException("Unable to locate subject path");
            }

            _subject     = Path.GetFileName(_subjectPath);
            _inertiaFile = Path.Combine(Path.Combine(_subjectPath, _neutralSeries), "inertia" + _neutralSeriesNum + _side + ".dat");
            _acsFile     = Path.Combine(Path.Combine(_subjectPath, _neutralSeries), "AnatCoordSys.dat");
            _acsFile_uln = Path.Combine(Path.Combine(_subjectPath, _neutralSeries), "AnatCoordSys_uln.dat");

            //setup Distance fields
            string distanceFieldFolder = Path.Combine(Path.Combine(_subjectPath, _neutralSeries), "DistanceFields");

            for (int i = 0; i < _bnames.Length; i++)
            {
                _distanceFieldPaths[i] = Path.Combine(distanceFieldFolder, String.Format("{0}{1}{2}_mri", _bnames[i], _neutralSeriesNum, _side));
            }

            //Now verify that this is the subject path
            if (!Regex.Match(Path.GetFileName(_subjectPath), @"E\d{5}").Success)
            {
                throw new ArgumentException("Invalid subject path: " + _subjectPath);
            }
        }
示例#19
0
        public CodeParser(Databases databases, Function f, IndentationManager lastIndentation)
        {
            fdtb = databases.fdtb;
            cdtb = databases.cdtb;
            sdtb = databases.sdtb;
            indent = lastIndentation;

            int offset = f is LocalFunction ? 1 : 0;

            foreach (Argument a in f.arguments)
            {
                if (!a.isSelfArgument())
                {
                    locals[a.name] = new LocalVariable(locals.Count+offset, a.type);
                }
            }

            if (f is LocalFunction) {
                Argument selfArgument = f.arguments.First((x => x.isSelfArgument()));
                locals[selfArgument.name]=new LocalVariable(0, selfArgument.type);
            }
            #if DEBUG
            Console.WriteLine("Locals are: " + locals.toAdvancedString());
            #endif
            block = new CodeBlock();
        }
示例#20
0
    public override IEnumerator BindServices(IServiceContainer serviceContainer)
    {
        yield return(base.BindServices(serviceContainer));

        IGameService gameService = Services.GetService <IGameService>();

        if (gameService != null)
        {
            this.game = (gameService.Game as global::Game);
        }
        this.eventService = Services.GetService <IEventService>();
        if (this.eventService == null)
        {
            Diagnostics.LogError("Wasn't able to find the event service.");
        }
        yield return(base.BindService <IPathfindingService>(serviceContainer, delegate(IPathfindingService service)
        {
            this.pathfindingService = service;
        }));

        yield return(base.BindService <ISeasonService>(serviceContainer, delegate(ISeasonService service)
        {
            this.seasonService = service;
        }));

        IDatabase <WeatherDefinition> weatherDefinitionDatabase = Databases.GetDatabase <WeatherDefinition>(false);

        Diagnostics.Assert(weatherDefinitionDatabase != null);
        this.weatherDefinitions = weatherDefinitionDatabase.GetValues();
        Array.Sort <WeatherDefinition>(this.weatherDefinitions, (WeatherDefinition left, WeatherDefinition right) => left.Name.CompareHandleTo(right.Name));
        List <WeatherDefinition>    availableWeathers          = new List <WeatherDefinition>(this.weatherDefinitions);
        IDownloadableContentService downloadableContentService = Services.GetService <IDownloadableContentService>();

        if (downloadableContentService == null)
        {
            Diagnostics.LogError("Wasn't able to find the Downloadable Content Service.");
        }
        else if (downloadableContentService == null)
        {
            Diagnostics.LogError("Wasn't able to find the Downloadable Content Service.");
        }
        else
        {
            for (int weatherIndex = availableWeathers.Count - 1; weatherIndex >= 0; weatherIndex--)
            {
                if (string.IsNullOrEmpty(availableWeathers[weatherIndex].RequiredDLC) || !downloadableContentService.IsShared(availableWeathers[weatherIndex].RequiredDLC))
                {
                    availableWeathers.RemoveAt(weatherIndex);
                }
            }
        }
        this.availableWeathersForGeneneration = availableWeathers.ToArray();
        this.droplistDatabase = Databases.GetDatabase <Droplist>(false);
        Diagnostics.Assert(this.droplistDatabase != null);
        this.simulationDescriptorsDatabase = Databases.GetDatabase <SimulationDescriptor>(true);
        Diagnostics.Assert(this.simulationDescriptorsDatabase != null);
        this.weatherDifficulty = Amplitude.Unity.Framework.Application.Registry.GetValue <string>(WeatherManager.WeatherDifficulty, "Random");
        if (this.weatherDifficulty != "Easy" && this.weatherDifficulty != "Normal" && this.weatherDifficulty != "Hard")
        {
            this.weatherDifficulty = "Random";
        }
        if (!float.TryParse(Amplitude.Unity.Runtime.Runtime.Registry.GetValue("Gameplay/Ancillaries/Weather/LightningDamageInPercent"), out this.lightningDamageInPercent))
        {
            Diagnostics.LogError("Fail getting lightning damage percent value.");
        }
        this.WeatherControlCooldown   = -1;
        this.WeatherControlStartTurn  = -1;
        this.WeatherControlTurnToLast = -1;
        serviceContainer.AddService <IWeatherService>(this);
        yield return(base.BindService <IWorldPositionningService>(serviceContainer, delegate(IWorldPositionningService service)
        {
            this.worldPositionService = service;
        }));

        if (this.worldPositionService == null)
        {
            Diagnostics.LogError("Wasn't able to find the world positionning service.");
        }
        yield break;
    }
 /// <summary>
 /// Gets the appropriate connection string based on the provided database name.
 /// </summary>
 /// <param name="dbName">The database for which to fetch connection string.</param>
 /// <returns></returns>
 public static string ConnectionString(Databases dbName = Databases.Default)
 {
     return SolePortalConnectionString;
 }
示例#22
0
 private Engine(SqlVersion sqlVersion)
 {
     this.sqlVersion = sqlVersion;
     Version         = SqlVersionToInt(sqlVersion);
     Databases.Declare(new Database("master"));
 }
示例#23
0
		public static string GetModificationParseRule(string path){
			string s = path.Contains(Path.DirectorySeparatorChar) ? path.Substring(path.LastIndexOf(Path.DirectorySeparatorChar) + 1) : path;
			return !Databases.ContainsKey(s) ? "" : Databases[s].ModificationParseRule;
		}
示例#24
0
    private void ValidatePath()
    {
        IGuiService        service  = Services.GetService <IGuiService>();
        IAudioEventService service2 = Services.GetService <IAudioEventService>();

        Diagnostics.Assert(service2 != null);
        bool flag = base.SelectedUnits.Length == 0 || base.SelectedUnits.Length == this.Army.StandardUnits.Count || (this.Garrison.UnitsCount == 1 && this.Garrison.Hero != null);

        if (!base.IsTransferable(WorldCursor.HighlightedWorldPosition) && flag)
        {
            global::Empire empire = this.WorldArmy.Army.Empire;
            if (this.battleTarget is Army)
            {
                Army army = this.battleTarget as Army;
                if (army.Empire.Index == this.Army.Empire.Index)
                {
                    int num = Mathf.Max(army.MaximumUnitSlot - army.CurrentUnitSlot, 0);
                    if (this.Army.HasCatspaw || army.HasCatspaw)
                    {
                        QuickWarningPanel.Show("%UnitsTransferImpossibleWithCatsPawArmy");
                    }
                    else if (this.Army.StandardUnits.Count > num)
                    {
                        QuickWarningPanel.Show(string.Format(AgeLocalizer.Instance.LocalizeString("%UnitsTransferNotEnoughSlotsInTargetArmy"), num));
                    }
                    else if (this.Army.GetPropertyValue(SimulationProperties.Movement) <= 0f && base.WorldPositionningService.GetDistance(this.Army.WorldPosition, army.WorldPosition) == 1)
                    {
                        QuickWarningPanel.Show(AgeLocalizer.Instance.LocalizeString("%" + ArmyAction_TransferUnits.NotEnoughMovementToTransfer + "Description"));
                    }
                    else if (this.TemporaryWorldPath != null && this.TemporaryWorldPath.Length > 1 && !this.Army.HasCatspaw && !army.HasCatspaw)
                    {
                        OrderGoToAndMerge order = new OrderGoToAndMerge(empire.Index, this.WorldArmy.Army.GUID, this.battleTarget.GUID, (from unit in base.SelectedUnits
                                                                                                                                         select unit.GUID).ToArray <GameEntityGUID>(), this.TemporaryWorldPath);
                        this.PlayerControllerRepositoryService.ActivePlayerController.PostOrder(order);
                    }
                }
                else
                {
                    DepartmentOfForeignAffairs agency = empire.GetAgency <DepartmentOfForeignAffairs>();
                    Diagnostics.Assert(agency != null);
                    bool flag2 = this.Army.IsNaval == army.IsNaval;
                    if ((agency.CanAttack(this.battleTarget) || this.WorldArmy.Army.IsPrivateers) && flag2)
                    {
                        ArmyAction             armyAction = null;
                        IDatabase <ArmyAction> database   = Databases.GetDatabase <ArmyAction>(false);
                        float cost = 0f;
                        if (database != null && database.TryGetValue(ArmyAction_Attack.ReadOnlyName, out armyAction))
                        {
                            cost = armyAction.GetCostInActionPoints();
                        }
                        if (!this.Army.HasEnoughActionPoint(cost))
                        {
                            QuickWarningPanel.Show(AgeLocalizer.Instance.LocalizeString("%ArmyNotEnoughActionPointsDescription"));
                        }
                        else if (this.TemporaryWorldPath != null && this.TemporaryWorldPath.Length > 1)
                        {
                            OrderGoToAndAttack order2 = new OrderGoToAndAttack(empire.Index, this.WorldArmy.Army.GUID, this.battleTarget.GUID, this.TemporaryWorldPath);
                            this.PlayerControllerRepositoryService.ActivePlayerController.PostOrder(order2);
                        }
                        else
                        {
                            OrderAttack order3 = new OrderAttack(empire.Index, this.WorldArmy.Army.GUID, this.battleTarget.GUID);
                            this.PlayerControllerRepositoryService.ActivePlayerController.PostOrder(order3);
                        }
                        service2.Play2DEvent("Gui/Interface/InGame/OrderAttack");
                    }
                    else if (army.Empire is MajorEmpire && flag2)
                    {
                        global::Empire empire2 = army.Empire;
                        service.GetGuiPanel <WarDeclarationModalPanel>().Show(new object[]
                        {
                            empire2,
                            "AttackTarget"
                        });
                    }
                }
            }
            else
            {
                bool flag3 = false;
                if (this.battleTarget != null)
                {
                    if (this.TemporaryWorldPath != null && this.TemporaryWorldPath.Length > 1)
                    {
                        flag3  = (this.TemporaryWorldPath.ControlPoints.Length == 0);
                        flag3 |= (this.TemporaryWorldPath.ControlPoints.Length == 1 && (int)this.TemporaryWorldPath.ControlPoints[0] == this.TemporaryWorldPath.Length - 1);
                    }
                    else
                    {
                        flag3 = base.PathfindingService.IsTransitionPassable(this.Army.WorldPosition, this.battleTarget.WorldPosition, this.Army, PathfindingFlags.IgnoreArmies | PathfindingFlags.IgnoreOtherEmpireDistrict | PathfindingFlags.IgnoreDiplomacy | PathfindingFlags.IgnorePOI | PathfindingFlags.IgnoreSieges | PathfindingFlags.IgnoreKaijuGarrisons, null);
                    }
                }
                if (flag3 || this.battleTarget is Fortress || this.battleTarget is KaijuGarrison)
                {
                    flag3 = false;
                    bool flag4 = true;
                    if (this.battleTarget is KaijuGarrison)
                    {
                        KaijuGarrison kaijuGarrison        = this.battleTarget as KaijuGarrison;
                        DepartmentOfForeignAffairs agency2 = empire.GetAgency <DepartmentOfForeignAffairs>();
                        Diagnostics.Assert(agency2 != null);
                        if (!agency2.CanAttack(this.battleTarget))
                        {
                            flag4 = false;
                            global::Empire empire3 = kaijuGarrison.Empire;
                            service.GetGuiPanel <WarDeclarationModalPanel>().Show(new object[]
                            {
                                empire3,
                                "AttackTarget"
                            });
                        }
                    }
                    if (flag4)
                    {
                        ArmyActionModalPanel guiPanel = service.GetGuiPanel <ArmyActionModalPanel>();
                        if (guiPanel != null)
                        {
                            WorldPosition destination = (this.TemporaryWorldPath == null || this.TemporaryWorldPath.Length <= 1) ? WorldPosition.Invalid : this.TemporaryWorldPath.Destination;
                            if (guiPanel.CheckForArmyActionsAvailability(this.Army, this.battleTarget, destination).Count > 0)
                            {
                                flag3 = true;
                            }
                        }
                    }
                }
                if (flag3 && this.battleTarget != null && !this.Army.IsPrivateers)
                {
                    MajorEmpire majorEmpire = null;
                    if (this.battleTarget is Garrison)
                    {
                        majorEmpire = ((this.battleTarget as Garrison).Empire as MajorEmpire);
                    }
                    else if (this.battleTarget is District)
                    {
                        majorEmpire = ((this.battleTarget as District).Empire as MajorEmpire);
                    }
                    if (majorEmpire != null && majorEmpire.Index != this.Army.Empire.Index)
                    {
                        flag3 = this.Army.Empire.GetAgency <DepartmentOfForeignAffairs>().IsSymetricallyDiscovered(majorEmpire);
                    }
                }
                if (flag3)
                {
                    WorldPosition worldPosition = (this.TemporaryWorldPath == null || this.TemporaryWorldPath.Length <= 1) ? WorldPosition.Invalid : this.TemporaryWorldPath.Destination;
                    service.Show(typeof(ArmyActionModalPanel), new object[]
                    {
                        this.Army,
                        this.battleTarget,
                        base.SelectedUnits,
                        worldPosition
                    });
                }
                else if (this.TemporaryWorldPath != null && this.TemporaryWorldPath.Destination != WorldPosition.Invalid)
                {
                    OrderGoTo order4 = new OrderGoTo(empire.Index, this.WorldArmy.Army.GUID, this.TemporaryWorldPath.Destination);
                    this.PlayerControllerRepositoryService.ActivePlayerController.PostOrder(order4);
                    service2.Play2DEvent("Gui/Interface/InGame/OrderGoTo");
                }
                else if (WorldCursor.HighlightedWorldPosition != WorldPosition.Invalid)
                {
                    Region region = base.WorldPositionningService.GetRegion(WorldCursor.HighlightedWorldPosition);
                    if (region != null && region.City != null && region.City.Empire != null)
                    {
                        DepartmentOfForeignAffairs agency3 = this.Army.Empire.GetAgency <DepartmentOfForeignAffairs>();
                        Diagnostics.Assert(agency3 != null);
                        if (!agency3.CanMoveOn(WorldCursor.HighlightedWorldPosition, this.WorldArmy.Army.IsPrivateers, this.WorldArmy.Army.IsCamouflaged))
                        {
                            District district = base.WorldPositionningService.GetDistrict(WorldCursor.HighlightedWorldPosition);
                            if ((district == null || district.Type == DistrictType.Exploitation) && region.City.Empire is MajorEmpire)
                            {
                                service.GetGuiPanel <WarDeclarationModalPanel>().Show(new object[]
                                {
                                    region.City.Empire,
                                    "BreakCloseBorder"
                                });
                            }
                        }
                    }
                }
            }
        }
        this.LastHighlightedWorldPosition = WorldPosition.Invalid;
        this.LastUnpathableWorldPosition  = WorldPosition.Invalid;
        this.SelectTarget();
        this.UpdateBattlegroundVisibility();
        if (this.TemporaryWorldPath != null)
        {
            this.PathRendererService.RemovePath(this.TemporaryWorldPath);
            this.TemporaryWorldPath = null;
        }
    }
示例#25
0
		public static string GetTaxonomyId(string path){
			string s = path.Contains(Path.DirectorySeparatorChar) ? path.Substring(path.LastIndexOf(Path.DirectorySeparatorChar) + 1) : path;
			return !Databases.ContainsKey(s) ? "" : Databases[s].Taxid;
		}
示例#26
0
 protected void SpawnArmy(QuestBehaviour questBehaviour)
 {
     if (!string.IsNullOrEmpty(this.ArmyDroplist))
     {
         IGameService service = Services.GetService <IGameService>();
         if (service == null || service.Game == null)
         {
             Diagnostics.LogError("Failed to retrieve the game service.");
             return;
         }
         global::Game game = service.Game as global::Game;
         if (game == null)
         {
             Diagnostics.LogError("Failed to cast gameService.Game to Game.");
             return;
         }
         IDatabase <Droplist> database = Databases.GetDatabase <Droplist>(false);
         if (database == null)
         {
             return;
         }
         string text = this.ArmyDroplist;
         if (this.ArmyDroplistSuffix != string.Empty)
         {
             text = text + "_" + this.ArmyDroplistSuffix;
         }
         Droplist droplist;
         if (!database.TryGetValue(text, out droplist))
         {
             Diagnostics.LogError("Cannot retrieve drop list '{0}' in quest definition '{1}'", new object[]
             {
                 text,
                 questBehaviour.Quest.QuestDefinition.Name
             });
             return;
         }
         if (!string.IsNullOrEmpty(this.EmpireArmyOwnerVarName))
         {
             global::Empire empire = null;
             object         obj;
             if (questBehaviour.TryGetQuestVariableValueByName <object>(this.EmpireArmyOwnerVarName, out obj))
             {
                 if (obj is global::Empire)
                 {
                     empire = (obj as global::Empire);
                 }
                 else if (obj is int)
                 {
                     empire = game.Empires[(int)obj];
                 }
                 if (empire != null)
                 {
                     this.EmpireArmyOwner = empire;
                 }
             }
         }
         global::Empire empire2 = this.EmpireArmyOwner;
         if (empire2 == null || empire2 is LesserEmpire || this.UseBehaviorInitiatorEmpire)
         {
             empire2 = questBehaviour.Initiator;
         }
         if (this.UseBehaviorInitiatorEmpire)
         {
             this.EmpireArmyOwner = questBehaviour.Initiator;
         }
         if (this.EmpireArmyOwner is MajorEmpire && (this.EmpireArmyOwner as MajorEmpire).ELCPIsEliminated)
         {
             return;
         }
         Droplist droplist2;
         DroppableArmyDefinition droppableArmyDefinition = droplist.Pick(empire2, out droplist2, new object[0]) as DroppableArmyDefinition;
         if (droppableArmyDefinition != null)
         {
             int num = 0;
             if (this.ScaleWithMaxEra)
             {
                 num = DepartmentOfScience.GetMaxEraNumber() - 1;
             }
             int val = 0;
             IDatabase <AnimationCurve> database2 = Databases.GetDatabase <AnimationCurve>(false);
             AnimationCurve             animationCurve;
             if (database2 != null && database2.TryGetValue(QuestBehaviourTreeNode_Action_SpawnArmy.questUnitLevelEvolution, out animationCurve))
             {
                 float propertyValue = questBehaviour.Initiator.GetPropertyValue(SimulationProperties.GameSpeedMultiplier);
                 val = (int)animationCurve.EvaluateWithScaledAxis((float)game.Turn, propertyValue, 1f);
                 val = Math.Max(0, Math.Min(100, val));
             }
             num = Math.Max(num, val);
             StaticString[]         array     = Array.ConvertAll <string, StaticString>(droppableArmyDefinition.UnitDesigns, (string input) => input);
             bool                   flag      = false;
             IDatabase <UnitDesign> database3 = Databases.GetDatabase <UnitDesign>(false);
             for (int i = 0; i < array.Length; i++)
             {
                 UnitDesign unitDesign;
                 if (database3.TryGetValue(array[i], out unitDesign) && unitDesign != null && unitDesign.Tags.Contains(DownloadableContent16.TagSeafaring))
                 {
                     flag = true;
                     break;
                 }
             }
             IEnumerable <WorldPosition> enumerable = null;
             questBehaviour.TryGetQuestVariableValueByName <WorldPosition>(this.ForbiddenSpawnLocationVarName, out enumerable);
             List <WorldPosition>      list     = this.SpawnLocations.ToList <WorldPosition>().Randomize(null);
             IWorldPositionningService service2 = game.Services.GetService <IWorldPositionningService>();
             IPathfindingService       service3 = game.Services.GetService <IPathfindingService>();
             Diagnostics.Assert(service2 != null);
             WorldPosition worldPosition = WorldPosition.Invalid;
             if (!questBehaviour.Quest.QuestDefinition.IsGlobal)
             {
                 PathfindingMovementCapacity pathfindingMovementCapacity = PathfindingMovementCapacity.Water;
                 if (!flag)
                 {
                     pathfindingMovementCapacity |= PathfindingMovementCapacity.Ground;
                 }
                 for (int j = 0; j < list.Count; j++)
                 {
                     WorldPosition worldPosition2 = list[j];
                     if (DepartmentOfDefense.CheckWhetherTargetPositionIsValidForUseAsArmySpawnLocation(worldPosition2, pathfindingMovementCapacity))
                     {
                         if (enumerable != null)
                         {
                             if (enumerable.Contains(worldPosition2))
                             {
                                 goto IL_330;
                             }
                             this.AddPositionToForbiddenSpawnPosition(questBehaviour, worldPosition2);
                         }
                         worldPosition = worldPosition2;
                         break;
                     }
                     IL_330 :;
                 }
                 if (!service3.IsTileStopable(worldPosition, PathfindingMovementCapacity.Ground | PathfindingMovementCapacity.Water, PathfindingFlags.IgnoreFogOfWar))
                 {
                     worldPosition = WorldPosition.Invalid;
                 }
                 if (!worldPosition.IsValid && list.Count > 0)
                 {
                     List <WorldPosition>  list2 = new List <WorldPosition>();
                     Queue <WorldPosition> queue = new Queue <WorldPosition>();
                     worldPosition = list[0];
                     bool flag2 = false;
                     if (worldPosition.IsValid)
                     {
                         flag2 = service2.IsWaterTile(worldPosition);
                     }
                     do
                     {
                         if (queue.Count > 0)
                         {
                             worldPosition = queue.Dequeue();
                         }
                         for (int k = 0; k < 6; k++)
                         {
                             WorldPosition neighbourTileFullCyclic = service2.GetNeighbourTileFullCyclic(worldPosition, (WorldOrientation)k, 1);
                             if (!list2.Contains(neighbourTileFullCyclic) && list2.Count < 19)
                             {
                                 queue.Enqueue(neighbourTileFullCyclic);
                                 list2.Add(neighbourTileFullCyclic);
                             }
                         }
                         if (!DepartmentOfDefense.CheckWhetherTargetPositionIsValidForUseAsArmySpawnLocation(worldPosition, pathfindingMovementCapacity) || !service3.IsTileStopable(worldPosition, PathfindingMovementCapacity.Ground | PathfindingMovementCapacity.Water, PathfindingFlags.IgnoreFogOfWar) || flag2 != service2.IsWaterTile(worldPosition))
                         {
                             worldPosition = WorldPosition.Invalid;
                         }
                     }while (worldPosition == WorldPosition.Invalid && queue.Count > 0);
                 }
                 if (!worldPosition.IsValid)
                 {
                     string   format = "Cannot find a valid position to spawn on: {0}";
                     object[] array2 = new object[1];
                     array2[0] = string.Join(",", list.Select(delegate(WorldPosition position)
                     {
                         WorldPosition worldPosition3 = position;
                         return(worldPosition3.ToString());
                     }).ToArray <string>());
                     Diagnostics.LogError(format, array2);
                     return;
                 }
             }
             OrderSpawnArmy orderSpawnArmy;
             if (worldPosition.IsValid)
             {
                 list.Clear();
                 list.Add(worldPosition);
                 WorldOrientation worldOrientation = WorldOrientation.East;
                 for (int l = 0; l < 6; l++)
                 {
                     WorldPosition neighbourTile = service2.GetNeighbourTile(worldPosition, worldOrientation, 1);
                     bool          flag3         = flag == service2.IsWaterTile(neighbourTile);
                     if (neighbourTile.IsValid && flag3 && service3.IsTileStopable(worldPosition, PathfindingMovementCapacity.Ground | PathfindingMovementCapacity.Water, PathfindingFlags.IgnoreFogOfWar))
                     {
                         list.Add(neighbourTile);
                     }
                     worldOrientation = worldOrientation.Rotate(1);
                 }
                 orderSpawnArmy = new OrderSpawnArmy(this.EmpireArmyOwner.Index, list.ToArray(), num, true, this.CanMoveOnSpawn, true, questBehaviour.Quest.QuestDefinition.IsGlobal || this.ForceGlobalArmySymbol, array);
             }
             else
             {
                 orderSpawnArmy = new OrderSpawnArmy(this.EmpireArmyOwner.Index, list.ToArray(), num, true, this.CanMoveOnSpawn, true, questBehaviour.Quest.QuestDefinition.IsGlobal || this.ForceGlobalArmySymbol, array);
             }
             orderSpawnArmy.GameEntityGUID = this.ArmyGUID;
             Diagnostics.Log("Posting order: {0} at {1}", new object[]
             {
                 orderSpawnArmy.ToString(),
                 worldPosition
             });
             if (!string.IsNullOrEmpty(this.TransferResourceName) && this.TransferResourceAmount > 0)
             {
                 Ticket ticket;
                 this.EmpireArmyOwner.PlayerControllers.Server.PostOrder(orderSpawnArmy, out ticket, new EventHandler <TicketRaisedEventArgs>(this.OrderSpawnArmy_TicketRaised));
                 return;
             }
             this.EmpireArmyOwner.PlayerControllers.Server.PostOrder(orderSpawnArmy);
         }
     }
 }
示例#27
0
		public static bool ContainsDatabase(string path){
			string s = path.Contains(Path.DirectorySeparatorChar) ? path.Substring(path.LastIndexOf(Path.DirectorySeparatorChar) + 1) : path;
			return Databases.ContainsKey(s);
		}
示例#28
0
        public async Task GetRevisionsBinEntries(bool useSession)
        {
            using (var store1 = GetDocumentStore())
                using (var store2 = GetDocumentStore())
                {
                    var database = await Databases.GetDocumentDatabaseInstanceFor(store1);

                    var database2 = await Databases.GetDocumentDatabaseInstanceFor(store2);

                    database.TombstoneCleaner.Subscribe(this);
                    database2.TombstoneCleaner.Subscribe(this);

                    await RevisionsHelper.SetupRevisions(Server.ServerStore, store1.Database, configuration =>
                    {
                        configuration.Collections["Users"].PurgeOnDelete = false;
                    });

                    await RevisionsHelper.SetupRevisions(Server.ServerStore, store2.Database, configuration =>
                    {
                        configuration.Collections["Users"].PurgeOnDelete = false;
                    });
                    await SetupReplicationAsync(store1, store2);

                    var deletedRevisions = await store1.Commands().GetRevisionsBinEntriesAsync(long.MaxValue);

                    Assert.Equal(0, deletedRevisions.Count());

                    var id = "users/1";
                    if (useSession)
                    {
                        var user = new User {
                            Name = "Fitzchak"
                        };
                        for (var i = 0; i < 2; i++)
                        {
                            using (var session = store1.OpenAsyncSession())
                            {
                                await session.StoreAsync(user);

                                await session.SaveChangesAsync();
                            }
                            using (var session = store1.OpenAsyncSession())
                            {
                                session.Delete(user.Id);
                                await session.SaveChangesAsync();
                            }
                        }
                        id += "-A";
                    }
                    else
                    {
                        await store1.Commands().PutAsync(id, null, new User {
                            Name = "Fitzchak"
                        });

                        await store1.Commands().DeleteAsync(id, null);

                        await store1.Commands().PutAsync(id, null, new User {
                            Name = "Fitzchak"
                        });

                        await store1.Commands().DeleteAsync(id, null);
                    }

                    WaitForMarker(store1, store2);
                    var statistics = store2.Maintenance.Send(new GetStatisticsOperation());
                    Assert.Equal(useSession ? 2 : 1, statistics.CountOfDocuments);
                    Assert.Equal(4, statistics.CountOfRevisionDocuments);

                    //sanity
                    deletedRevisions = await store1.Commands().GetRevisionsBinEntriesAsync(long.MaxValue);

                    Assert.Equal(1, deletedRevisions.Count());

                    deletedRevisions = await store2.Commands().GetRevisionsBinEntriesAsync(long.MaxValue);

                    Assert.Equal(1, deletedRevisions.Count());

                    using (var session = store2.OpenAsyncSession())
                    {
                        var users = await session.Advanced.Revisions.GetForAsync <User>(id);

                        Assert.Equal(4, users.Count);
                        Assert.Equal(null, users[0].Name);
                        Assert.Equal("Fitzchak", users[1].Name);
                        Assert.Equal(null, users[2].Name);
                        Assert.Equal("Fitzchak", users[3].Name);

                        // Can get metadata only
                        var revisionsMetadata = await session.Advanced.Revisions.GetMetadataForAsync(id);

                        Assert.Equal(4, revisionsMetadata.Count);
                        Assert.Equal((DocumentFlags.DeleteRevision | DocumentFlags.HasRevisions | DocumentFlags.FromReplication).ToString(), revisionsMetadata[0].GetString(Constants.Documents.Metadata.Flags));
                        Assert.Equal((DocumentFlags.HasRevisions | DocumentFlags.Revision | DocumentFlags.FromReplication).ToString(), revisionsMetadata[1].GetString(Constants.Documents.Metadata.Flags));
                        Assert.Equal((DocumentFlags.DeleteRevision | DocumentFlags.HasRevisions | DocumentFlags.FromReplication).ToString(), revisionsMetadata[2].GetString(Constants.Documents.Metadata.Flags));
                        Assert.Equal((DocumentFlags.HasRevisions | DocumentFlags.Revision | DocumentFlags.FromReplication).ToString(), revisionsMetadata[3].GetString(Constants.Documents.Metadata.Flags));
                    }

                    await store1.Maintenance.SendAsync(new RevisionsTests.DeleteRevisionsOperation(new AdminRevisionsHandler.Parameters
                    {
                        DocumentIds = new[] { id, "users/not/exists" }
                    }));

                    WaitForMarker(store1, store2);

                    statistics = store2.Maintenance.Send(new GetStatisticsOperation());
                    Assert.Equal(useSession ? 3 : 2, statistics.CountOfDocuments);

                    Assert.Equal(0, statistics.CountOfRevisionDocuments);
                }
        }
示例#29
0
 private void txtMemID_TextChanged(object sender, EventArgs e)
 {
     grdBookedClasses.DataSource = Databases.GetMemberBookings(Convert.ToInt32(txtMemID.Text)).Tables["Bookings"];
 }
 public DatabaseTypeAttribute(Databases databaseType)
 {
     DatabaseType = databaseType;
 }
示例#31
0
 public DefaultManager()
 {
     Databases = new Databases();
 }
示例#32
0
    public static void CheckWorldGeneratorOptionsConstraints()
    {
        ISessionService service = Services.GetService <ISessionService>();

        if (service != null && service.Session != null)
        {
            IDatabase <WorldGeneratorOptionDefinition> database = Databases.GetDatabase <WorldGeneratorOptionDefinition>(false);
            if (database != null)
            {
                List <WorldGeneratorOptionDefinition> list = database.GetValues().ToList <WorldGeneratorOptionDefinition>();
                list.Sort(new WorldGenerator.WorldGeneratorOptionDefinitionComparer());
                for (int i = 0; i < list.Count; i++)
                {
                    string text      = list[i].Name;
                    string lobbyData = service.Session.GetLobbyData <string>(text, null);
                    if (string.IsNullOrEmpty(lobbyData))
                    {
                        string text2 = list[i].DefaultName;
                        service.Session.SetLobbyData(text, text2, true);
                        Amplitude.Diagnostics.LogWarning("Missing value for option (name: '{0}') has been reset to default (value: '{1}').", new object[]
                        {
                            text,
                            text2
                        });
                    }
                    else if (list[i].ItemDefinitions != null)
                    {
                        bool flag = false;
                        for (int j = 0; j < list[i].ItemDefinitions.Length; j++)
                        {
                            if (list[i].ItemDefinitions[j].Name == lobbyData)
                            {
                                flag = true;
                                OptionDefinition.ItemDefinition itemDefinition = list[i].ItemDefinitions[j];
                                if (itemDefinition.OptionDefinitionConstraints != null)
                                {
                                    foreach (OptionDefinitionConstraint optionDefinitionConstraint in from iterator in itemDefinition.OptionDefinitionConstraints
                                             where iterator.Type == OptionDefinitionConstraintType.Control
                                             select iterator)
                                    {
                                        string text3 = optionDefinitionConstraint.OptionName;
                                        if (string.IsNullOrEmpty(text3))
                                        {
                                            Amplitude.Diagnostics.LogWarning("Invalid null or empty option name for constraint (item: '{0'}', index: '{1}') in option (name: '{2}').", new object[]
                                            {
                                                itemDefinition.Name,
                                                Array.IndexOf <OptionDefinitionConstraint>(itemDefinition.OptionDefinitionConstraints, optionDefinitionConstraint),
                                                list[i].Name
                                            });
                                        }
                                        else
                                        {
                                            string lobbyData2 = service.Session.GetLobbyData <string>(text3, null);
                                            if (!optionDefinitionConstraint.Keys.Select((OptionDefinitionConstraint.Key key) => key.Name).Contains(lobbyData2))
                                            {
                                                string text4 = optionDefinitionConstraint.Keys[0].Name;
                                                service.Session.SetLobbyData(text3, text4, true);
                                                Amplitude.Diagnostics.LogWarning("Option (name: '{0}') has been control-constrained (new value: '{1}').", new object[]
                                                {
                                                    text3,
                                                    text4
                                                });
                                                int k = 0;
                                                while (k < list.Count)
                                                {
                                                    if (list[k].Name == text3)
                                                    {
                                                        if (k < i)
                                                        {
                                                            Amplitude.Diagnostics.Log("Rollback has been triggered.");
                                                            break;
                                                        }
                                                        break;
                                                    }
                                                    else
                                                    {
                                                        k++;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    foreach (OptionDefinitionConstraint optionDefinitionConstraint2 in from iterator in itemDefinition.OptionDefinitionConstraints
                                             where iterator.Type == OptionDefinitionConstraintType.Conditional
                                             select iterator)
                                    {
                                        string text5 = optionDefinitionConstraint2.OptionName;
                                        if (!string.IsNullOrEmpty(text5))
                                        {
                                            string lobbyData3 = service.Session.GetLobbyData <string>(text5, null);
                                            if (!optionDefinitionConstraint2.Keys.Select((OptionDefinitionConstraint.Key key) => key.Name).Contains(lobbyData3))
                                            {
                                                bool flag2 = false;
                                                foreach (OptionDefinition.ItemDefinition itemDefinition2 in list[i].ItemDefinitions)
                                                {
                                                    if (!(itemDefinition2.Name == lobbyData))
                                                    {
                                                        bool flag3 = false;
                                                        if (itemDefinition2.OptionDefinitionConstraints == null)
                                                        {
                                                            flag3 = true;
                                                        }
                                                        else
                                                        {
                                                            foreach (OptionDefinitionConstraint optionDefinitionConstraint3 in itemDefinition2.OptionDefinitionConstraints.Where((OptionDefinitionConstraint iterator) => iterator.Type == OptionDefinitionConstraintType.Conditional))
                                                            {
                                                                text5 = optionDefinitionConstraint3.OptionName;
                                                                if (!string.IsNullOrEmpty(text5))
                                                                {
                                                                    lobbyData3 = service.Session.GetLobbyData <string>(text5, null);
                                                                    if (optionDefinitionConstraint2.Keys.Select((OptionDefinitionConstraint.Key key) => key.Name).Contains(lobbyData3))
                                                                    {
                                                                        flag3 = true;
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        if (flag3)
                                                        {
                                                            service.Session.SetLobbyData(text, itemDefinition2.Name, true);
                                                            Amplitude.Diagnostics.LogWarning("Option (name: '{0}') has been condition-constrained (new value: '{1}').", new object[]
                                                            {
                                                                text,
                                                                itemDefinition2.Name
                                                            });
                                                            flag2 = true;
                                                            break;
                                                        }
                                                    }
                                                }
                                                if (flag2)
                                                {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (!flag)
                        {
                            string text6 = list[i].DefaultName;
                            service.Session.SetLobbyData(text, text6, true);
                            if (text6 != lobbyData)
                            {
                                i--;
                            }
                            Amplitude.Diagnostics.LogWarning("Invalid value for option (name: '{0}', value: '{1}') has been reset to default (value: '{2}').", new object[]
                            {
                                text,
                                lobbyData,
                                text6
                            });
                        }
                    }
                }
            }
        }
    }
示例#33
0
        public async Task PutAttachments()
        {
            using (var store = GetDocumentStore())
            {
                var names = new[]
                {
                    "profile.png",
                    "background-photo.jpg",
                    "fileNAME_#$1^%_בעברית.txt"
                };

                using (var session = store.OpenSession())
                    using (var profileStream = new MemoryStream(new byte[] { 1, 2, 3 }))
                        using (var backgroundStream = new MemoryStream(new byte[] { 10, 20, 30, 40, 50 }))
                            using (var fileStream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }))
                            {
                                var user = new User {
                                    Name = "Fitzchak"
                                };
                                session.Store(user, "users/1");

                                session.Advanced.Attachments.Store("users/1", names[0], profileStream, "image/png");
                                session.Advanced.Attachments.Store(user, names[1], backgroundStream, "ImGgE/jPeG");
                                session.Advanced.Attachments.Store(user, names[2], fileStream);

                                session.SaveChanges();
                            }

                using (var session = store.OpenSession())
                {
                    var user     = session.Load <User>("users/1");
                    var metadata = session.Advanced.GetMetadataFor(user);
                    Assert.Equal(DocumentFlags.HasAttachments.ToString(), metadata[Constants.Documents.Metadata.Flags]);
                    var attachments = metadata.GetObjects(Constants.Documents.Metadata.Attachments);
                    Assert.Equal(3, attachments.Length);
                    var orderedNames = names.OrderBy(x => x).ToArray();
                    for (var i = 0; i < names.Length; i++)
                    {
                        var name       = orderedNames[i];
                        var attachment = attachments[i];
                        Assert.Equal(name, attachment.GetString(nameof(AttachmentName.Name)));
                        var hash = attachment.GetString(nameof(AttachmentName.Hash));
                        if (i == 0)
                        {
                            Assert.Equal("igkD5aEdkdAsAB/VpYm1uFlfZIP9M2LSUsD6f6RVW9U=", hash);
                            Assert.Equal(5, attachment.GetLong(nameof(AttachmentName.Size)));
                        }
                        else if (i == 1)
                        {
                            Assert.Equal("Arg5SgIJzdjSTeY6LYtQHlyNiTPmvBLHbr/Cypggeco=", hash);
                            Assert.Equal(5, attachment.GetLong(nameof(AttachmentName.Size)));
                        }
                        else if (i == 2)
                        {
                            Assert.Equal("EcDnm3HDl2zNDALRMQ4lFsCO3J2Lb1fM1oDWOk2Octo=", hash);
                            Assert.Equal(3, attachment.GetLong(nameof(AttachmentName.Size)));
                        }
                    }

                    AttachmentsCrud.AssertAttachmentCount(store, 3, 3);

                    var dbId1 = new Guid("00000000-48c4-421e-9466-000000000000");
                    await Databases.SetDatabaseId(store, dbId1);

                    var readBuffer = new byte[8];
                    for (var i = 0; i < names.Length; i++)
                    {
                        var name = names[i];
                        using (var attachmentStream = new MemoryStream(readBuffer))
                            using (var attachment = session.Advanced.Attachments.Get(user, name))
                            {
                                attachment.Stream.CopyTo(attachmentStream);
                                var expected = "A:" + (2 + i);
                                Assert.Equal(expected, attachment.Details.ChangeVector.Substring(0, expected.Length));
                                Assert.Equal(name, attachment.Details.Name);
                                Assert.Equal(i == 0 ? 3 : 5, attachmentStream.Position);
                                if (i == 0)
                                {
                                    Assert.Equal(new byte[] { 1, 2, 3 }, readBuffer.Take(3));
                                    Assert.Equal("image/png", attachment.Details.ContentType);
                                    Assert.Equal("EcDnm3HDl2zNDALRMQ4lFsCO3J2Lb1fM1oDWOk2Octo=", attachment.Details.Hash);
                                    Assert.Equal(3, attachment.Details.Size);
                                }
                                else if (i == 1)
                                {
                                    Assert.Equal(new byte[] { 10, 20, 30, 40, 50 }, readBuffer.Take(5));
                                    Assert.Equal("ImGgE/jPeG", attachment.Details.ContentType);
                                    Assert.Equal("igkD5aEdkdAsAB/VpYm1uFlfZIP9M2LSUsD6f6RVW9U=", attachment.Details.Hash);
                                    Assert.Equal(5, attachment.Details.Size);
                                }
                                else if (i == 2)
                                {
                                    Assert.Equal(new byte[] { 1, 2, 3, 4, 5 }, readBuffer.Take(5));
                                    Assert.Equal("", attachment.Details.ContentType);
                                    Assert.Equal("Arg5SgIJzdjSTeY6LYtQHlyNiTPmvBLHbr/Cypggeco=", attachment.Details.Hash);
                                    Assert.Equal(5, attachment.Details.Size);
                                }
                            }
                    }

                    using (var notExistsAttachment = session.Advanced.Attachments.Get("users/1", "not-there"))
                    {
                        Assert.Null(notExistsAttachment);
                    }
                }
            }
        }
示例#34
0
 public MSSQLConnectionFactory(IConfiguration configuration, ILogger <MSSQLConnectionFactory> logger)
 {
     _configuration = configuration;
     _logger        = logger;
     DatabaseType   = Databases.MSSQL;
 }
示例#35
0
        public async Task DeleteAttachments()
        {
            using (var store = GetDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    var user = new User {
                        Name = "Fitzchak"
                    };
                    session.Store(user, "users/1");

                    using (var stream1 = new MemoryStream(Enumerable.Range(1, 3).Select(x => (byte)x).ToArray()))
                        using (var stream2 = new MemoryStream(Enumerable.Range(1, 6).Select(x => (byte)x).ToArray()))
                            using (var stream3 = new MemoryStream(Enumerable.Range(1, 9).Select(x => (byte)x).ToArray()))
                                using (var stream4 = new MemoryStream(Enumerable.Range(1, 12).Select(x => (byte)x).ToArray()))
                                {
                                    session.Advanced.Attachments.Store(user, "file1", stream1, "image/png");
                                    session.Advanced.Attachments.Store(user, "file2", stream2, "image/png");
                                    session.Advanced.Attachments.Store(user, "file3", stream3, "image/png");
                                    session.Advanced.Attachments.Store(user, "file4", stream4, "image/png");

                                    session.SaveChanges();
                                }
                }

                AttachmentsCrud.AssertAttachmentCount(store, 4, documentsCount: 1);

                using (var session = store.OpenSession())
                {
                    var user = session.Load <User>("users/1");

                    session.Advanced.Attachments.Delete("users/1", "file2");
                    session.Advanced.Attachments.Delete(user, "file4");

                    session.SaveChanges();
                }
                AttachmentsCrud.AssertAttachmentCount(store, 2, documentsCount: 1);

                using (var session = store.OpenSession())
                {
                    var user     = session.Load <User>("users/1");
                    var metadata = session.Advanced.GetMetadataFor(user);
                    Assert.Equal(DocumentFlags.HasAttachments.ToString(), metadata[Constants.Documents.Metadata.Flags]);
                    var attachments = metadata.GetObjects(Constants.Documents.Metadata.Attachments);
                    Assert.Equal(2, attachments.Length);
                    Assert.Equal("file1", attachments[0].GetString(nameof(AttachmentName.Name)));
                    Assert.Equal("EcDnm3HDl2zNDALRMQ4lFsCO3J2Lb1fM1oDWOk2Octo=", attachments[0].GetString(nameof(AttachmentName.Hash)));
                    Assert.Equal("file3", attachments[1].GetString(nameof(AttachmentName.Name)));
                    Assert.Equal("NRQuixiqj+xvEokF6MdQq1u+uH1dk/gk2PLChJQ58Vo=", attachments[1].GetString(nameof(AttachmentName.Hash)));
                }

                var dbId1 = new Guid("00000000-48c4-421e-9466-000000000000");
                await Databases.SetDatabaseId(store, dbId1);

                using (var session = store.OpenSession())
                {
                    var user = session.Load <User>("users/1");


                    var readBuffer = new byte[16];
                    using (var attachmentStream = new MemoryStream(readBuffer))
                        using (var attachment = session.Advanced.Attachments.Get("users/1", "file1"))
                        {
                            attachment.Stream.CopyTo(attachmentStream);
                            Assert.Equal("A:2", attachment.Details.ChangeVector.Substring(0, 3));
                            Assert.Equal("file1", attachment.Details.Name);
                            Assert.Equal("EcDnm3HDl2zNDALRMQ4lFsCO3J2Lb1fM1oDWOk2Octo=", attachment.Details.Hash);
                            Assert.Equal(3, attachmentStream.Position);
                            Assert.Equal(new byte[] { 1, 2, 3 }, readBuffer.Take(3));
                        }
                    using (var attachment = session.Advanced.Attachments.Get(user, "file2"))
                    {
                        Assert.Null(attachment);
                    }
                    using (var attachmentStream = new MemoryStream(readBuffer))
                        using (var attachment = session.Advanced.Attachments.Get(user, "file3"))
                        {
                            attachment.Stream.CopyTo(attachmentStream);
                            Assert.Equal("A:4", attachment.Details.ChangeVector.Substring(0, 3));
                            Assert.Equal("file3", attachment.Details.Name);
                            Assert.Equal("NRQuixiqj+xvEokF6MdQq1u+uH1dk/gk2PLChJQ58Vo=", attachment.Details.Hash);
                            Assert.Equal(9, attachmentStream.Position);
                            Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, readBuffer.Take(9));
                        }
                    using (var attachment = session.Advanced.Attachments.Get(user, "file4"))
                    {
                        Assert.Null(attachment);
                    }

                    // Delete document should delete all the attachments
                    session.Delete(user);
                    session.SaveChanges();
                }
                AttachmentsCrud.AssertAttachmentCount(store, 0, documentsCount: 0);
            }
        }
示例#36
0
 public TypeWriter(KindPrototype parent, KindPrototype kind, Databases dtbs)
 {
     this.parent = parent;
     this.kind = kind;
     this.dtbs = dtbs;
     var name = dtbs.sdtb.getStr(parent.getName());
     stringID = name.getID();
 }
示例#37
0
    public virtual void ReadXml(XmlReader reader)
    {
        int num = reader.ReadVersionAttribute();

        reader.ReadStartElement();
        this.OwnerEmpireIndex = reader.ReadElementString <int>("OwnerEmpireIndex");
        this.OtherEmpireIndex = reader.ReadElementString <int>("OtherEmpireIndex");
        string text = reader.ReadElementString <string>("State");

        if (string.IsNullOrEmpty(text))
        {
            this.State = null;
            Diagnostics.Assert(this.OwnerEmpireIndex == this.OtherEmpireIndex);
        }
        else
        {
            IDatabase <DiplomaticRelationState> database = Databases.GetDatabase <DiplomaticRelationState>(false);
            DiplomaticRelationState             state;
            if (!database.TryGetValue(text, out state))
            {
                Diagnostics.LogError("Can't retrieve diplomatic relation state {0} from database.", new object[]
                {
                    text
                });
            }
            this.State = state;
        }
        this.TurnAtTheBeginningOfTheState = reader.ReadElementString <int>("TurnAtTheBeginningOfTheState");
        int attribute = reader.GetAttribute <int>("Count");

        reader.ReadStartElement("DiplomaticAbilities");
        if (num >= 3)
        {
            for (int i = 0; i < attribute; i++)
            {
                DiplomaticAbility diplomaticAbility = new DiplomaticAbility();
                reader.ReadElementSerializable <DiplomaticAbility>(ref diplomaticAbility);
                ((IDiplomaticRelationManagment)this).AddDiplomaticAbility(diplomaticAbility);
            }
        }
        else
        {
            IDatabase <DiplomaticAbilityDefinition> database2 = Databases.GetDatabase <DiplomaticAbilityDefinition>(false);
            for (int j = 0; j < attribute; j++)
            {
                string text2 = reader.ReadElementString <string>("DiplomaticAbility");
                if (text2 == "PassOverArmies")
                {
                    text2 = DiplomaticAbilityDefinition.PassThroughArmies;
                }
                if (text2 == "VisionAndMapExchange")
                {
                    text2 = DiplomaticAbilityDefinition.VisionExchange;
                }
                DiplomaticAbilityDefinition diplomaticAbilityDefinition;
                if (!database2.TryGetValue(text2, out diplomaticAbilityDefinition))
                {
                    Diagnostics.LogError("Can't retrieve the diplomatic ability {0}.", new object[]
                    {
                        text2
                    });
                }
                ((IDiplomaticRelationManagment)this).AddDiplomaticAbility(diplomaticAbilityDefinition);
            }
        }
        reader.ReadEndElement("DiplomaticAbilities");
        if (num >= 2)
        {
            this.score = new DiplomaticRelationScore(1f, -100f, 100f);
            reader.ReadElementSerializable <DiplomaticRelationScore>(ref this.score);
        }
        IEndTurnService service = Services.GetService <IEndTurnService>();

        this.RelationDuration = (float)(service.Turn - this.TurnAtTheBeginningOfTheState);
    }
示例#38
0
    public static void GetCostAndTurn(Amplitude.Unity.Gui.IGuiService guiService, DepartmentOfTheTreasury departmentOfTheTreasury, SimulationObjectWrapper context, out string costString, out int turn)
    {
        turn = 0;
        StringBuilder stringBuilder = new StringBuilder();

        if (PanelFeatureCost.costByResource.Count > 0)
        {
            bool flag = false;
            IDatabase <ResourceDefinition> database = Databases.GetDatabase <ResourceDefinition>(false);
            foreach (KeyValuePair <StaticString, PanelFeatureCost.CostResume> keyValuePair in PanelFeatureCost.costByResource)
            {
                if (keyValuePair.Key == SimulationProperties.Population)
                {
                    stringBuilder.Append(GuiFormater.FormatGui(keyValuePair.Value.Cost, false, true, false, 1));
                    stringBuilder.Append(guiService.FormatSymbol(keyValuePair.Key));
                }
                else if (keyValuePair.Key == DepartmentOfTheTreasury.Resources.FreeBorough)
                {
                    stringBuilder.Append(GuiFormater.FormatGui(keyValuePair.Value.Cost, false, true, false, 1));
                    stringBuilder.Append(guiService.FormatSymbol(keyValuePair.Key));
                    float num;
                    if (!departmentOfTheTreasury.TryGetResourceStockValue(context.SimulationObject, DepartmentOfTheTreasury.Resources.QueuedFreeBorough, out num, true))
                    {
                        Diagnostics.Log("Can't get resource stock value {0} on simulation object {1}.", new object[]
                        {
                            DepartmentOfTheTreasury.Resources.QueuedFreeBorough,
                            context.SimulationObject.Name
                        });
                    }
                    else
                    {
                        stringBuilder.Append(string.Format(AgeLocalizer.Instance.LocalizeString("%CityFreeBoroughsLeft"), num));
                    }
                }
                else
                {
                    float              cost = keyValuePair.Value.Cost;
                    StaticString       key  = keyValuePair.Key;
                    ResourceDefinition resourceDefinition;
                    if (!database.TryGetValue(key, out resourceDefinition))
                    {
                        Diagnostics.LogError("Invalid resource name. The resource {0} does not exist in the resource database.", new object[]
                        {
                            key
                        });
                    }
                    else
                    {
                        string value = guiService.FormatSymbol(resourceDefinition.GetName(departmentOfTheTreasury.Empire));
                        if (!string.IsNullOrEmpty(value))
                        {
                            global::Empire empire = null;
                            if (context is City)
                            {
                                empire = (context as City).Empire;
                            }
                            else if (context is global::Empire)
                            {
                                empire = (context as global::Empire);
                            }
                            if (empire.SimulationObject.Tags.Contains(FactionTrait.FactionTraitMimics2) && key == DepartmentOfTheTreasury.Resources.Production)
                            {
                                ResourceDefinition resourceDefinition2;
                                if (!database.TryGetValue(SimulationProperties.CityGrowth, out resourceDefinition2))
                                {
                                    Diagnostics.LogError("Invalid resource name. The resource {0} does not exist in the resource database.", new object[]
                                    {
                                        key
                                    });
                                    continue;
                                }
                                value = guiService.FormatSymbol(resourceDefinition2.GetName(departmentOfTheTreasury.Empire));
                                if (string.IsNullOrEmpty(value))
                                {
                                    continue;
                                }
                            }
                            float num2;
                            if (!departmentOfTheTreasury.TryGetResourceStockValue(context.SimulationObject, key, out num2, true))
                            {
                                num2 = 0f;
                            }
                            if (keyValuePair.Value.Instant && num2 < cost)
                            {
                                AgeUtils.ColorToHexaKey(Color.red, ref stringBuilder, false);
                                flag = true;
                            }
                            stringBuilder.Append(GuiFormater.FormatGui(cost, false, true, false, 1));
                            stringBuilder.Append(value);
                            if (flag)
                            {
                                stringBuilder.Append("#REVERT#");
                                flag = false;
                            }
                            if (!keyValuePair.Value.Instant)
                            {
                                float num3;
                                if (!departmentOfTheTreasury.TryGetNetResourceValue(context.SimulationObject, key, out num3, true))
                                {
                                    num3 = 0f;
                                }
                                if (cost > num2)
                                {
                                    if (num3 <= 0f)
                                    {
                                        turn = int.MaxValue;
                                    }
                                    else
                                    {
                                        int num4 = Mathf.CeilToInt((cost - num2) / num3);
                                        if (num4 > turn)
                                        {
                                            turn = num4;
                                        }
                                    }
                                }
                            }
                            stringBuilder.Append(" ");
                        }
                    }
                }
            }
        }
        costString = stringBuilder.ToString();
        if (string.IsNullOrEmpty(costString))
        {
            costString = "-";
        }
    }
示例#39
0
    private void LoadGuiImage(params object[] parameters)
    {
        if (this.Background.Image != null)
        {
            AgeManager.Instance.ReleaseDynamicTexture(this.Background.Image.name);
        }
        string             text = string.Empty;
        GameSaveDescriptor gameSaveDescriptor = null;

        if (parameters.Length > 0)
        {
            for (int i = 0; i < parameters.Length; i++)
            {
                if (parameters[i] is string)
                {
                    text = (string)parameters[i];
                    this.Background.Image = (Resources.Load(text) as Texture2D);
                    if (this.Background.Image != null)
                    {
                        break;
                    }
                }
                if (parameters[i] is GameSaveDescriptor)
                {
                    gameSaveDescriptor = (parameters[i] as GameSaveDescriptor);
                }
            }
        }
        if (string.IsNullOrEmpty(text))
        {
            if (this.SessionService != null && this.SessionService.Session != null && this.SessionService.Session.IsOpened)
            {
                int num = 0;
                for (;;)
                {
                    string x         = string.Format("Empire{0}", num);
                    string lobbyData = this.SessionService.Session.GetLobbyData <string>(x, null);
                    if (string.IsNullOrEmpty(lobbyData))
                    {
                        break;
                    }
                    if (lobbyData.Contains(this.SessionService.Session.SteamIDUser.ToString()))
                    {
                        goto Block_11;
                    }
                    num++;
                }
                goto IL_201;
Block_11:
                string x2 = string.Format("Faction{0}", num);
                string lobbyData2 = this.SessionService.Session.GetLobbyData <string>(x2, null);
                if (!string.IsNullOrEmpty(lobbyData2))
                {
                    string[]               array      = lobbyData2.Split(Amplitude.String.Separators, StringSplitOptions.None);
                    string                 x3         = array[3];
                    GuiElement             guiElement = null;
                    IDatabase <GuiElement> database   = Databases.GetDatabase <GuiElement>(false);
                    if (database != null && database.TryGetValue(x3, out guiElement))
                    {
                        text = guiElement.Icons["MoodScore"];
                        this.Background.Image = (Resources.Load(text) as Texture2D);
                    }
                }
            }
IL_201:
            if (string.IsNullOrEmpty(text))
            {
                if (gameSaveDescriptor == null)
                {
                    IGameSerializationService service = Services.GetService <IGameSerializationService>();
                    if (service != null && service.GameSaveDescriptor != null)
                    {
                        gameSaveDescriptor = service.GameSaveDescriptor;
                    }
                }
                if (gameSaveDescriptor != null)
                {
                    int num2 = 0;
                    for (;;)
                    {
                        string key        = string.Format("Empire{0}", num2);
                        string lobbyData3 = gameSaveDescriptor.GameSaveSessionDescriptor.GetLobbyData <string>(key, null);
                        if (string.IsNullOrEmpty(lobbyData3))
                        {
                            break;
                        }
                        Steamworks.SteamID steamID = Steamworks.SteamAPI.SteamUser.SteamID;
                        bool flag  = lobbyData3.Contains(steamID.ToString());
                        bool flag2 = !lobbyData3.StartsWith("AI");
                        if (flag || (flag2 && string.IsNullOrEmpty(text)))
                        {
                            string key2       = string.Format("Faction{0}", num2);
                            string lobbyData4 = gameSaveDescriptor.GameSaveSessionDescriptor.GetLobbyData <string>(key2, null);
                            if (!string.IsNullOrEmpty(lobbyData4))
                            {
                                string[]               array2      = lobbyData4.Split(Amplitude.String.Separators, StringSplitOptions.None);
                                string                 x4          = array2[3];
                                GuiElement             guiElement2 = null;
                                IDatabase <GuiElement> database2   = Databases.GetDatabase <GuiElement>(false);
                                if (database2 != null && database2.TryGetValue(x4, out guiElement2))
                                {
                                    text = guiElement2.Icons["MoodScore"];
                                    this.Background.Image = (Resources.Load(text) as Texture2D);
                                }
                            }
                            if (flag)
                            {
                                break;
                            }
                        }
                        num2++;
                    }
                }
                if (string.IsNullOrEmpty(text))
                {
                    if (this.validGuiElements != null && this.validGuiElements.Count != 0)
                    {
                        GuiElement guiElement3 = this.validGuiElements[UnityEngine.Random.Range(0, this.validGuiElements.Count)];
                        Texture2D  image;
                        if (base.GuiService.GuiPanelHelper.TryGetTextureFromIcon(guiElement3, global::GuiPanel.IconSize.MoodScore, out image))
                        {
                            this.Background.Image = image;
                        }
                    }
                    else
                    {
                        this.Background.Image = (Resources.Load("GUI/DynamicBitmaps/Backdrop/Pov_Auriga") as Texture2D);
                    }
                }
            }
        }
    }
示例#40
0
        public async Task<Databases> GetDatabasesAsync()
        {
            ThrowIfDisposed();

            var result = new Databases();

            var json = await GetDatabasesJsonAsync().ForAwait();
            var data = Requester.JsonSerializer.Deserialize<InfluxDbResponse>(json);
            if (data?.Results == null || !data.Results.Any())
                return result;

            foreach (var serie in data.Results.SelectMany(r => r.Series))
                result.AddRange(serie.Values.Select(value => value.First.ToObject<string>()).ToArray());

            return result;
        }
示例#41
0
        public async Task PutDifferentAttachmentsShouldConflict()
        {
            using (var store1 = GetDocumentStore(options: new Options
            {
                ModifyDatabaseRecord = record =>
                {
                    record.ConflictSolverConfig = new ConflictSolver();
                }
            }))
                using (var store2 = GetDocumentStore(options: new Options
                {
                    ModifyDatabaseRecord = record =>
                    {
                        record.ConflictSolverConfig = new ConflictSolver();
                    }
                }))
                {
                    await Databases.SetDatabaseId(store1, new Guid("00000000-48c4-421e-9466-000000000000"));

                    await Databases.SetDatabaseId(store2, new Guid("99999999-48c4-421e-9466-999999999999"));

                    using (var session = store1.OpenAsyncSession())
                    {
                        var x = new User {
                            Name = "Fitzchak"
                        };
                        await session.StoreAsync(x, "users/1");

                        await session.SaveChangesAsync();

                        using (var a1 = new MemoryStream(new byte[] { 1, 2, 3 }))
                        {
                            await store1.Operations.SendAsync(new PutAttachmentOperation("users/1", "a1", a1, "a1/png"));
                        }

                        using (var session2 = store2.OpenSession())
                        {
                            session2.Store(new User {
                                Name = "Fitzchak"
                            }, "users/1");
                            session2.SaveChanges();

                            using (var a2 = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }))
                            {
                                store2.Operations.Send(new PutAttachmentOperation("users/1", "a1", a2, "a1/png"));
                            }

                            await SetupReplicationAsync(store1, store2);

                            await session.StoreAsync(new User { Name = "Toli" }, "users/2");

                            await session.SaveChangesAsync();

                            WaitForDocumentToReplicate <User>(store2, "users/2", 3000);

                            var conflicts = (await store2.Commands().GetConflictsForAsync("users/1")).ToList();
                            Assert.Equal(2, conflicts.Count);
                            var requestExecutor = store2.GetRequestExecutor();

                            using (var context = JsonOperationContext.ShortTermSingleUse())
                                using (var stringStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(_conflictedDocument)))
                                    using (var blittableJson = await context.ReadForMemoryAsync(stringStream, "Reading of foo/bar"))
                                    {
                                        var result = new InMemoryDocumentSessionOperations.SaveChangesData((InMemoryDocumentSessionOperations)session2);
                                        result.SessionCommands.Add(new PutCommandDataWithBlittableJson("users/1", null, null, blittableJson));
                                        var sbc = new SingleNodeBatchCommand(DocumentConventions.Default, context, result.SessionCommands, result.Options);
                                        await requestExecutor.ExecuteAsync(sbc, context);
                                    }
                        }
                    }

                    using (var session = store1.OpenAsyncSession())
                    {
                        var conflicts = (await store2.Commands().GetConflictsForAsync("users/1")).ToList();
                        Assert.Equal(0, conflicts.Count);

                        Assert.True(await session.Advanced.Attachments.ExistsAsync("users/1", "a1"));
                    }
                }
        }
示例#42
0
 public BattleTargetingController(IWorldPositionningService worldPositionningService, IPathfindingService pathfindingService, BattleSimulation battleSimulation)
 {
     if (worldPositionningService == null)
     {
         throw new ArgumentNullException("worldPositionningService");
     }
     if (pathfindingService == null)
     {
         throw new ArgumentNullException("pathfindingService");
     }
     this.worldPositionningService         = worldPositionningService;
     this.pathfindingService               = pathfindingService;
     this.targettingAnimationCurveDatabase = Databases.GetDatabase <Amplitude.Unity.Framework.AnimationCurve>(false);
     if (this.targettingAnimationCurveDatabase == null)
     {
         Diagnostics.Assert("Can't retrieve the animationCurve database.", new object[0]);
     }
     this.battleTargetingUnitBehaviorWeightDatabase = Databases.GetDatabase <BattleTargetingUnitBehaviorWeight>(false);
     if (this.battleTargetingUnitBehaviorWeightDatabase == null)
     {
         Diagnostics.Assert("Can't retrieve the unit behavior weight database, please reimport BehaviorWeight/BattleTargetingUnitBehaviorWeight.xls.", new object[0]);
     }
     this.battleSimulation           = battleSimulation;
     this.paramsComputationDelegates = new Dictionary <StaticString, BattleTargetingController.ParamComputationDelegate>();
     this.paramsComputationDelegates.Add("TurnsToReachTargetWithCapacities", new BattleTargetingController.ParamComputationDelegate(this.GetNumberOfTurnToReachTargetWithCapacities));
     this.paramsComputationDelegates.Add("TurnsToReachTargetAsCrowFlies", new BattleTargetingController.ParamComputationDelegate(this.GetNumberOfTurnToReachTargetByAir));
     this.paramsComputationDelegates.Add("TargetHPRatio", new BattleTargetingController.ParamComputationDelegate(this.GetTargetHPRatio));
     this.paramsComputationDelegates.Add("DoesTargetHaveFullHP", new BattleTargetingController.ParamComputationDelegate(this.GetDoesTargetHaveFullHP));
     this.paramsComputationDelegates.Add("TargetLostHPRatio", new BattleTargetingController.ParamComputationDelegate(this.GetTargetLostHPRatio));
     this.paramsComputationDelegates.Add("TargetRatioOfOffensiveMilitaryPowerToBattleAverage", new BattleTargetingController.ParamComputationDelegate(this.GetTargetOffensiveMilitaryPowerRatio));
     this.paramsComputationDelegates.Add("TargetRatioOfDefensiveMilitaryPowerToBattleAverage", new BattleTargetingController.ParamComputationDelegate(this.GetTargetDefensiveMilitaryPowerRatio));
     this.paramsComputationDelegates.Add("TargetMorale", new BattleTargetingController.ParamComputationDelegate(this.GetTargetMorale));
     this.paramsComputationDelegates.Add("RatioOfTargetSpeedToBattleArea", new BattleTargetingController.ParamComputationDelegate(this.GetRatioOfTargetSpeedToBattleArea));
     this.paramsComputationDelegates.Add("WithinAttackRange", new BattleTargetingController.ParamComputationDelegate(this.GetWithinAttackRange));
     this.paramsComputationDelegates.Add("WithinMovementRange", new BattleTargetingController.ParamComputationDelegate(this.GetWithinMovementRange));
     this.paramsComputationDelegates.Add("WithinAttackAndMoveRange", new BattleTargetingController.ParamComputationDelegate(this.GetWithinAttackAndMoveRange));
     this.paramsComputationDelegates.Add("RatioDistanceToAttackAndMoveRange", new BattleTargetingController.ParamComputationDelegate(this.GetRatioDistanceToAttackAndMoveRange));
     this.paramsComputationDelegates.Add("NumberOfNegativeGroundEffectsAtTargetPosition", new BattleTargetingController.ParamComputationDelegate(this.GetNumberOfNegativeGroundBattleActionsAtTargetPosition));
     this.paramsComputationDelegates.Add("NumberOfPositiveGroundEffectsAtTargetPosition", new BattleTargetingController.ParamComputationDelegate(this.GetNumberOfPositiveGroundBattleActionsAtTargetPosition));
     this.paramsComputationDelegates.Add("IsMyBattleEffectAppliedOnTarget", new BattleTargetingController.ParamComputationDelegate(this.IsMyBattleEffectAppliedOnTarget));
     this.paramsComputationDelegates.Add("IsTargetUnitClassMelee", new BattleTargetingController.ParamComputationDelegate(this.GetIsTargetUnitClassMelee));
     this.paramsComputationDelegates.Add("IsTargetUnitClassCavalry", new BattleTargetingController.ParamComputationDelegate(this.GetIsTargetUnitClassCavalry));
     this.paramsComputationDelegates.Add("IsTargetUnitClassRanged", new BattleTargetingController.ParamComputationDelegate(this.GetIsTargetUnitClassRanged));
     this.paramsComputationDelegates.Add("IsTargetUnitClassFlying", new BattleTargetingController.ParamComputationDelegate(this.GetIsTargetUnitClassFlying));
     this.paramsComputationDelegates.Add("IsTargetUnitClassSupport", new BattleTargetingController.ParamComputationDelegate(this.GetIsTargetUnitClassSupport));
     this.paramsComputationDelegates.Add("IsTargetUnitClassInterceptor", new BattleTargetingController.ParamComputationDelegate(this.GetIsTargetUnitClassInterceptor));
     this.paramsComputationDelegates.Add("IsTargetUnitClassFrigate", new BattleTargetingController.ParamComputationDelegate(this.GetIsTargetUnitClassFrigate));
     this.paramsComputationDelegates.Add("IsTargetUnitClassJuggernaut", new BattleTargetingController.ParamComputationDelegate(this.GetIsTargetUnitClassJuggernaut));
     this.paramsComputationDelegates.Add("IsTargetUnitClassSubmersible", new BattleTargetingController.ParamComputationDelegate(this.GetIsTargetUnitClassSubmersible));
     this.paramsComputationDelegates.Add("IsTargetTransportShipUnit", new BattleTargetingController.ParamComputationDelegate(this.GetIsTargetTransportShipUnit));
     this.paramsComputationDelegates.Add("DoesTargetPlaysBeforeMe", new BattleTargetingController.ParamComputationDelegate(this.GetDoesTargetPlaysBeforeMe));
     this.paramsComputationDelegates.Add("RatioOfOpponentsAroundTargetPosition", new BattleTargetingController.ParamComputationDelegate(this.GetRatioOfOpponentsAroundTargetPosition));
     this.paramsComputationDelegates.Add("RatioOfOpponentsAroundTargetPositionWhoPlayAfterMe", new BattleTargetingController.ParamComputationDelegate(this.RatioOfOpponentsAroundTargetPositionWhoPlayAfterMe));
     this.paramsComputationDelegates.Add("IsNoEnemyAroundTargetPositionWhoPlaysAfterMe", new BattleTargetingController.ParamComputationDelegate(this.IsNoEnemyAroundTargetPositionWhoPlaysAfterMe));
     this.paramsComputationDelegates.Add("RatioOfAlliesAroundTargetPosition", new BattleTargetingController.ParamComputationDelegate(this.GetRatioOfAlliesAroundTargetPosition));
     this.paramsComputationDelegates.Add("IsTargetHigher", new BattleTargetingController.ParamComputationDelegate(this.GetIsTargetHigher));
     this.paramsComputationDelegates.Add("IsTargetLower", new BattleTargetingController.ParamComputationDelegate(this.GetIsTargetLower));
     this.paramsComputationDelegates.Add("RatioOfTargetAltitudeToMyAltitude", new BattleTargetingController.ParamComputationDelegate(this.GetRatioOfTargetAltitudeToMyAltitude));
     this.paramsComputationDelegates.Add("RatioMyAttackToTargetDefense", new BattleTargetingController.ParamComputationDelegate(this.GetRatioMyAttackToTargetDefense));
     this.paramsComputationDelegates.Add("RatioMyDefenseToTargetAttack", new BattleTargetingController.ParamComputationDelegate(this.GetRatioMyDefenseToTargetAttack));
     this.paramsComputationDelegates.Add("RatioOfHigherNeighboursAroundTargetPosition", new BattleTargetingController.ParamComputationDelegate(this.GetRatioOfHigherNeighboursAroundTargetPosition));
     this.paramsComputationDelegates.Add("RatioOfLowerNeighboursAroundTargetPosition", new BattleTargetingController.ParamComputationDelegate(this.GetRatioOfLowerNeighboursAroundTargetPosition));
     this.paramsComputationDelegates.Add("RatioOfWalkableNeighboursAroundTargetPosition", new BattleTargetingController.ParamComputationDelegate(this.GetRatioOfWalkableNeighboursAroundTargetPosition));
     this.paramsComputationDelegates.Add("RatioOfImpassableNeighboursAroundTargetPosition", new BattleTargetingController.ParamComputationDelegate(this.GetRatioOfImpassableNeighboursAroundTargetPosition));
     this.paramsComputationDelegates.Add("RatioOfAllyTargettedNeighboursAroundTargetPosition", new BattleTargetingController.ParamComputationDelegate(this.GetRatioOfAllyTargettedNeighboursAroundTargetPosition));
     this.paramsComputationDelegates.Add("RatioOfEnemyTargettedNeighboursAroundTargetPosition", new BattleTargetingController.ParamComputationDelegate(this.GetRatioOfEnemyTargettedNeighboursAroundTargetPosition));
     this.paramsComputationDelegates.Add("TargetedByAlliesCount", new BattleTargetingController.ParamComputationDelegate(this.GetTargetedByAlliesCount));
     this.paramsComputationDelegates.Add("TargetedByAlliesWithMyBodyCount", new BattleTargetingController.ParamComputationDelegate(this.GetTargetedByAlliesWithMyBodyCount));
     this.paramsComputationDelegates.Add("NumberOfAliveOpponents", new BattleTargetingController.ParamComputationDelegate(this.GetNumberOfAliveOpponents));
     this.paramsComputationDelegates.Add("OpponentsDebufferRatio", new BattleTargetingController.ParamComputationDelegate(this.GetOpponentsDebufferRatio));
     this.paramsComputationDelegates.Add("RatioOfOpponentsToAllies", new BattleTargetingController.ParamComputationDelegate(this.RatioOfOpponentsToAllies));
     this.paramsComputationDelegates.Add("RatioOfAlliesToOpponents", new BattleTargetingController.ParamComputationDelegate(this.RatioOfAlliesToOpponents));
     this.filtersComputationDelegates = new Dictionary <StaticString, BattleTargetingController.FilterComputationDelegate>();
     this.filtersComputationDelegates.Add("CanAttackWithoutMoving", new BattleTargetingController.FilterComputationDelegate(this.CanAttackWithoutMoving));
     this.filtersComputationDelegates.Add("IsEnemy", new BattleTargetingController.FilterComputationDelegate(this.IsEnemy));
     this.filtersComputationDelegates.Add("IsAlly", new BattleTargetingController.FilterComputationDelegate(this.IsAlly));
     this.filtersComputationDelegates.Add("IsGroundUnit", new BattleTargetingController.FilterComputationDelegate(this.IsGroundUnit));
     this.filtersComputationDelegates.Add("IsFreePosition", new BattleTargetingController.FilterComputationDelegate(this.IsFreePosition));
     this.filtersComputationDelegates.Add("IsUnit", new BattleTargetingController.FilterComputationDelegate(this.IsUnit));
     this.filtersComputationDelegates.Add("IsNotMe", new BattleTargetingController.FilterComputationDelegate(this.IsNotMe));
     this.filtersComputationDelegates.Add("IAmCombatUnit", new BattleTargetingController.FilterComputationDelegate(this.IAmCombatUnit));
     this.filtersComputationDelegates.Add("IAmInLightForm", new BattleTargetingController.FilterComputationDelegate(this.IAmInLightForm));
     this.filtersComputationDelegates.Add("IAmInDarkForm", new BattleTargetingController.FilterComputationDelegate(this.IAmInDarkForm));
     this.filtersComputationDelegates.Add("AlliesArePresent", new BattleTargetingController.FilterComputationDelegate(this.AlliesArePresent));
     this.filtersComputationDelegates.Add("IsTargetWithinMovementRange", new BattleTargetingController.FilterComputationDelegate(this.IsTargetWithinMovementRange));
     this.filtersComputationDelegates.Add("CanTargetBeDebuffed", new BattleTargetingController.FilterComputationDelegate(this.CanTargetBeDebuffed));
     this.filtersComputationDelegates.Add("IsTargetNotMindControlled", new BattleTargetingController.FilterComputationDelegate(this.IsTargetNotMindControlled));
     this.filtersComputationDelegates.Add("AnyAliveOpponents", new BattleTargetingController.FilterComputationDelegate(this.AnyAliveOpponents));
     this.filtersComputationDelegates.Add("IAmTransportShip", new BattleTargetingController.FilterComputationDelegate(this.IAmTransportShip));
     this.filtersComputationDelegates.Add("IAmNotTransportShip", new BattleTargetingController.FilterComputationDelegate(this.IAmNotTransportShip));
 }
示例#43
0
        public Parser()
        {
            databases = Databases.getDefault();

            currentBlock = new BlockParser(databases, manager);
        }