public IValidationResults ValidateString(string json) { try { var configRoot = JObject.Parse(json); var isValid = configRoot.IsValid(_rootSchema, out _errors); if (!isValid) { return(new InvalidResults(_errors.ToList())); } _config = JsonConvert.DeserializeObject <ConfigRoot>(json); return(new ValidResults <ConfigRoot>(_config)); } catch { return(new InvalidResults(_errors.ToList())); } }
public void Put_returns_400_if_component_name_contains_invalid_characters() { var entity = _repository.Create(); entity.Contents = new ConfigRoot { ComponentName = "taboUli", Data = new ConfigNode { Name = "tabouli", Value = "salad" } }; _repository.Add(entity); _repository.Save(); var configRoot = new ConfigRoot { ComponentName = "jsnsadnc sd 8d8*** sad8s7sagd ^Q^ G5asds", Data = new ConfigNode { Name = string.Empty, Value = string.Empty } }; IRequest request = new InMemoryRequest { HttpMethod = "PUT", Uri = new Uri("http://localhost/Config/tabouli") }; request.Headers["Content-Type"] = "application/json"; var length = WriteConfigRootToStream(request.Entity.Stream, configRoot); request.Headers["Content-Length"] = length.ToString(CultureInfo.InvariantCulture); var response = _host.ProcessRequest(request); Assert.AreEqual(400, response.StatusCode); }
/// <summary> /// Handles POST for creating new resource. /// </summary> /// <param name="config">Config root deserialized from JSON in request body</param> /// <returns> /// 409 Conflict - If config exists for component of same name already in repository /// 201 Created - If adding new config succeeds /// 500 Internal Server Error - If error occurs /// </returns> public OperationResult Post(ConfigRoot config) { _log.Debug("Entering ConfigHandler.Post()"); try { IJsonEntity <ConfigRoot> configEntity = _repository.Entities.FirstOrDefault( x => x.Contents.ComponentName.ToLower() == config.ComponentName.ToLower()); if (configEntity != null) { _log.Debug(string.Format("Returning 400 Bad Request for POST to component {0}", config.ComponentName)); return(new OperationResult.BadRequest()); } if (config.ComponentName == null || Regex.IsMatch(config.ComponentName, @"\W")) { _log.Debug(string.Format("Returning 400 Bad Request for POST to component {0}", config.ComponentName)); return(new OperationResult.BadRequest()); } configEntity = _repository.Create(); configEntity.Contents = config; _repository.Add(configEntity); _repository.Save(); var location = HttpHelper.GetLocation(_request.Uri, config.ComponentName); _response.Headers[HttpHelper.LocationHeader] = location.ToString(); return(new OperationResult.Created { ResponseResource = configEntity.Contents }); } catch (Exception exception) { _log.Error(string.Format("Error in Post for component '{0}': {1}", config != null ? config.ComponentName : null, exception)); throw; } }
public void TestQuoteAggregatorWithDisabledBa() { var config = new ConfigRoot { Brokers = new List <BrokerConfig> { new BrokerConfig() { Broker = Broker.Zb, Enabled = false }, new BrokerConfig { Broker = Broker.Hpx, Enabled = true } } }; var mConfigRepo = new Mock <IConfigStore>(); mConfigRepo.Setup(x => x.Config).Returns(config); var configStore = mConfigRepo.Object; var mZbBa = new Mock <IBrokerAdapter>(); mZbBa.Setup(x => x.Broker).Returns(Broker.Zb); var quotes1 = new List <Quote> { new Quote(Broker.Zb, QuoteSide.Ask, 500000, 0.1m, 0.1m), new Quote(Broker.Zb, QuoteSide.Ask, 500001, 0.01m, 0.01m) }; mZbBa.Setup(x => x.FetchQuotes()).Returns(quotes1); var mHpxBa = new Mock <IBrokerAdapter>(); mHpxBa.Setup(x => x.Broker).Returns(Broker.Hpx); mHpxBa.Setup(x => x.FetchQuotes()).Returns(new List <Quote>()); }
public void Execute(GameState state, ConfigRoot config, ICommandBuffer buffer) { var level = state.Level; if (TryKill(level.PlayerUnits, out var player)) { if (config.IsFeatureEnabled(Features.AutoHeal)) { buffer.Add(new HealUnitCommand(player.Id)); } state.Units.Add(UnitId, player); if (level.PlayerUnits.Count == 0) { buffer.Add(new FinishLevelCommand(false)); } } TryKill(level.EnemyUnits, out _); if (level.EnemyUnits.Count == 0) { buffer.Add(new FinishLevelCommand(true)); } }
private Split ParseSplit(string splitId) { XElement splitEl = ConfigRoot.Descendants("split") .Where(el => el.Attribute("id").Value.Inject(Parameters) == splitId).Single(); SplitType splitType = (SplitType)Enum.Parse(typeof(SplitType), splitEl.Attribute("type").Value.Inject(Parameters).ToUpper()); DataContainer container = GetDataContainer(splitEl.Attribute("dataContainer").Value.Inject(Parameters)); Split split; if (splitEl.Attribute("class") != null) { Type splitClassType = Helpers.ResolveType(splitEl.Attribute("class").Value.Inject(Parameters)); if (!typeof(Split).IsAssignableFrom(splitClassType)) { throw new WrapRecException(string.Format("Split type '{0}' should inherit class 'WrapRec.Data.Split'", splitClassType.Name)); } split = (Split)splitClassType.GetConstructor(Type.EmptyTypes).Invoke(null); } else { split = new FeedbackSimpleSplit(); } var setupParams = splitEl.Attributes().ToDictionary(a => a.Name.LocalName, a => a.Value.Inject(Parameters)); split.Id = splitId; split.Type = splitType; split.Container = container; split.SetupParameters = setupParams; // Splits are required to be Setuped when they are being created to make sure // the subSplits are being formed (this is necessary for CrossValidation) becuase // the number of experiments is determined based on the number of SubSplits split.Setup(); return(split); }
public void Should_be_able_to_serialize_root_with_multiple_value_children() { var originalRoot = new ConfigRoot(); originalRoot.ComponentName = "foo"; originalRoot.LastModified = new DateTime(2009, 11, 14); // JSON.NET loses the last 4 digits for Ticks when doing a round-trip conversion. Therefore, something like DateTime.Now would cause this test to fail. var node = new ConfigNode(); node.Name = "N1"; node.Children = new List <ConfigNode> { CreateValueNode(1), CreateValueNode(2), CreateValueNode(3), CreateValueNode(4) }; originalRoot.Data = node; string json = JsonConvert.SerializeObject(originalRoot); var deserializedRoot = JsonConvert.DeserializeObject <ConfigRoot>(json); Assert.IsTrue(_objectComparer.Compare(originalRoot, deserializedRoot).AreEqual); }
public bool IsValid(GameState state, ConfigRoot config) { if (!state.Items.TryGetValue(Id, out var item)) { return(false); } var upgradePrices = GetUpgradePrices(config, item.Descriptor); if (item.Level >= upgradePrices.Length) { return(false); } foreach (var pair in upgradePrices[item.Level]) { var res = pair.Key; var price = pair.Value; if (state.Resources.GetOrDefault(res) < price) { return(false); } } return(true); }
IEnumerator CheckDataLoaded(List <System.Object> allData, Action callback) { //Load Config Root and Config Mission bool isLoadRoot = false; bool isLoadMission = false; ConfigRoot rootConfig = null; ConfigMission missionConfig = null; while (rootConfig == null && isLoadRoot == false) { rootConfig = ConfigRoot.Instance; isLoadRoot = true; yield return(null); } while (missionConfig == null && isLoadMission == false) { missionConfig = ConfigMission.Instance; isLoadMission = true; yield return(null); } #if DevMode //add console GameObject console = GameObject.Find(m_consolePrefabName); if (console == null) { PrefabManager.Instance.InstantiateAsync <Transform> (m_consolePrefabName, (result) => { Debug.Log($"===========aas:{result.key}加载完成."); Debug.Log($"===========aas:{result.key}加载完成."); Transform tf = result.result as Transform; tf.gameObject.name = m_consolePrefabName; }); } #endif callback(); }
static NameValueCollection loadConfigJson(string appSettings) { if (ConfigRoot == null) { var builder = new ConfigurationBuilder() .SetBasePath(FileUtil.GetBasePath()) .AddJsonFile(appSettings, optional: false, reloadOnChange: true) .AddEnvironmentVariables(); ConfigRoot = builder.Build(); } languages = new Hashtable(StringComparer.OrdinalIgnoreCase); NameValueCollection cfg = new NameValueCollection(StringComparer.Ordinal); //Case sensitive foreach (var c in ConfigRoot.GetSection("appSettings").GetChildren()) { string key = c.Key; string value = c.Value; if (EnvVarReader.GetEnvironmentValue(key, out string envVarValue)) { value = envVarValue; } cfg.Add(key, value); } foreach (var c in ConfigRoot.GetSection("languages").GetChildren()) { languages[c.Key] = new Hashtable(StringComparer.OrdinalIgnoreCase); Hashtable language = (Hashtable)languages[c.Key]; foreach (var prop in c.GetChildren()) { language[prop.Key] = prop.Value; } } return(cfg); }
public void Should_be_able_to_serialize_root_with_multiple_value_children() { var originalRoot = new ConfigRoot(); originalRoot.ComponentName = "foo"; originalRoot.LastModified = new DateTime(2009, 11, 14); // JSON.NET loses the last 4 digits for Ticks when doing a round-trip conversion. Therefore, something like DateTime.Now would cause this test to fail. var node = new ConfigNode(); node.Name = "N1"; node.Children = new List<ConfigNode> { CreateValueNode(1), CreateValueNode(2), CreateValueNode(3), CreateValueNode(4) }; originalRoot.Data = node; string json = JsonConvert.SerializeObject(originalRoot); var deserializedRoot = JsonConvert.DeserializeObject<ConfigRoot>(json); Assert.IsTrue(_objectComparer.Compare(originalRoot, deserializedRoot).AreEqual); }
private void Setup(Dictionary <string, string> overrideParams) { try { XElement allExpEl = ConfigRoot.Descendants("experiments").Single(); Parameters = ConfigRoot.Descendants("param").ToDictionary(p => p.Attribute("name").Value, p => p.Attribute("value").Value); if (overrideParams != null) { foreach (string name in overrideParams.Keys) { if (!Parameters.ContainsKey(name)) { Console.WriteLine("Parameter {0} is not defined in the configuration file.", name); Environment.Exit(1); } Parameters[name] = overrideParams[name]; } } if (allExpEl.Attribute("verbosity") != null) { if (allExpEl.Attribute("verbosity").Value.Inject(Parameters).ToLower() == "trace") { Logger.Current = NLog.LogManager.GetLogger("traceLogger"); } else if (allExpEl.Attribute("verbosity").Value.Inject(Parameters).ToLower() == "warn") { Logger.Current = NLog.LogManager.GetLogger("warnLogger"); } } ResultSeparator = allExpEl.Attribute("separator") != null?allExpEl.Attribute("separator").Value.Replace("\\t", "\t") : ","; RunParallel = allExpEl.Attribute("parallel") != null && allExpEl.Attribute("parallel").Value == "true" ? true : false; bool subFolder = allExpEl.Attribute("subFolder") != null && allExpEl.Attribute("subFolder").Value == "true" ? true : false; string expFolder = subFolder ? DateTime.Now.ToString("wr yyyy-MM-dd HH.mm", CultureInfo.InvariantCulture) : ""; string rootPath = allExpEl.Attribute("resultsFolder") != null?allExpEl.Attribute("resultsFolder").Value.Inject(Parameters) : Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); ResultsFolder = Directory.CreateDirectory(Path.Combine(rootPath, expFolder)).FullName; JointFile = allExpEl.Attribute("jointResults") != null? Path.Combine(ResultsFolder, allExpEl.Attribute("jointResults").Value.Inject(Parameters)) : ""; XAttribute runAttr = allExpEl.Attribute("run"); IEnumerable <XElement> expEls = allExpEl.Descendants("experiment"); if (runAttr != null) { var expIds = runAttr.Value.Inject(Parameters).Split(','); _resultWriters = expIds.ToDictionary(eId => eId, eId => new StreamWriter(Path.Combine(ResultsFolder, eId + ".csv"))); _statWriters = expIds.ToDictionary(eId => eId, eId => new StreamWriter(Path.Combine(ResultsFolder, eId + ".splits.csv"))); _errorWriters = expIds.ToDictionary(eId => eId, eId => new StreamWriter(Path.Combine(ResultsFolder, eId + ".err.txt"))); _loggedSplits = expIds.ToDictionary(eId => eId, eId => new List <string>()); _loggedModels = expIds.ToDictionary(eId => eId, eId => new List <string>()); expEls = expEls.Where(el => expIds.Contains(el.Attribute("id").Value.Inject(Parameters))); ExperimentIds = expEls.Select(el => el.Attribute("id").Value.Inject(Parameters)).ToArray(); } Logger.Current.Info("Resolving experiments..."); Experiments = expEls.SelectMany(el => ParseExperiments(el)); } catch (Exception ex) { Logger.Current.Error("Error in setuping experiments or parsing the configuration file: {0}\n{1}\n", ex.Message, ex.StackTrace); //Environment.Exit(1); } }
/// <summary> /// adds to the next code number of the messages /// </summary> public void AddToMessageCode() { ConfigRoot.Element("MessageCode").Value = (GetMessageCode() + 1).ToString(); ConfigRoot.Save(ConfigPath); }
/// <summary> /// returns the code for the next message to be added /// </summary> /// <returns></returns> public int GetMessageCode() { return(int.Parse(ConfigRoot.Element("MessageCode").Value)); }
/// <summary> /// <see cref="MainModel"/> の新しいインスタンスを生成します。 /// </summary> public MainModel() { config = ConfigManager.GetDefaultConfigRoot(); collectedTweets = new List <Tweet>(); reportFileEncoidng = Encoding.GetEncoding(config.FuhaReports.EncodingName); }
public bool IsValid(GameState state, ConfigRoot config) => true;
public bool IsValid(GameState state, ConfigRoot config) => (Kind != Resource.Unknown) && (Count > 0);
public void Execute(GameState state, ConfigRoot config, ICommandBuffer buffer) { var health = config.Units[Descriptor].MaxHealth[0]; state.AddUnit(new UnitState(Descriptor, health).WithId(Id)); }
public static (string name, FarmConfig config) GetFirstAvailable(GameState state, ConfigRoot config) { foreach (var pair in config.Farming) { if (IsAvailable(pair.Key, state, config)) { return(pair.Key, pair.Value); } } return(string.Empty, null); }
public static (string name, EventConfig config) GetFirstActive(GameState state, ConfigRoot config) { foreach (var pair in config.Events) { if (IsActive(pair.Key, state, config)) { return(pair.Key, pair.Value); } } return(string.Empty, null); }
public bool IsValid(GameState state, ConfigRoot config) => state.Units.ContainsKey(Id);
public void Execute(GameState state, ConfigRoot config, ICommandBuffer buffer) { state.Time.PersistentOffset += Amount; }
public FileConfigRepository(ConvertService convert, string path) { _config = convert.FromJson <ConfigRoot>(File.ReadAllText(path)); }
LevelConfig FindLevelConfig(ConfigRoot config) => config.Levels.GetOrDefault(LevelDesc);
public void Should_be_able_to_serialize_empty_config_root() { var originalRoot = new ConfigRoot(); string json = JsonConvert.SerializeObject(originalRoot); var deserializedRoot = JsonConvert.DeserializeObject<ConfigRoot>(json); Assert.IsTrue(_objectComparer.Compare(originalRoot, deserializedRoot).AreEqual); }
public void Execute(GameState state, ConfigRoot config, ICommandBuffer buffer) { buffer.Add(new AddResourceCommand(Resource.Coins, 50)); buffer.Add(new AddUnitCommand(state.NewEntityId(), "weak_unit")); }
public void Execute(GameState state, ConfigRoot config, ICommandBuffer _) { var oldValue = state.Resources.GetOrDefault(Kind); state.Resources[Kind] = oldValue - Count; }
/// <summary> /// returns the code for the next test to be added /// </summary> /// <returns></returns> public int GetTestCode() { return(int.Parse(ConfigRoot.Element("TestCode").Value)); }
/// <summary> /// adds 1 to the code of the Config test code /// </summary> public void AddToTestCode() { ConfigRoot.Element("TestCode").Value = (GetTestCode() + 1).ToString(); ConfigRoot.Save(ConfigPath); }
private void CreateMockDurableCacheEntry(ConfigRoot configFromMockCache) { DurableMemoryRepositoryHelper.CreateMockDurableCacheEntry(configFromMockCache, _mockFileSystem, 1, TestPath); }
public static bool IsFarmigLevel(string desc, ConfigRoot config) { var scope = LevelUtils.GetScope(desc); return(config.Farming.ContainsKey(scope)); }
public bool IsValid(GameState state, ConfigRoot config) { return(!state.Events.ContainsKey(EventName) && EventLogic.IsCompleted(EventName, state, config)); }