/// <summary> /// Parses a XML node that contains information about a web node. /// </summary> /// <param name="node">A XML node containing the data to parse.</param> /// <param name="nodes">A <see cref="DictionaryValue"/> containing the collection of /// configuration nodes.</param> /// <remarks> /// The <paramref name="nodes"/> is used to store the nodes that is parsed by this class. /// </remarks> public void Parse(XmlNode node, DictionaryValue nodes) { XmlNode xml_web_node; DictionaryValue<ContentGroupNode> content_groups; if (GetNode<ContentGroupNode>(NohrosConfiguration.kContentGroupsNodeName ,NohrosConfiguration.kContentGroupNodeTree ,nodes ,node ,out xml_web_node ,out content_groups)) { DictionaryValue<RepositoryNode> repositories = (DictionaryValue <RepositoryNode>)nodes[NohrosConfiguration.kRepositoryNodeTree]; foreach (XmlNode n in xml_web_node.ChildNodes) { if (string.Compare(n.Name, "group", StringComparison.OrdinalIgnoreCase) == 0) { string name; if (!GetAttributeValue(n, "name", out name)) Thrower.ThrowConfigurationException("[Parse Nohros.Configuration.WebNode]", string.Format(StringResources.Config_MissingAt, "name", NohrosConfiguration.kContentGroupNodeTree)); ContentGroupNode content_group = new ContentGroupNode(name); content_group.Parse(n, repositories); content_groups[ContentGroupKey(content_group.Name, (content_group.BuildType == BuildType.Release) ? "release" : "build", content_group.MimeType)] = content_group; } } } }
public InventoryError AddItem(string label, DateTime expirationDate, InventoryItemType itemType) { lock (m_lock) { if (!InventoryItem.ValidLabelStatic(label)) { return(new InventoryError(Severity.Error, ErrorCode.EmptyLabelError, null)); } InventoryItem item = new InventoryItem(label, expirationDate, itemType); if (m_inventory.ContainsKey(label)) { return(new InventoryError(Severity.Error, ErrorCode.ItemWithLabelExistsError, new string[] { label })); } DictionaryValue value = new DictionaryValue(item, false); m_inventory.Add(item.Label, value); if (item.Expired()) { value.ExpirationReported = true; SendNotification(new NotificationMessage(item, new InventoryError(Severity.Error, ErrorCode.ExpiredItemWarning, new string[] { label }))); } return(new InventoryError(Severity.Info, ErrorCode.Success, null)); } }
public void DictForCacheNotKept() { var loop1 = new Dictionary <object, object>() { { "a", 10 } }; var loop2 = new Dictionary <object, object>() { { "a", 20 } }; var loopdict = new ObjectValue(new Dictionary <object, object>[] { loop1, loop2 }); var dictEval = new Tuple <IExpression, IExpression>[] { new Tuple <IExpression, IExpression>(new StringValue("hi"), new VariableValue("a")) }; var dict = new DictionaryValue(dictEval); var lookup = new IndexerRefExpression(dict, new StringValue("hi")); var statement1 = new ExpressionStatement(lookup); var exprStatement = new ListOfStatementsExpression(new IStatement[] { statement1 }); var forLoop = new FunctionExpression("for", loopdict, exprStatement); var c = new RootContext(); var r = forLoop.Evaluate(c); Assert.AreEqual(20, r, "for loop with nothing in it"); }
private static object ToRawValue(LogEventPropertyValue logEventValue) { // Special-case a few types of LogEventPropertyValue that allow us to maintain better type fidelity. // For everything else take the default string rendering as the data. ScalarValue scalarValue = logEventValue as ScalarValue; if (scalarValue != null) { return(scalarValue.Value); } SequenceValue sequenceValue = logEventValue as SequenceValue; if (sequenceValue != null) { object[] arrayResult = sequenceValue.Elements.Select(e => ToRawScalar(e)).ToArray(); if (arrayResult.Length == sequenceValue.Elements.Count) { // All values extracted successfully, it is a flat array of scalars return(arrayResult); } } StructureValue structureValue = logEventValue as StructureValue; if (structureValue != null) { IDictionary <string, object> structureResult = new Dictionary <string, object>(structureValue.Properties.Count); foreach (var property in structureValue.Properties) { structureResult[property.Name] = ToRawScalar(property.Value); } if (structureResult.Count == structureValue.Properties.Count) { if (structureValue.TypeTag != null) { structureResult["$type"] = structureValue.TypeTag; } return(structureResult); } } DictionaryValue dictionaryValue = logEventValue as DictionaryValue; if (dictionaryValue != null) { IDictionary <string, object> dictionaryResult = dictionaryValue.Elements .Where(kvPair => kvPair.Key.Value is string) .ToDictionary(kvPair => (string)kvPair.Key.Value, kvPair => ToRawScalar(kvPair.Value)); if (dictionaryResult.Count == dictionaryValue.Elements.Count) { return(dictionaryResult); } } // Fall back to string rendering of the value return(logEventValue.ToString()); }
public void It_Should_Dereference_A_Nested_Dictionary() { // Arrange var dict3 = new Dictionary<String, IExpressionConstant> { {"str", new StringValue("Dict 3")}, }; DictionaryValue dictValue3 = new DictionaryValue(dict3); var dict2 = new Dictionary<String, IExpressionConstant> { {"dict3", dictValue3} }; DictionaryValue dictValue2 = new DictionaryValue(dict2); var dict = new Dictionary<String, IExpressionConstant> { {"dict2", dictValue2} }; DictionaryValue dictValue = new DictionaryValue(dict); ITemplateContext ctx = new TemplateContext() .DefineLocalVariable("dict1", dictValue); // Act var result = RenderingHelper.RenderTemplate("Result : {{dict1.dict2.dict3.str}}->{% if dict1.dict2.dict3.str == \"Dict 2\" %}Dict2{% elseif dict1.dict2.dict3.str == \"Dict 3\" %}Dict3{%endif%}", ctx); // Assert Assert.That(result, Is.EqualTo("Result : Dict 3->Dict3")); }
private static void WriteDictionaryValue(string key, DictionaryValue dictionaryValue, IDictionary <string, string> properties) { foreach (var eventProperty in dictionaryValue.Elements) { WriteValue(key + "." + eventProperty.Key.Value, eventProperty.Value, properties); } }
/// <summary> /// Initializes a new instance of the <see cref="Configuration"/> class /// that is empty. /// </summary> public Configuration() { properties_ = new DictionaryValue(); repositories_ = new RepositoriesNode(); providers_ = new ProvidersNode(); xml_elements_ = new XmlElementsNode(); }
async Task IDictionaryRepository.Append(string key, byte[] value) { using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { var valueObj = new DictionaryValue { Key = key, Value = value }; var dictionaryKey = await Context.DictionaryKeys.SingleOrDefaultAsync(dk => dk.Key == key).ConfigureAwait(false); if (dictionaryKey == null) { await Context.DictionaryKeys.AddAsync(new DictionaryKey { Key = key, DictionaryValues = new List <DictionaryValue>() { valueObj } }) .ConfigureAwait(false); await Context.SaveChangesAsync(); scope.Complete(); return; } await Context.DictionaryValues.AddAsync(valueObj) .ConfigureAwait(false); dictionaryKey.UpdatedDate = DateTime.Now; await Context.SaveChangesAsync() .ConfigureAwait(false); scope.Complete(); } }
/// <summary> /// Initializes a new instance of the /// <see cref="AbstractConfigurationBuilder{T}"/> class. /// </summary> protected AbstractConfigurationBuilder() { properties_ = new DictionaryValue(); repositories_ = new RepositoriesNode(); providers_ = new ProvidersNode(); xml_elements_ = new XmlElementsNode(); }
/// <summary> /// Convert from <see cref="PropertyBag"/> to <see cref="DictionaryValue"/>. /// </summary> /// <param name="propertyBag"><see cref="PropertyBag"/> to convert.</param> /// <returns>Converted <see cref="DictionaryValue"/>.</returns> public static DictionaryValue AsDictionaryValue(this PropertyBag propertyBag) { var dictionaryValue = new DictionaryValue(); propertyBag.Values.ForEach(kvp => dictionaryValue.Object.Add(kvp.Key, kvp.Value)); return(dictionaryValue); }
public static void FormatDictionaryValue(LogEvent logEvent, TextWriter builder, DictionaryValue value, string propertyName) { ColorCodeContext.WriteOverridden(builder, logEvent, ColorCode.Value, "{"); var isFirst = true; foreach (var element in value.Elements) { if (!isFirst) { ColorCodeContext.WriteOverridden(builder, logEvent, ColorCode.Value, ", "); } isFirst = false; ColorCodeContext.WriteOverridden(builder, logEvent, ColorCode.Value, "["); using (ColorCodeContext.StartOverridden(builder, logEvent, ColorCode.StringValue)) { Format(logEvent, element.Key, builder, null, propertyName); } ColorCodeContext.WriteOverridden(builder, logEvent, ColorCode.Value, "]="); Format(logEvent, element.Value, builder, null, propertyName); } ColorCodeContext.WriteOverridden(builder, logEvent, ColorCode.Value, "}"); }
/// <summary> /// Convert from <see cref="DictionaryValue"/> to <see cref="PropertyBag"/>. /// </summary> /// <param name="dictionaryValue"><see cref="DictionaryValue"/> to convert.</param> /// <returns>Converted <see cref="PropertyBag"/>.</returns> public static PropertyBag AsPropertyBag(this DictionaryValue dictionaryValue) { var propertyBag = new PropertyBag(); dictionaryValue.Object.ForEach(kvp => propertyBag.Values.Add(kvp.Key, kvp.Value)); return(propertyBag); }
public void CreateEntityWithPropertiesShouldSupportAzureTableTypesForDictionary() { var messageTemplate = "{Dictionary}"; var dict1 = new DictionaryValue(new List <KeyValuePair <ScalarValue, LogEventPropertyValue> > { new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d1k1"), new ScalarValue("d1k1v1")), new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d1k2"), new ScalarValue("d1k2v2")), new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d1k3"), new ScalarValue("d1k3v3")), }); var dict2 = new DictionaryValue(new List <KeyValuePair <ScalarValue, LogEventPropertyValue> > { new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d2k1"), new ScalarValue("d2k1v1")), new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d2k2"), new ScalarValue("d2k2v2")), new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d2k3"), new ScalarValue("d2k3v3")), }); var dict0 = new DictionaryValue(new List <KeyValuePair <ScalarValue, LogEventPropertyValue> > { new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d1"), dict1), new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d2"), dict2), new KeyValuePair <ScalarValue, LogEventPropertyValue>(new ScalarValue("d0"), new ScalarValue(0)) }); var properties = new List <LogEventProperty> { new LogEventProperty("Dictionary", dict0) }; var template = new MessageTemplateParser().Parse(messageTemplate); var logEvent = new Events.LogEvent(DateTime.Now, LogEventLevel.Information, null, template, properties); var entity = AzureTableStorageEntityFactory.CreateEntityWithProperties(logEvent, null, null, new PropertiesKeyGenerator()); Assert.Equal(3 + properties.Count, entity.Properties.Count); Assert.Equal("[(\"d1\": [(\"d1k1\": \"d1k1v1\"), (\"d1k2\": \"d1k2v2\"), (\"d1k3\": \"d1k3v3\")]), (\"d2\": [(\"d2k1\": \"d2k1v1\"), (\"d2k2\": \"d2k2v2\"), (\"d2k3\": \"d2k3v3\")]), (\"d0\": 0)]", entity.Properties["Dictionary"].StringValue); }
/// <summary> /// Add the value into the specified sub-tree. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expiration"></param> /// <param name="node"></param> private void Add(TKey key, TValue value, DateTime expiration, ref TTNode node, object parentLocker) { if (node == null) { lock (parentLocker) if (node == null) { node = new TTNode(expiration); } } if (expiration < node.ExpirationTime) { Add(key, value, expiration, ref node.lNode, node); } else if (expiration > node.ExpirationTime) { Add(key, value, expiration, ref node.rNode, node); } else { lock (node) { // add the item in to the current node Items[key] = new DictionaryValue() { treeNode = node, listNode = node.AddFirst(new KeyValuePair <TKey, TValue>(key, value)) }; } } }
public DictionaryValue(DictionaryValue other) : this(CNTKLibPINVOKE.new_DictionaryValue__SWIG_8(DictionaryValue.getCPtr(other)), true) { if (CNTKLibPINVOKE.SWIGPendingException.Pending) { throw CNTKLibPINVOKE.SWIGPendingException.Retrieve(); } }
/// <summary> /// Initializes a new instance of the <see cref="Configuration"/> class. /// </summary> public Configuration(IConfigurationBuilder <IConfiguration> builder) { properties_ = builder.Properties; repositories_ = builder.Repositories; providers_ = builder.Providers; xml_elements_ = builder.XmlElements; }
/// <summary> /// Recursively gets the dynamic properties. /// </summary> /// <param name="node"> /// A XML node containing the dynamic properties. /// </param> /// <param name="path"> /// The path to the node value. /// </param> /// <remarks> /// If the namespace of the property is not defined it will be assigned to /// the default namespace. /// </remarks> void GetProperties(XmlNode node, string path) { if (node != null && node.ChildNodes.Count > 0) { foreach (XmlNode inner_node in node.ChildNodes) { if (inner_node.NodeType == XmlNodeType.Element) { if (inner_node.ChildNodes.Count > 0) { GetProperties(inner_node, path + "." + inner_node.Name); } else { XmlAttributeCollection properties = inner_node.Attributes; if (properties.Count == 0) { return; } DictionaryValue keys = new DictionaryValue(); foreach (XmlAttribute property in properties) { keys.SetString(property.Name, property.Value); } properties_[path] = keys; } } } } }
public void Add() { DictionaryValue dict = new DictionaryValue(); CommonNodeParser common = new CommonNodeParser(); dict.Add("common.providers.commondataprovider", new DataProviderNode("commondataprovider", "System.String")); Assert.Pass(); }
public void Get() { DictionaryValue dict = FillDictionary(); DictionaryValue dict2 = dict["common.providers"] as DictionaryValue; Assert.IsNotNull(dict2); Assert.AreEqual(4, dict2.Size); }
/// <summary> /// Copies the configuration data from the specified /// <see cref="Configuration"/> object. /// </summary> /// <param name="configuration"> /// A <see cref="Configuration"/> object that contains the /// configuration data to be copied. /// </param> public void CopyFrom(Configuration configuration) { providers_ = configuration.providers_; repositories_ = configuration.repositories_; xml_elements_ = configuration.xml_elements_; log_level_ = configuration.log_level_; properties_ = configuration.properties_; }
public void Add(string key, DictionaryValue value) { CNTKLibPINVOKE.CNTKDictionary_Add__SWIG_1(swigCPtr, key, DictionaryValue.getCPtr(value)); if (CNTKLibPINVOKE.SWIGPendingException.Pending) { throw CNTKLibPINVOKE.SWIGPendingException.Retrieve(); } }
bool TryConvertEnumerable(object value, Destructuring destructuring, Type valueType, out LogEventPropertyValue result) { if (value is IEnumerable enumerable) { // Only dictionaries with 'scalar' keys are permitted, as // more complex keys may not serialize to unique values for // representation in sinks. This check strengthens the expectation // that resulting dictionary is representable in JSON as well // as richer formats (e.g. XML, .NET type-aware...). // Only actual dictionaries are supported, as arbitrary types // can implement multiple IDictionary interfaces and thus introduce // multiple different interpretations. if (TryGetDictionary(value, valueType, out var dictionary)) { result = new DictionaryValue(MapToDictionaryElements(dictionary, destructuring)); return true; IEnumerable<KeyValuePair<ScalarValue, LogEventPropertyValue>> MapToDictionaryElements(IDictionary dictionaryEntries, Destructuring destructure) { var count = 0; foreach (DictionaryEntry entry in dictionaryEntries) { if (++count > _maximumCollectionCount) { yield break; } var pair = new KeyValuePair<ScalarValue, LogEventPropertyValue>( (ScalarValue)_depthLimiter.CreatePropertyValue(entry.Key, destructure), _depthLimiter.CreatePropertyValue(entry.Value, destructure)); if (pair.Key.Value != null) yield return pair; } } } result = new SequenceValue(MapToSequenceElements(enumerable, destructuring)); return true; IEnumerable<LogEventPropertyValue> MapToSequenceElements(IEnumerable sequence, Destructuring destructure) { var count = 0; foreach (var element in sequence) { if (++count > _maximumCollectionCount) { yield break; } yield return _depthLimiter.CreatePropertyValue(element, destructure); } } } result = null; return false; }
static DictionaryValue FillDictionary() { DictionaryValue dict = new DictionaryValue(); CommonNodeParser common = new CommonNodeParser(); dict.Add("common.providers.commondataprovider", new DataProviderNode("commondataprovider", "System.String")); dict.Add("common.providers.testdataprovider", new DataProviderNode("testdataprovider", "System.String")); dict.Add("common.providers.nohrosdataprovider", new DataProviderNode("nohrosdataprovider", "System.String")); dict.Add("common.providers.userdataprovider", new DataProviderNode("userdataprovider", "System.String")); return dict; }
public void Insert(DicValueModel model) { var entity = new DictionaryValue(); entity.DictionaryId = model.DicId; entity.Code = model.Code; entity.Value = model.Value; _dicManager.InsertOrUpdate(entity); }
public List <GridColumn> GetSecondaryGridColumns() { Allowances = DicValuesRepo.WithDetails(x => x.ValueType).Where(x => x.ValueType.ValueTypeFor == ValueTypeModules.AllowanceType).ToList(); List <GridColumn> earningsColumns = new List <GridColumn>(); earningsColumns.Add(new GridColumn { Field = "getBasicSalaries", HeaderText = "Basic Salary", TextAlign = TextAlign.Center, MinWidth = "40" }); for (int i = 0; i < Allowances.Count; i++) { DictionaryValue allowance = Allowances[i]; string camelCaseName = allowance.Value; camelCaseName = camelCaseName.Replace(" ", ""); camelCaseName = char.ToLowerInvariant(camelCaseName[0]) + camelCaseName.Substring(1); earningsColumns.Add(new GridColumn() { Field = $"{camelCaseName}_Value", HeaderText = $"{Allowances[i].Value}", TextAlign = TextAlign.Center, MinWidth = "50" }); } List <GridColumn> deductionsColumns = new List <GridColumn>() { new GridColumn() { Field = "gosiValue", HeaderText = "GOSI", TextAlign = TextAlign.Center, MinWidth = "50" }, new GridColumn() { Field = "loansValue", HeaderText = "Loans", TextAlign = TextAlign.Center, MinWidth = "50" }, new GridColumn() { Field = "leavesValue", HeaderText = "Leaves", TextAlign = TextAlign.Center, MinWidth = "50" }, }; List <GridColumn> gridColumns = new List <GridColumn>() { new GridColumn() { Field = "totalEmployees", HeaderText = "Total Employees", TextAlign = TextAlign.Center, MinWidth = "50" }, new GridColumn { Field = "", HeaderText = "Earnings", TextAlign = TextAlign.Center, MinWidth = "40", Columns = earningsColumns }, new GridColumn { Field = "", HeaderText = "Deductions", TextAlign = TextAlign.Center, MinWidth = "40", Columns = deductionsColumns } }; return(gridColumns); }
public void DictionaryWithScalarKeyFormatsAsAnObject() { var dict = new DictionaryValue(new Dictionary <ScalarValue, TemplatePropertyValue> { { new ScalarValue(12), new ScalarValue(345) } }); var f = Format(dict); Assert.Equal("{\"12\":345}", f); }
public bool AreNotEqual(DictionaryValue other) { bool ret = CNTKLibPINVOKE.DictionaryValue_AreNotEqual(swigCPtr, DictionaryValue.getCPtr(other)); if (CNTKLibPINVOKE.SWIGPendingException.Pending) { throw CNTKLibPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public static DictionaryValue Load(string filename) { DictionaryValue ret = new DictionaryValue(CNTKLibPINVOKE.DictionaryValue_Load(filename), true); if (CNTKLibPINVOKE.SWIGPendingException.Pending) { throw CNTKLibPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
/// <summary> /// Copies the configured data from the specified /// <see cref="AbstractConfigurationBuilder{T}"/> object. /// </summary> /// <param name="builder"> /// A <see cref="AbstractConfigurationBuilder{T}"/> object that contains the /// configuration data to be copied. /// </param> /// <remarks> /// A <see cref="AbstractConfigurationBuilder{T}"/> object configured with the /// data copied from <paramref name="builder"/>. /// </remarks> public IConfigurationBuilder <T> CopyFrom( AbstractConfigurationBuilder <T> builder) { properties_ = builder.properties_; providers_ = builder.providers_; log_level_ = builder.log_level_; repositories_ = builder.repositories_; xml_elements_ = builder.xml_elements_; return(this); }
static JToken ConvertDictionaryValue(DictionaryValue dict) { JObject obj = new JObject(); foreach (KeyValuePair <ScalarValue, LogEventPropertyValue> kvp in dict.Elements) { string propname = kvp.Key.Value?.ToString() ?? "<<null>>"; obj.Add(propname, ConvertPropertyValue(kvp.Value)); } return(obj); }
private IDictionary <string, object> VisitDictionaryValue(DictionaryValue dictionary) { var dic = new Dictionary <string, object>(); foreach (var element in dictionary.Elements) { dic[element.Key.Value.ToString()] = this.Visit(element.Value); } return(dic); }
static DictionaryValue FillDictionary() { DictionaryValue dict = new DictionaryValue(); CommonNodeParser common = new CommonNodeParser(); dict.Add("common.providers.commondataprovider", new DataProviderNode("commondataprovider", "System.String")); dict.Add("common.providers.testdataprovider", new DataProviderNode("testdataprovider", "System.String")); dict.Add("common.providers.nohrosdataprovider", new DataProviderNode("nohrosdataprovider", "System.String")); dict.Add("common.providers.userdataprovider", new DataProviderNode("userdataprovider", "System.String")); return(dict); }
public void Add() { DictionaryValue <StringValue> dict = new DictionaryValue <StringValue>(); dict.Add("bu.x", new StringValue("x")); StringValue x = dict["bu.x"]; Assert.IsNotNull(x); Assert.AreEqual(x, "x"); }
public void A_Dict_With_No_Value_Should_Have_Zero_Length() { // Arrange DictionaryValue dictValue = new DictionaryValue(new Dictionary<String,Option<IExpressionConstant>>()); var filter = new SizeFilter(); // Act var result = filter.Apply(new TemplateContext(), dictValue).SuccessValue<NumericValue>(); // Assert Assert.That(result.Value, Is.EqualTo(0)); }
public void It_Should_Allow_A_Variable_With_Index() { // Arrange ITemplateContext ctx = new TemplateContext().WithAllFilters(); DictionaryValue dict = new DictionaryValue(new Dictionary<String, IExpressionConstant> { { "foo", NumericValue.Create(33) } }); ctx.DefineLocalVariable("bar", dict); var template = LiquidTemplate.Create("{{ 1 | plus: bar.foo}}"); // Act String result = template.Render(ctx); Logger.Log(result); // Assert Assert.That(result, Is.EqualTo("34")); }
public void It_Should_Dereference_A_Dictionary() { // Arrange var dict = new Dictionary<String, IExpressionConstant> { {"string1", new StringValue("a string")}, {"string2", NumericValue.Create(123)}, {"string3", NumericValue.Create(456m)} }; DictionaryValue dictValue = new DictionaryValue(dict); // Assert Assert.That(dictValue.ValueAt("string1").Value, Is.EqualTo(dict["string1"].Value)); }
public void Dictionaries() { IDictionary<string, string> values1 = new Dictionary<string, string>(); IDictionary<string, string> same = new Dictionary<string, string>(); IDictionary<string, string> longer = new Dictionary<string, string>(); IDictionary<string, string> shorter = new Dictionary<string, string>(); IDictionary<string, string> different1 = new Dictionary<string, string>(); IDictionary<string, string> different2 = new Dictionary<string, string>(); IDictionary<string, string> different3 = new Dictionary<string, string>(); values1.Add("a", "1"); values1.Add("b", ""); values1.Add("c", null); same.Add("a", "1"); same.Add("b", ""); same.Add("c", null); longer.Add("a", "1"); longer.Add("b", ""); longer.Add("c", null); longer.Add("d", "4"); shorter.Add("a", "1"); shorter.Add("b", ""); different1.Add("a", "1"); different1.Add("b", "2"); different1.Add("c", null); different2.Add("a", "1"); different2.Add("b", ""); different2.Add("c", "3"); different3.Add("a", "1"); different3.Add("b", null); different3.Add("c", null); DictionaryValue value1 = new DictionaryValue(); DictionaryValue value2 = new DictionaryValue(); DictionaryValue value3 = new DictionaryValue(); DictionaryValue value4 = new DictionaryValue(); DictionaryValue value5 = new DictionaryValue(); DictionaryValue value6 = new DictionaryValue(); DictionaryValue value7 = new DictionaryValue(); DictionaryValue value8 = new DictionaryValue(); value1.Values = values1; value2.Values = same; value3.Values = longer; value4.Values = shorter; value5.Values = different1; value6.Values = different2; value7.Values = different3; value8.Values = null; Assert.That(value1 == value2); Assert.That(value1 != value3); Assert.That(value1 != value4); Assert.That(value1 != value5); Assert.That(value1 != value6); Assert.That(value1 != value7); Assert.That(value1 != value8); }
public void It_Should_Measure_The_Size_Of_A_Dictionary() { // Arrange var dict = new Dictionary<String, IExpressionConstant> { {"string1", new StringValue("a string")}, {"string2", NumericValue.Create(123)}, {"string3", NumericValue.Create(456m)} }; DictionaryValue dictValue = new DictionaryValue(dict); SizeFilter sizeFilter = new SizeFilter(); // Act var result = sizeFilter.Apply(new TemplateContext(), dictValue).SuccessValue<NumericValue>(); // Assert Assert.That(result.Value, Is.EqualTo(dict.Keys.Count())); }
private void Update() { ColumnDefinitions.Clear(); Children.Clear(); var idictionary = DataContext as IDictionary; if (idictionary != null) { var index = 0; foreach (string key in idictionary.Keys) { var dictionaryValue = new DictionaryValue { IDictionary = idictionary, Key = key }; ColumnDefinitions.Add(new ColumnDefinition()); var dictionaryValueControl = new IDictionaryValueControl { DataContext = dictionaryValue }; Children.Add(dictionaryValueControl); Grid.SetColumn(dictionaryValueControl, index); ++index; } } }
/// <summary> /// Parses a XML node that contains information about a content group. /// </summary> /// <param name="node">The XML node to parse.</param> /// <exception cref="ConfigurationErrosException">The <paramref name="node"/> is not a /// valid representation of a content group.</exception> public void Parse(XmlNode node, DictionaryValue<RepositoryNode> repositories) { string name = null, build = null, mime_type = null, path_ref = null; if (!(GetAttributeValue(node, kNameAttributeName, out name) && GetAttributeValue(node, kBuildAttributeName, out build) && GetAttributeValue(node, kMimeTypeAttributeName, out mime_type) && GetAttributeValue(node, kPathRefAttributeName, out path_ref) )) { Thrower.ThrowConfigurationException(string.Format(StringResources.Config_MissingAt ,"a required attribute" ,NohrosConfiguration.kContentGroupNodeTree + ".any" ) ,"[Parse Nohros.Configuration.ContentGroupNode]" ); } // sanity check the build type if (build != "release" && build != "debug") Thrower.ThrowConfigurationException(string.Format(StringResources.Config_ArgOutOfRange, build, NohrosConfiguration.kContentGroupNodeTree + "." + name + "." + kBuildAttributeName), "[Parse Nohros.Configuration.ContentGroupNode]"); // resolve the base path RepositoryNode str; str = repositories[path_ref] as RepositoryNode; if (str == null) Thrower.ThrowConfigurationException(string.Format(StringResources.Config_ArgOutOfRange, path_ref, NohrosConfiguration.kContentGroupNodeTree + "." + name + "." + kPathRefAttributeName), "[Parse Nohros.Configuration.ContentGroupNode]"); build_type_ = (build == "release") ? BuildType.Release : BuildType.Debug; mime_type_ = mime_type; base_path_ = str.RelativePath; string file_name = null; foreach (XmlNode file_node in node.ChildNodes) { if (string.Compare(file_node.Name, "add", StringComparison.OrdinalIgnoreCase) == 0) { if (!GetAttributeValue(file_node, kFileNameAttributeName, out file_name)) { Thrower.ThrowConfigurationException(string.Format(StringResources.Config_MissingAt, kFileNameAttributeName, Name), "[Parse Nohros.Configuration.ContentGroupNode]"); } files_.Add(file_name); } } }
public void It_Should_Parse_A_Variable_And_A_Value(String liquid, String expected) { // Arrange DictionaryValue dict = new DictionaryValue(new Dictionary<String, IExpressionConstant> { { "foo", NumericValue.Create(22) }, { "bar", NumericValue.Create(23) } }); ITemplateContext ctx = new TemplateContext().WithAllFilters() .WithFilter<FilterFactoryTests.MockStringToStringFilter>("mockfilter") .DefineLocalVariable("bar", dict) .DefineLocalVariable("foo", dict); //ArrayValue arr = new ArrayValue(new List<IExpressionConstant> { new NumericValue(33) }); //ctx.DefineLocalVariable("bar", arr); var template = LiquidTemplate.Create(liquid); // Act String result = template.Render(ctx); Logger.Log(result); // Assert Assert.That(result, Is.EqualTo(expected)); }
public void It_Should_Render_A_Null_In_A_Dictionary() { // Arrange var subDictValue = new DictionaryValue( new Dictionary<string, IExpressionConstant> { {"abc", new StringValue("def")}, {"ghi", null} }); var dictValue = new DictionaryValue( new Dictionary<string, IExpressionConstant> { {"one", null}, {"two", subDictValue}, }); // Act ITemplateContext ctx = new TemplateContext().DefineLocalVariable("dict1", dictValue); // Act var result = RenderingHelper.RenderTemplate("Result : {{ dict1 }}", ctx); // Assert Assert.That(result, Is.EqualTo("Result : { \"one\" : null, \"two\" : { \"abc\" : \"def\", \"ghi\" : null } }")); }
public void It_Should_Recursively_Render_Dictionaries_in_Json() { // Arrange var subDictValue = new DictionaryValue( new Dictionary<string, IExpressionConstant> { {"abc", new StringValue("def")} }); var dictValue = new DictionaryValue( new Dictionary<string, IExpressionConstant> { {"one", NumericValue.Create(1)}, {"two", subDictValue}, }); // Act ITemplateContext ctx = new TemplateContext().DefineLocalVariable("dict1", dictValue); // Act var result = RenderingHelper.RenderTemplate("Result : {{ dict1 }}", ctx); // Assert Assert.That(result, Is.EqualTo("Result : { \"one\" : 1, \"two\" : { \"abc\" : \"def\" } }")); }
public void It_Should_Not_Quote_Numerics_In_Json_Dict() { // Arrange var dictValue = new DictionaryValue( new Dictionary<string, IExpressionConstant> { {"one", NumericValue.Create(1)}, {"two", NumericValue.Create(2L)}, {"three", NumericValue.Create(3m)}, {"four", NumericValue.Create(new BigInteger(4))} }); // Act ITemplateContext ctx = new TemplateContext().DefineLocalVariable("dict1", dictValue); // Act var result = RenderingHelper.RenderTemplate("Result : {{ dict1 }}", ctx); // Assert Assert.That(result, Is.EqualTo("Result : { \"one\" : 1, \"two\" : 2, \"three\" : 3.0, \"four\" : 4 }")); }
// SEE: https://github.com/Shopify/liquid/wiki/Liquid-for-Designers public void It_Should_Cast_KV_Pairs_In_A_Dictionary_To_An_Array_Of_Arrays_with_Two_Elements() { // Arrange var dictValue = new DictionaryValue( new Dictionary<string, IExpressionConstant> { {"one", new StringValue("ONE")}, {"two", new StringValue("TWO")}, {"three", new StringValue("THREE")}, {"four", new StringValue("FOUR")} }); // Act var result = ValueCaster.Cast<DictionaryValue, ArrayValue>(dictValue).SuccessValue<ArrayValue>(); // Assert Assert.That(result.ArrValue.Count, Is.EqualTo(4)); }
private LiquidExpressionResult DoLookup(ITemplateContext ctx, DictionaryValue dictionaryValue, IExpressionConstant indexProperty) { String propertyNameString = ValueCaster.RenderAsString(indexProperty); if (propertyNameString.ToLower().Equals("size")) { return LiquidExpressionResult.Success(NumericValue.Create(dictionaryValue.DictValue.Keys.Count())); } return LiquidExpressionResult.Success(dictionaryValue.ValueAt(indexProperty.Value.ToString())); }
private LiquidExpressionResult Contains(DictionaryValue dictValue, IExpressionConstant expressionConstant) { return LiquidExpressionResult.Success(new BooleanValue(dictValue.DictValue.Keys.Any(x => x.Equals(expressionConstant.Value)))); }
/// <summary> /// Initializes a new instance of the <see cref="Configuration"/> class. /// </summary> public Configuration(IConfigurationBuilder<IConfiguration> builder) { properties_ = builder.Properties; repositories_ = builder.Repositories; providers_ = builder.Providers; xml_elements_ = builder.XmlElements; }
/// <summary> /// Recursively gets the dynamic properties. /// </summary> /// <param name="node"> /// A XML node containing the dynamic properties. /// </param> /// <param name="path"> /// The path to the node value. /// </param> /// <remarks> /// If the namespace of the property is not defined it will be assigned to /// the default namespace. /// </remarks> void GetProperties(XmlNode node, string path) { if (node != null && node.ChildNodes.Count > 0) { foreach (XmlNode inner_node in node.ChildNodes) { if (inner_node.NodeType == XmlNodeType.Element) { if (inner_node.ChildNodes.Count > 0) { GetProperties(inner_node, path + "." + inner_node.Name); } else { XmlAttributeCollection properties = inner_node.Attributes; if (properties.Count == 0) return; DictionaryValue keys = new DictionaryValue(); foreach (XmlAttribute property in properties) { keys.SetString(property.Name, property.Value); } properties_[path] = keys; } } } } }
/// <summary> /// Convenience form of Get(). /// </summary> /// <param name="index">The zero-based index of the element to get.</param> /// <param name="out_value">When this method returns, contains the <see cref="Value"/> associated /// with the specified index if the index falls within the current list range; otherwise null</param> /// <returns>true if the index falls within the current list range; otherwise false.</returns> public bool GetDictionary(int index, out DictionaryValue out_value) { IValue value; out_value = null; if (!Get(index, out value) || value.IsType(ValueType.Dictionary)) return false; out_value = value as DictionaryValue; return true; }
/// <summary> /// Recursively build <see cref="Value"/>. /// </summary> /// <param name="is_root">true to verify if the root is either an object or an array; otherwise, false.</param> /// <returns>An IDictionary&alt;string, string> containing the parsed JSON string or a null reference /// if we don't have a valid JSON string.</returns> /// <exception cref="ArgumentException">Too much nesting.</exception> IValue BuildValue(bool is_root) { ++stack_depth_; if (stack_depth_ > kStackLimit) { throw new InvalidOperationException( Resources.Resources.InvalidOperation_TooMuchNesting); } Token token = ParseToken(); // The root token must be an array or an object. if (is_root && token.type != Token.TokenType.OBJECT_BEGIN && token.type != Token.TokenType.ARRAY_BEGIN) return null; IValue node; switch (token.type) { case Token.TokenType.END_OF_INPUT: case Token.TokenType.INVALID_TOKEN: return null; case Token.TokenType.NULL_TOKEN: node = Value.CreateNullValue(); break; case Token.TokenType.BOOL_TRUE: node = Value.CreateBooleanValue(true); break; case Token.TokenType.BOOL_FALSE: node = Value.CreateBooleanValue(false); break; case Token.TokenType.NUMBER: node = DecodeNumber(token); break; case Token.TokenType.STRING: node = DecodeString(token); break; case Token.TokenType.ARRAY_BEGIN: { json_pos_ += token.length; token = ParseToken(); node = new ListValue(); while (token.type != Token.TokenType.ARRAY_END) { IValue array_node = BuildValue(false); if (array_node == null) return null; ((ListValue)node).Append(array_node); // After a list value, we expect a comma ot the end of the list. token = ParseToken(); if (token.type == Token.TokenType.LIST_SEPARATOR) { json_pos_ += token.length; token = ParseToken(); // Trailing commas are invalid according to the JSON RFC, but some // consumers need the parsing leniency, so handle accordingly. if (token.type == Token.TokenType.ARRAY_END) { if (!allow_trailing_comma_) { throw new InvalidOperationException(string.Format( Resources.Resources.InvalidOperation_json_TrailingComma, json_pos_)); } // Trailing comma OK, stop parsing the Array. break; } } else if (token.type != Token.TokenType.ARRAY_END) { // Unexpected value after list value. Bail out. return null; } } if (token.type != Token.TokenType.ARRAY_END) { return null; } break; } case Token.TokenType.OBJECT_BEGIN: { json_pos_ += token.length; token = ParseToken(); node = new DictionaryValue(); while (token.type != Token.TokenType.OBJECT_END) { if (token.type != Token.TokenType.STRING) { throw new InvalidOperationException(string.Format( Resources.Resources.InvalidOperation_json_UnquotedDictionaryKey, json_pos_)); } IValue dict_key_value = DecodeString(token); if (dict_key_value == null) return null; // Converts the key into a string. string dict_key; bool success = dict_key_value.GetAsString(out dict_key); json_pos_ += token.length; token = ParseToken(); if (token.type != Token.TokenType.OBJECT_PAIR_SEPARATOR) return null; json_pos_ += token.length; //token = ParseToken(); IValue dict_value = BuildValue(false); if (dict_value == null) return null; (node as DictionaryValue)[dict_key] = dict_value; // After a key value pair, we expect a comma or the end of the object token = ParseToken(); if (token.type == Token.TokenType.LIST_SEPARATOR) { json_pos_ += token.length; token = ParseToken(); // Trailing commas are invalid according to the JSON RFC, but some // consumers need the parsing leniency, so handle accordingly. if (token.type == Token.TokenType.OBJECT_END) { if (!allow_trailing_comma_) { throw new InvalidOperationException(string.Format( Resources.Resources.InvalidOperation_json_TrailingComma, json_pos_)); } // Trailing comma OK, stop parsing the object. break; } } else if (token.type != Token.TokenType.OBJECT_END) { // Unexpected value after last object value. Bail out. return null; } } if (token.type != Token.TokenType.OBJECT_END) return null; break; } default: // We got a token that's not a value. return null; } json_pos_ += token.length; --stack_depth_; return node; }
private static bool CheckIsEmpty(DictionaryValue val) { return !val.DictValue.Any(); }