/// <summary> /// Reads a URI. /// </summary> /// <param name="node">The node containing the URI.</param> /// <param name="table">The serialiser table.</param> /// <returns>A new instance of a <see cref="Uri"/> if the node is valid; null otherwise.</returns> public override object Read(XmlNode node, NetReflectorTypeTable table) { if (node == null) { // NetReflector should do this check, but doesn't if (this.Attribute.Required) { throw new NetReflectorItemRequiredException(Attribute.Name + " is required"); } else { return null; } } Uri ret; if (node is XmlAttribute) { ret = new Uri(node.Value); } else { ret = new Uri(node.InnerText); } return ret; }
protected override object Read(XmlNode node, Type instanceType, NetReflectorTypeTable table) { Type elementType = instanceType.GetElementType(); // null check XmlElementList nodes = new XmlElementList(node.ChildNodes); Array array = Array.CreateInstance(elementType, nodes.Count); for (int i = 0; i < array.Length; i++) { try { object value = converter.Convert(elementType, ReadValue(nodes[i], table)); if (value == null) { throw new NetReflectorConverterException( string.Format("Unable to convert element '{0}' to '{1}'", nodes[i].Name, elementType.FullName)); } array.SetValue(value, i); } catch (NetReflectorConverterException error) { throw new NetReflectorException( string.Format("Unable to load array item '{0}' - {1}" + Environment.NewLine + "Xml: {2}", nodes[i].Name, error.Message, nodes[i].OuterXml), error); } } return array; }
/// <summary> /// Reads the specified node. /// </summary> /// <param name="node">The node to read.</param> /// <param name="table">The underlying serialiser table.</param> /// <returns>The deserialised network credentials.</returns> public override object Read(XmlNode node, NetReflectorTypeTable table) { NetworkCredential ret = null; if (node is XmlElement) { XmlElement elem = (XmlElement)node; if (!elem.HasAttribute("userName") || String.IsNullOrEmpty(elem.GetAttribute("userName").Trim())) { Log.Warning("No 'userName' specified!"); return ret; } if (!elem.HasAttribute("password")) { Log.Warning("No 'password' specified!"); return ret; } if (elem.HasAttribute("domain") && !String.IsNullOrEmpty(elem.GetAttribute("domain").Trim())) { ret = new NetworkCredential(elem.GetAttribute("userName").Trim(), elem.GetAttribute("password").Trim(), elem.GetAttribute("domain").Trim()); } else { ret = new NetworkCredential(elem.GetAttribute("userName").Trim(), elem.GetAttribute("password").Trim()); } } return ret; }
public static NetReflectorTypeTable CreateDefault(IInstantiator instantiator) { NetReflectorTypeTable table = new NetReflectorTypeTable(instantiator); SetupDefaultTable(table); return(table); }
private Type GetTargetType(XmlNode childNode, NetReflectorTypeTable table) { if ((attribute.InstanceTypeKey != null) && (childNode.Attributes != null) && (childNode.Attributes[attribute.InstanceTypeKey] != null)) { XmlAttribute instanceTypeAttribute = childNode.Attributes[attribute.InstanceTypeKey]; IXmlTypeSerialiser serialiser = table[instanceTypeAttribute.InnerText]; if (serialiser == null) { string msg = @"Type with NetReflector name ""{0}"" does not exist. The name may be incorrect or the assembly containing the type might not be loaded. Xml: {1}"; throw new NetReflectorException(string.Format(msg, instanceTypeAttribute.InnerText, childNode.OuterXml)); } /// HACK: no way of indicating that attribute is InstanceTypeKey. If this is removed then attribute will generate warning. childNode.Attributes.Remove(instanceTypeAttribute); return(serialiser.Type); } else if (attribute.InstanceType != null) { return(attribute.InstanceType); } else { return(member.MemberType); } }
/// <summary> /// Reads a URI. /// </summary> /// <param name="node">The node containing the URI.</param> /// <param name="table">The serialiser table.</param> /// <returns>A new instance of a <see cref="Uri"/> if the node is valid; null otherwise.</returns> public override object Read(XmlNode node, NetReflectorTypeTable table) { if (node == null) { // NetReflector should do this check, but doesn't if (this.Attribute.Required) { throw new NetReflectorItemRequiredException(Attribute.Name + " is required"); } else { return null; } } // Get the actual private value PrivateString value; if (node is XmlAttribute) { value = node.Value; } else { value = node.InnerText; } return value; }
/// <summary> /// Loads the version information from the type table. /// </summary> /// <param name="typeTable">The type table.</param> public void LoadInformation(NetReflectorTypeTable typeTable) { // Sort the assemblies and types var assemblies = new Dictionary<Assembly, SortedDictionary<string, Type>>(); foreach (IXmlTypeSerialiser type in typeTable) { SortedDictionary<string, Type> types; var assembly = type.Type.Assembly; if (assemblies.ContainsKey(assembly)) { types = assemblies[assembly]; } else { types = new SortedDictionary<string, Type>(); assemblies.Add(assembly, types); } types.Add(type.Attribute.Name, type.Type); } foreach (var assembly in assemblies) { // Make sure the assembly has been added var name = assembly.Key.GetName(); var parentNode = new TreeNode(name.Name + " [" + name.Version.ToString() + "]"); this.versionInformation.Nodes.Add(parentNode); // Add the types foreach (var type in assembly.Value) { parentNode.Nodes.Add(new TreeNode(type.Key, 1, 1)); } } }
public override object Read(XmlNode node, NetReflectorTypeTable types) { var files = new List<BuildReportXslFilename>(); foreach (XmlNode fileNode in node.SelectNodes("xslFile")) { var newFile = new BuildReportXslFilename(); foreach (XmlNode childNode in fileNode.ChildNodes) { if (childNode.NodeType == XmlNodeType.Text) { newFile.Filename = childNode.InnerText.Trim(); } else if (childNode.LocalName == "includedProjects") { foreach (XmlNode projectNode in childNode.ChildNodes) { newFile.IncludedProjects.Add(projectNode.InnerText.Trim()); } } else if (childNode.LocalName == "excludedProjects") { foreach (XmlNode projectNode in childNode.ChildNodes) { newFile.ExcludedProjects.Add(projectNode.InnerText.Trim()); } } } files.Add(newFile); } return files.ToArray(); }
public void ReadMembers(XmlNode node, object instance, NetReflectorTypeTable table) { IList childNodes = new ArrayList(); AddChildNodes(node.Attributes, childNodes, table); AddChildNodes(node.ChildNodes, childNodes, table); foreach (IXmlMemberSerialiser serialiser in MemberSerialisers) { XmlNode childNode = GetNodeByName(childNodes, serialiser.Attribute.Name); try { object value = serialiser.Read(childNode, table); if (value != null) { serialiser.SetValue(instance, value); } childNodes.Remove(childNode); } catch (NetReflectorItemRequiredException error) { throw new NetReflectorException( string.Format("{0}" + Environment.NewLine + "Xml: {1}", error.Message, node.OuterXml), error); } } foreach (XmlNode orphan in childNodes) { HandleUnusedNode(table, orphan); } }
protected override object Read(XmlNode node, Type instanceType, NetReflectorTypeTable table) { Type elementType = instanceType.GetElementType(); // null check XmlElementList nodes = new XmlElementList(node.ChildNodes); Array array = Array.CreateInstance(elementType, nodes.Count); for (int i = 0; i < array.Length; i++) { try { object value = converter.Convert(elementType, ReadValue(nodes[i], table)); if (value == null) { throw new NetReflectorConverterException( string.Format("Unable to convert element '{0}' to '{1}'", nodes[i].Name, elementType.FullName)); } array.SetValue(value, i); } catch (NetReflectorConverterException error) { throw new NetReflectorException( string.Format("Unable to load array item '{0}' - {1}" + Environment.NewLine + "Xml: {2}", nodes[i].Name, error.Message, nodes[i].OuterXml), error); } } return(array); }
public static NetReflectorTypeTable CreateDefault() { NetReflectorTypeTable table = new NetReflectorTypeTable(); SetupDefaultTable(table); return(table); }
public override object Read(XmlNode node, NetReflectorTypeTable types) { Timeout timeout = Timeout.DefaultTimeout; if (node is XmlAttribute) { XmlAttribute a = (XmlAttribute) node; try { timeout = new Timeout(Int32.Parse(a.Value)); } catch (Exception) { Log.Warning("Could not parse timeout string. Using default timeout."); } } else if (node is XmlElement) { XmlElement e = (XmlElement) node; try { TimeUnits units = TimeUnits.MILLIS; string unitsString = e.GetAttribute("units"); if (unitsString != null && unitsString != "") { units = TimeUnits.Parse(unitsString); } timeout = new Timeout(Int32.Parse(e.InnerText), units); } catch (Exception) { Log.Warning("Could not parse timeout string. Using default timeout."); } } return timeout; }
public object Read(XmlNode node, NetReflectorTypeTable table) { object instance = instantiator.Instantiate(type); ReflectionPreprocessorAttribute.Invoke(instance, table, node); ReadMembers(node, instance, table); return instance; }
public NetReflectorConfigurationReader() { typeTable = new NetReflectorTypeTable(); typeTable.Add(AppDomain.CurrentDomain); typeTable.Add(Directory.GetCurrentDirectory(), CONFIG_ASSEMBLY_PATTERN); typeTable.InvalidNode += new InvalidNodeEventHandler(HandleUnusedNode); reader = new NetReflectorReader(typeTable); }
private void HandleUnusedNode(NetReflectorTypeTable table, XmlNode orphan) { // Ignore any XML schema instance nodes if (!string.Equals(orphan.NamespaceURI, "http://www.w3.org/2001/XMLSchema-instance")) { table.OnInvalidNode(new InvalidNodeEventArgs(orphan, "Unused node detected: " + orphan.OuterXml)); } }
public object Read(XmlNode node, NetReflectorTypeTable table) { object instance = instantiator.Instantiate(type); ReflectionPreprocessorAttribute.Invoke(instance, table, node); ReadMembers(node, instance, table); return(instance); }
public virtual object Read(XmlNode node, NetReflectorTypeTable table) { if (node == null) { CheckIfMemberIsRequired(); return null; } Type targetType = GetTargetType(node, table); return Read(node, targetType, table); }
protected override object Read(XmlNode node, Type instanceType, NetReflectorTypeTable table) { IDictionary dictionary = Instantiator.Instantiate(instanceType) as IDictionary; // null check foreach (XmlNode child in XmlElementList.Create(node.ChildNodes)) { object key = GetHashkey(child); object value = base.ReadValue(child, table); dictionary.Add(key, value); } return dictionary; }
public void LoadsFromXml() { NetReflectorTypeTable typeTable = new NetReflectorTypeTable(); typeTable.Add(AppDomain.CurrentDomain); NetReflectorReader reader = new NetReflectorReader(typeTable); object result = reader.Read("<inMemoryCache duration=\"5\" mode=\"Fixed\"/>"); Assert.That(result, Is.InstanceOf<InMemorySessionCache>()); InMemorySessionCache cache = result as InMemorySessionCache; Assert.AreEqual(5, cache.Duration); Assert.AreEqual(SessionExpiryMode.Fixed, cache.ExpiryMode); }
/// <summary> /// Invokes the preprocessor method. /// </summary> /// <param name="parent">The parent.</param> /// <param name="typeTable">The type table.</param> /// <param name="inputNode">The input node.</param> /// <returns></returns> public static XmlNode Invoke(object parent, NetReflectorTypeTable typeTable, XmlNode inputNode) { var result = inputNode; foreach (var method in parent.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance)) { if (method.GetCustomAttributes(typeof(ReflectionPreprocessorAttribute), true).Length > 0) { result = method.Invoke(parent, new object[]{ typeTable, inputNode }) as XmlNode; } } return result; }
/// <summary> /// Read a node. /// </summary> /// <param name="node"></param> /// <param name="table"></param> /// <returns></returns> public override object Read(XmlNode node, NetReflectorTypeTable table) { if (isList) { return ReadList(node); } else { var value = ReadValue(node as XmlElement); return value; } }
public void LoadsFromXml() { NetReflectorTypeTable typeTable = new NetReflectorTypeTable(); typeTable.Add(AppDomain.CurrentDomain); NetReflectorReader reader = new NetReflectorReader(typeTable); object result = reader.Read("<fileBasedCache duration=\"5\" mode=\"Fixed\"/>"); Assert.IsInstanceOfType(typeof(FileBasedSessionCache), result); FileBasedSessionCache cache = result as FileBasedSessionCache; Assert.AreEqual(5, cache.Duration); Assert.AreEqual(SessionExpiryMode.Fixed, cache.ExpiryMode); }
/// <summary> /// Reads the specified node. /// </summary> /// <param name="node">The node.</param> /// <param name="types">The types.</param> /// <returns></returns> /// <remarks></remarks> public override object Read(XmlNode node, NetReflectorTypeTable types) { if (node == null) { // NetReflector should do this check, but doesn't if (this.Attribute.Required) { throw new NetReflectorItemRequiredException(Attribute.Name + " is required"); } else { return null; } } Timeout timeout = Timeout.DefaultTimeout; XmlAttribute a = node as XmlAttribute; if (a != null) { try { timeout = new Timeout(Int32.Parse(a.Value, CultureInfo.CurrentCulture)); } catch (Exception) { Log.Warning("Could not parse timeout string. Using default timeout."); } } else { var e = node as XmlElement; if (e != null) { try { TimeUnits units = TimeUnits.MILLIS; string unitsString = e.GetAttribute("units"); if (unitsString != null && !(unitsString != null && unitsString.Length == 0)) { units = TimeUnits.Parse(unitsString); } timeout = new Timeout(Int32.Parse(e.InnerText, CultureInfo.CurrentCulture), units); } catch (Exception) { Log.Warning("Could not parse timeout string. Using default timeout."); } } } return timeout; }
protected override object Read(XmlNode node, Type instanceType, NetReflectorTypeTable table) { IDictionary dictionary = Instantiator.Instantiate(instanceType) as IDictionary; // null check foreach (XmlNode child in XmlElementList.Create(node.ChildNodes)) { object key = GetHashkey(child); object value = base.ReadValue(child, table); dictionary.Add(key, value); } return(dictionary); }
public virtual object Read(XmlNode node, NetReflectorTypeTable table) { if (node == null) { CheckIfMemberIsRequired(); return(null); } else { Type targetType = GetTargetType(node, table); return(Read(node, targetType, table)); } }
protected override void ExecuteTask() { Log(Level.Info, "Loading assembly {0}.", assembly); NetReflectorTypeTable table = new NetReflectorTypeTable(); table.Add(assembly); Log(Level.Info, "Loaded {0} types.", table.Count); Log(Level.Info, "Generating documentation. The output will be written to {0}", outfile); using (StreamWriter writer = new StreamWriter(outfile)) { new XmlDocumentationGenerator(table).WriteIndented(writer); } }
/// <summary> /// Invokes the preprocessor method. /// </summary> /// <param name="parent">The parent.</param> /// <param name="typeTable">The type table.</param> /// <param name="inputNode">The input node.</param> /// <returns></returns> public static XmlNode Invoke(object parent, NetReflectorTypeTable typeTable, XmlNode inputNode) { var result = inputNode; foreach (var method in parent.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance)) { if (method.GetCustomAttributes(typeof(ReflectionPreprocessorAttribute), true).Length > 0) { result = method.Invoke(parent, new object[] { typeTable, inputNode }) as XmlNode; } } return(result); }
// refactor with method above??? protected object ReadValue(XmlNode node, NetReflectorTypeTable table) { IXmlSerialiser serialiser = table[node.Name]; if (serialiser == null) { return(node.InnerText); } else { // fix return(serialiser.Read(node, table)); } }
protected virtual object Read(XmlNode childNode, Type instanceType, NetReflectorTypeTable table) { if (ReflectionUtil.IsCommonType(instanceType)) { if ((childNode.Attributes != null) && (childNode.Attributes.Count > 0)) { throw new NetReflectorException( string.Format("Attributes are not allowed on {3} types - {0} attributes(s) found on '{1}'" + Environment.NewLine + "Xml: {2}", childNode.Attributes.Count, childNode.Name, childNode.OuterXml, instanceType.Name)); } return childNode.InnerText; } else { ReflectorTypeAttribute reflectorTypeAttribute = ReflectorTypeAttribute.GetAttribute(instanceType); if (reflectorTypeAttribute == null) { if (!string.IsNullOrEmpty(attribute.InstanceTypeKey)) { throw new NetReflectorException( string.Format("Unable to find reflector type for '{0}' when deserialising '{1}' - '{3}' has not been set" + Environment.NewLine + "Xml: {2}", instanceType.Name, childNode.Name, childNode.OuterXml, attribute.InstanceTypeKey)); } else { throw new NetReflectorException( string.Format("Unable to find reflector type for '{0}' when deserialising '{1}'" + Environment.NewLine + "Xml: {2}", instanceType.Name, childNode.Name, childNode.OuterXml)); } } IXmlSerialiser serialiser = table[reflectorTypeAttribute.Name]; // null check return serialiser.Read(childNode, table); } }
protected virtual object Read(XmlNode childNode, Type instanceType, NetReflectorTypeTable table) { if (ReflectionUtil.IsCommonType(instanceType)) { if ((childNode.Attributes != null) && (childNode.Attributes.Count > 0)) { throw new NetReflectorException( string.Format("Attributes are not allowed on {3} types - {0} attributes(s) found on '{1}'" + Environment.NewLine + "Xml: {2}", childNode.Attributes.Count, childNode.Name, childNode.OuterXml, instanceType.Name)); } return(childNode.InnerText); } else { ReflectorTypeAttribute reflectorTypeAttribute = ReflectorTypeAttribute.GetAttribute(instanceType); if (reflectorTypeAttribute == null) { if (!string.IsNullOrEmpty(attribute.InstanceTypeKey)) { throw new NetReflectorException( string.Format("Unable to find reflector type for '{0}' when deserialising '{1}' - '{3}' has not been set" + Environment.NewLine + "Xml: {2}", instanceType.Name, childNode.Name, childNode.OuterXml, attribute.InstanceTypeKey)); } else { throw new NetReflectorException( string.Format("Unable to find reflector type for '{0}' when deserialising '{1}'" + Environment.NewLine + "Xml: {2}", instanceType.Name, childNode.Name, childNode.OuterXml)); } } IXmlSerialiser serialiser = table[reflectorTypeAttribute.Name]; // null check return(serialiser.Read(childNode, table)); } }
private void AddChildNodes(IEnumerable nodes, IList childNodes, NetReflectorTypeTable table) { foreach (XmlNode node in nodes) { if (node.NodeType == XmlNodeType.Comment) { continue; } if (GetNodeByName(childNodes, node.Name) != null) { HandleUnusedNode(table, node); } else { childNodes.Add(node); } } }
public XmlNode PreprocessParameters(NetReflectorTypeTable typeTable, XmlNode inputNode) { var dobNode = (from node in inputNode.ChildNodes .OfType<XmlNode>() where node.Name == "dob" select node).SingleOrDefault(); if (dobNode != null) { var dob = DateTime.Parse(dobNode.InnerText); inputNode.RemoveChild(dobNode); var ageNode = inputNode.OwnerDocument.CreateElement("age"); ageNode.InnerText = Convert.ToInt32( (DateTime.Now - dob).TotalDays / 365) .ToString(); inputNode.AppendChild(ageNode); } return inputNode; }
public NetReflectorConfigurationReader() { typeTable = new NetReflectorTypeTable(); typeTable.Add(AppDomain.CurrentDomain); string pluginLocation = ConfigurationManager.AppSettings["PluginLocation"]; if (!string.IsNullOrEmpty(pluginLocation)) { if (Directory.Exists(pluginLocation)) { typeTable.Add(pluginLocation, CONFIG_ASSEMBLY_PATTERN); } else { throw new CruiseControlException("Unable to find plugin directory: " + pluginLocation); } } typeTable.Add(Directory.GetCurrentDirectory(), CONFIG_ASSEMBLY_PATTERN); reader = new NetReflectorReader(typeTable); }
private Type GetTargetType(XmlNode childNode, NetReflectorTypeTable table) { // Attempt to find the type XmlAttribute typeAttribute = null; if ((attribute.InstanceTypeKey != null) && (childNode.Attributes != null)) { typeAttribute = childNode.Attributes[attribute.InstanceTypeKey]; // This is a special case - the element may be an abstract element (see XSD) and needs the xsi namespace if ((typeAttribute == null) && (attribute.InstanceTypeKey == "type")) { typeAttribute = childNode.Attributes["type", "http://www.w3.org/2001/XMLSchema-instance"]; } } if ((attribute.InstanceTypeKey != null) && (childNode.Attributes != null) && (typeAttribute != null)) { IXmlTypeSerialiser serialiser = table[typeAttribute.InnerText]; if (serialiser == null) { string msg = @"Type with NetReflector name ""{0}"" does not exist. The name may be incorrect or the assembly containing the type might not be loaded. Xml: {1}"; throw new NetReflectorException(string.Format(msg, typeAttribute.InnerText, childNode.OuterXml)); } /// HACK: no way of indicating that attribute is InstanceTypeKey. If this is removed then attribute will generate warning. childNode.Attributes.Remove(typeAttribute); return(serialiser.Type); } else if (attribute.InstanceType != null) { return(attribute.InstanceType); } else { return(member.MemberType); } }
/// Todo: convert to element type protected override object Read(XmlNode node, Type instanceType, NetReflectorTypeTable table) { IList list = Instantiator.Instantiate(instanceType) as IList; // null check foreach (XmlNode child in XmlElementList.Create(node.ChildNodes)) { object value = base.ReadValue(child, table); try { list.Add(value); } catch (InvalidCastException error) { throw new NetReflectorConverterException( string.Format("Unable to convert element '{0}' to its required type{2}XML: {1}", child.Name, node.OuterXml, Environment.NewLine), error); } } return list; }
/// Todo: convert to element type protected override object Read(XmlNode node, Type instanceType, NetReflectorTypeTable table) { IList list = Instantiator.Instantiate(instanceType) as IList; // null check foreach (XmlNode child in XmlElementList.Create(node.ChildNodes)) { object value = base.ReadValue(child, table); try { list.Add(value); } catch (InvalidCastException error) { throw new NetReflectorConverterException( string.Format("Unable to convert element '{0}' to its required type{2}XML: {1}", child.Name, node.OuterXml, Environment.NewLine), error); } } return(list); }
public NetReflectorReader(NetReflectorTypeTable table) { this.table = table; }
public static object Read(XmlReader reader, NetReflectorTypeTable table) { return(new NetReflectorReader(table).Read(reader)); }
public static object Read(string xml, NetReflectorTypeTable table) { return(new NetReflectorReader(table).Read(xml)); }
public NetReflectorReader() : this(NetReflectorTypeTable.CreateDefault()) { }
public static object Read(XmlNode node, NetReflectorTypeTable table) { return(new NetReflectorReader(table).Read(node)); }
public virtual XmlNode PreprocessParameters(NetReflectorTypeTable typeTable, XmlNode inputNode) { return DynamicValueUtility.ConvertXmlToDynamicValues(typeTable, inputNode); }
public static void Read(string xml, object instance, NetReflectorTypeTable table) { new NetReflectorReader(table).Read(xml, instance); }
public virtual XmlNode PreprocessParameters(NetReflectorTypeTable typeTable, XmlNode inputNode) { var node = DynamicValueUtility.ConvertXmlToDynamicValues(typeTable, inputNode); if (!string.IsNullOrEmpty(inputNode.NamespaceURI) && inputNode.NamespaceURI.StartsWith("http://thoughtworks.org/ccnet/")) { var parts = inputNode.NamespaceURI.Split('/'); var version = new Version( Convert.ToInt32(parts[parts.Length - 2], CultureInfo.CurrentCulture), Convert.ToInt32(parts[parts.Length - 1], CultureInfo.CurrentCulture)); node = this.UpgradeConfiguration(version, node); } return node; }
public static void Read(XmlReader reader, object instance, NetReflectorTypeTable table) { new NetReflectorReader(table).Read(reader, instance); }
public static void Read(XmlNode node, object instance, NetReflectorTypeTable table) { new NetReflectorReader(table).Read(node, instance); }
public void DeserializeOne_NonCustomSortUsing_Before_CustomSortRules() { NetReflectorTypeTable t = new NetReflectorTypeTable(); t.Add(typeof (WritingSystem)); NetReflectorReader r = new NetReflectorReader(t); WritingSystem ws = (WritingSystem) r.Read( "<WritingSystem><SortUsing>one</SortUsing><CustomSortRules>test</CustomSortRules><FontName>Tahoma</FontName><FontSize>99</FontSize><Id>one</Id></WritingSystem>"); Assert.IsNotNull(ws); Assert.IsNull(ws.CustomSortRules); Assert.AreEqual("one", ws.SortUsing); }
public void DeserializeCollection() { NetReflectorTypeTable t = new NetReflectorTypeTable(); t.Add(typeof (WritingSystemCollection)); t.Add(typeof (WritingSystem)); NetReflectorReader r = new NetReflectorReader(t); WritingSystemCollection c = r.Read(MakeXmlFromCollection()) as WritingSystemCollection; Assert.IsNotNull(c); Assert.AreEqual(2, c.Values.Count); }
private static void buildMembers(ref Dictionary<string, XmlMemberSerialiser> members, NetReflectorTypeTable typeTable, XmlNode node) { if (node == null) return; var nodeType = typeTable.ContainsType(node.Name) ? typeTable[node.Name] : null; if (nodeType != null) { foreach (XmlMemberSerialiser value in nodeType.MemberSerialisers) { if (value != null) { if (!members.ContainsKey(value.Attribute.Name)) members.Add(value.Attribute.Name, value); } } } foreach (XmlNode childNode in node.ChildNodes) { buildMembers(ref members, typeTable, childNode); } }
/// <summary> /// Check for and convert inline XML dynamic value notation into <see cref="IDynamicValue"/> definitions. /// </summary> /// <param name="typeTable">The type table.</param> /// <param name="inputNode">The node to process.</param> /// <param name="exclusions">Any elements to exclude.</param> /// <returns></returns> public static XmlNode ConvertXmlToDynamicValues(NetReflectorTypeTable typeTable, XmlNode inputNode, params string[] exclusions) { var resultNode = inputNode; var doc = inputNode.OwnerDocument; var parameters = new List<XmlElement>(); // Initialise the values from the reflection var inputMembers = new Dictionary<string, XmlMemberSerialiser>(); buildMembers(ref inputMembers, typeTable, inputNode); var nodes = inputNode.SelectNodes("descendant::text()|descendant-or-self::*[@*]/@*"); foreach (XmlNode nodeWithParam in nodes) { var text = nodeWithParam.Value; var isExcluded = CheckForExclusion(nodeWithParam, exclusions); if (!isExcluded && parameterRegex.Match(text).Success) { // Generate the format string var parametersEl = doc.CreateElement("parameters"); var index = 0; var lastReplacement = string.Empty; var format = parameterRegex.Replace(text, (match) => { // Split into it's component parts var parts = paramPartRegex.Split(match.Value.Substring(2, match.Value.Length - 3)); // Generate the value element var dynamicValueEl = doc.CreateElement("namedValue"); dynamicValueEl.SetAttribute("name", parts[0].Replace("\\|", "|")); if (parts.Length > 1) { dynamicValueEl.SetAttribute("value", parts[1].Replace("\\|", "|")); } parametersEl.AppendChild(dynamicValueEl); // Generate the replacement lastReplacement = string.Format(CultureInfo.CurrentCulture, "{{{0}{1}}}", index++, parts.Length > 2 ? ":" + parts[2].Replace("\\|", "|") : string.Empty); return lastReplacement; }); // Generate the dynamic value element var replacementValue = string.Empty; XmlElement replacementEl; if (lastReplacement != format) { replacementEl = doc.CreateElement("replacementValue"); AddElement(replacementEl, "format", format); replacementEl.AppendChild(parametersEl); } else { replacementEl = doc.CreateElement("directValue"); AddElement(replacementEl, "parameter", parametersEl.SelectSingleNode("namedValue/@name").InnerText); var innerValue = parametersEl.SelectSingleNode("namedValue/@value"); if (innerValue != null) { replacementValue = innerValue.InnerText; AddElement(replacementEl, "default", replacementValue); } } parameters.Add(replacementEl); // Generate the path var propertyName = new StringBuilder(); var currentNode = nodeWithParam is XmlAttribute ? nodeWithParam : nodeWithParam.ParentNode; var previousNode = currentNode; var lastName = string.Empty; bool hasDynamicValues = false; while ((currentNode != null) && (currentNode.NodeType != XmlNodeType.Document)) { var nodeName = currentNode.Name; var currentNodeType = typeTable.ContainsType(nodeName) ? typeTable[nodeName] : null; if (currentNodeType != null) { hasDynamicValues = currentNodeType.Type. GetInterface(typeof(IWithDynamicValuesItem).Name) != null; if (hasDynamicValues) break; } // we don't want to take into account the input node, but we need to know if it has // dynamic values, hence the break here and not in the while loop if (currentNode == inputNode) break; // Check if we are dealing with an array if (inputMembers.ContainsKey(nodeName) && inputMembers[nodeName].ReflectorMember.MemberType.IsArray) { // Do some convoluted processing to handle array items propertyName.Remove(0, lastName.Length + 1); // Remove the previous name, since this is now an index position var position = 0; var indexNode = previousNode; // Find the index of the node while (indexNode.PreviousSibling != null) { if (indexNode.NodeType != XmlNodeType.Comment) position++; indexNode = indexNode.PreviousSibling; } // Add the node as an indexed node propertyName.Insert(0, "." + nodeName + "[" + position.ToString(CultureInfo.CurrentCulture) + "]"); } else { // Just add the node name propertyName.Insert(0, "." + nodeName); } // Move to the parent lastName = nodeName; previousNode = currentNode; currentNode = getParentNode(currentNode); } propertyName.Remove(0, 1); AddElement(replacementEl, "property", propertyName.ToString()); // Set a replacement value nodeWithParam.Value = replacementValue; // add the parameters already there if the current node has dynamic values if (hasDynamicValues) addParameters(ref parameters, currentNode); } } // Add the remaining parameters to the root element addParameters(ref parameters, inputNode); return resultNode; }
public void CustomSortRules_SerializeAndDeserialize() { WritingSystem ws = new WritingSystem("one", new Font("Arial", 99)); ws.SortUsing = CustomSortRulesType.CustomICU.ToString(); string rules = "&n < ng <<< Ng <<< NG"; ws.CustomSortRules = rules; string s = NetReflector.Write(ws); NetReflectorTypeTable t = new NetReflectorTypeTable(); t.Add(typeof (WritingSystem)); NetReflectorReader r = new NetReflectorReader(t); WritingSystem wsRead = (WritingSystem) r.Read(s); Assert.IsNotNull(wsRead); Assert.AreEqual(rules, ws.CustomSortRules); }
public void DynamicUtilityNestedTasksWithParameters_ReflectorTableInitialisedAsByServer() { var TaskSetupXml = GetNestedTasksWithParametersXML(); var processedTaskXml = "<conditional>" + " <conditions>" + " <buildCondition>" + " <value>ForceBuild</value>" + " </buildCondition>" + " <compareCondition>" + " <value1></value1>" + " <value2>Yes</value2>" + " <evaluation>Equal</evaluation>" + " </compareCondition>" + " </conditions>" + " <tasks>" + " <exec>" + " <!-- if you want the task to fail, ping an unknown server -->" + " <executable>ping.exe</executable>" + " <buildArgs>localhost</buildArgs>" + " <buildTimeoutSeconds>15</buildTimeoutSeconds>" + " <description>Pinging a server</description>" + " </exec>" + " <conditional>" + " <conditions>" + " <compareCondition>" + " <value1></value1>" + " <value2>Yes</value2>" + " <evaluation>Equal</evaluation>" + " </compareCondition>" + " </conditions>" + " <tasks>" + " <exec>" + " <!-- if you want the task to fail, ping an unknown server -->" + " <executable>ping.exe</executable>" + " <buildArgs></buildArgs>" + " <buildTimeoutSeconds>15</buildTimeoutSeconds>" + " <description>Pinging a server</description>" + " <dynamicValues>" + " <directValue>" + " <parameter>TagVersion</parameter>" + " <property>buildArgs</property>" + " </directValue>" + " </dynamicValues>" + " </exec>" + " </tasks>" + " <dynamicValues>" + " <directValue>" + " <parameter>TagBuild</parameter>" + " <property>conditions[0].value1</property>" + " </directValue>" + " </dynamicValues>" + " </conditional>" + " </tasks>" + " <dynamicValues>" + " <directValue>" + " <parameter>CommitBuild</parameter>" + " <property>conditions[1].value1</property>" + " </directValue>" + " </dynamicValues>" + "</conditional>"; var xdoc = new System.Xml.XmlDocument(); xdoc.LoadXml(TaskSetupXml); Objection.ObjectionStore objectionStore = new Objection.ObjectionStore(); Exortech.NetReflector.NetReflectorTypeTable typeTable = Exortech.NetReflector.NetReflectorTypeTable.CreateDefault(new Objection.NetReflectorPlugin.ObjectionNetReflectorInstantiator(objectionStore)); var result = ThoughtWorks.CruiseControl.Core.Tasks.DynamicValueUtility.ConvertXmlToDynamicValues(typeTable, xdoc.DocumentElement, null); Console.WriteLine(result.OuterXml); xdoc.LoadXml(processedTaskXml); // load in xdoc to ease comparing xml documents Assert.AreEqual(xdoc.OuterXml, result.OuterXml); }
public void DeserializeOne() { NetReflectorTypeTable t = new NetReflectorTypeTable(); t.Add(typeof (WritingSystem)); NetReflectorReader r = new NetReflectorReader(t); WritingSystem ws = (WritingSystem) r.Read( "<WritingSystem><FontName>Tahoma</FontName><FontSize>99</FontSize><Id>one</Id><SortUsing>one</SortUsing></WritingSystem>"); // since Linux may not have Tahoma, we // need to test against the font mapping Font font = new Font("Tahoma", 99); Assert.IsNotNull(ws); Assert.AreEqual(font.Name, ws.FontName); Assert.AreEqual("one", ws.Id); Assert.AreEqual(font.Size, ws.FontSize); }
private static void SetupDefaultTable(NetReflectorTypeTable table) { table.Add(AppDomain.CurrentDomain); }