// Methods public int Add(XmlArrayItemAttribute attribute) { }
private void SerializeElement <T>(T obj, List <Attribute> customAttributes, string xmlNodeName = null, XmlTagAttribute classTagAttribute = null) { if (customAttributes.Any(x => x.GetType() == typeof(XmlIgnoreAttribute))) { return; } Type objType = obj.GetType(); if (validTypes.Any(x => x == objType)) // If the type is one of the basics { XmlFormatAttribute formatAttribute = GetAttribute <XmlFormatAttribute>(customAttributes); string objToString = string.Format("{0" + (formatAttribute == null ? "" : ":" + formatAttribute.Format) + "}", obj); bool xmlEncode = GetAttribute <XmlCDataAttribute>(customAttributes) == null; objToString = EscapeXMLValue(objToString, xmlEncode); XmlElementAttribute elementAttribute = GetAttribute <XmlElementAttribute>(customAttributes); XmlTagAttribute tagAttribute = GetAttribute <XmlTagAttribute>(customAttributes); string xmlNodeRestylized = tagAttribute?.Format(xmlNodeName); string xmlNodeClassRestylized = classTagAttribute?.Format(xmlNodeName); xmlNodeName = elementAttribute?.ElementName ?? xmlNodeRestylized ?? xmlNodeClassRestylized ?? xmlNodeName; string formattedNode = xmlNodeName != null ? string.Format("<{0}>{1}</{0}>\n", xmlNodeName, objToString) : objToString; Append(formattedNode); } else if (typeof(IEnumerable).IsAssignableFrom(objType)) // If the type is IEnumerable { Type underlyingType = objType.GetGenericArguments().FirstOrDefault() ?? objType.GetElementType(); XmlArrayAttribute arrayAttribute = GetAttribute <XmlArrayAttribute>(customAttributes); XmlArrayItemAttribute arrayItemAttribute = GetAttribute <XmlArrayItemAttribute>(customAttributes); XmlElementAttribute arrayElementAttribute = GetAttribute <XmlElementAttribute>(customAttributes); string collectionNodeName; string itemNodeName; bool indent; if (arrayElementAttribute != null && (arrayAttribute != null || arrayItemAttribute != null)) { throw new XmlException("Cannot have both element attribute and array attribute/s"); } else if (arrayElementAttribute != null) { collectionNodeName = null; itemNodeName = arrayElementAttribute.ElementName; indent = false; } else { collectionNodeName = arrayAttribute?.ElementName ?? xmlNodeName; itemNodeName = arrayItemAttribute?.ElementName ?? underlyingType.Name; indent = true; } if (indent) { Append(string.Format("<{0}>\n", collectionNodeName)); nestCount++; } foreach (var item in obj as IEnumerable) { SerializeElement(item, new List <Attribute>(), itemNodeName, classTagAttribute); } if (indent) { nestCount--; Append(string.Format("</{0}>\n", collectionNodeName)); } } else // If the type is object { customAttributes.AddRange(GetXmlAttributes(objType)); XmlRootAttribute rootAttribute = GetAttribute <XmlRootAttribute>(customAttributes); XmlElementAttribute elementAttribute = GetAttribute <XmlElementAttribute>(customAttributes); XmlTagAttribute tagAttribute = GetAttribute <XmlTagAttribute>(customAttributes); xmlNodeName = elementAttribute?.ElementName ?? rootAttribute?.ElementName ?? xmlNodeName ?? objType.Name; var properties = objType.GetProperties(); var fields = objType.GetFields(); int xmlRootIndex = Append(""); nestCount++; Dictionary <string, string> xmlAttributes = new Dictionary <string, string>(); foreach (var property in properties) { List <Attribute> propertyAttributes = GetXmlAttributes(property); XmlAttributeAttribute xmlAttribute = GetAttribute <XmlAttributeAttribute>(propertyAttributes); if (xmlAttribute != null) { string name = xmlAttribute.AttributeName.Length != 0 ? xmlAttribute.AttributeName : property.Name; xmlAttributes.Add(name, property.GetValue(obj, null).ToString()); } else { SerializeElement(property.GetValue(obj, null), propertyAttributes, property.Name, tagAttribute ?? classTagAttribute); } } foreach (var field in fields) { List <Attribute> fieldAttributes = GetXmlAttributes(field); XmlAttributeAttribute xmlAttribute = GetAttribute <XmlAttributeAttribute>(fieldAttributes); if (xmlAttribute != null) { string name = xmlAttribute.AttributeName.Length != 0 ? xmlAttribute.AttributeName : field.Name; xmlAttributes.Add(name, field.GetValue(obj).ToString()); } else { SerializeElement(field.GetValue(obj), fieldAttributes, field.Name, tagAttribute ?? classTagAttribute); } } nestCount--; Append(string.Format("</{0}>\n", xmlNodeName)); IEnumerable <string> wholeAttributes = xmlAttributes.Select(x => x.Key + "=\"" + x.Value + "\""); string xmlRoot = string.Format("<{0}{1}{2}>\n", xmlNodeName, (wholeAttributes.Any() ? " " : ""), string.Join(" ", wholeAttributes)); stringList[xmlRootIndex] = xmlRoot; } }
public void TimetableFileModelClassNoteDefinitionsPropertyXmlArrayItemAttributeElementNamePropertyEqualsNote() { XmlArrayItemAttribute attr = typeof(SerialData.Xml.Legacy.V3.TimetableFileModel).GetProperty("NoteDefinitions").GetCustomAttributes <XmlArrayItemAttribute>(false).First(); Assert.AreEqual("Note", attr.ElementName); }
/// <summary> /// Adds specified instance of XmlArrayItemAttribute to current type or member /// </summary> public OverrideXml Attr(XmlArrayItemAttribute attribute) { Open(); _attributes.XmlArrayItems.Add(attribute); return(this); }
protected virtual void ProcessProperty(PropertyInfo property, ICollection <Serializer <TContext> > attributeSerializers, ICollection <Serializer <TContext> > elementSerializers) { XmlAttributeAttribute attribute_attribute = null; XmlElementAttribute element_attribute = null; XmlFlagAttribute flag_attribute = null; XmlArrayAttribute array_attribute = null; XmlArrayItemAttribute array_item_attribute = null; XmlValueAttribute value_attribute = null; foreach (var custom_attribute in property.GetCustomAttributes(false)) { if (custom_attribute is DoNotSerializeAttribute) { attribute_attribute = null; element_attribute = null; flag_attribute = null; array_attribute = null; value_attribute = null; break; } var attribute = custom_attribute as XmlAttributeAttribute; if (attribute != null) { attribute_attribute = attribute; continue; } var element = custom_attribute as XmlElementAttribute; if (element != null) { element_attribute = element; continue; } var flag = custom_attribute as XmlFlagAttribute; if (flag != null) { flag_attribute = flag; continue; } var array = custom_attribute as XmlArrayAttribute; if (array != null) { array_attribute = array; continue; } var array_item = custom_attribute as XmlArrayItemAttribute; if (array_item != null) { array_item_attribute = array_item; continue; } var value = custom_attribute as XmlValueAttribute; if (value != null) { value_attribute = value; continue; } } if (attribute_attribute != null) { attributeSerializers.Add( CreateSerializer(property, CreateAttributeSerializer(property, attribute_attribute))); } else if (element_attribute != null) { elementSerializers.Add( CreateSerializer(property, CreateElementSerializer(property, element_attribute))); } else if (flag_attribute != null) { elementSerializers.Add( CreateSerializer(property, CreateFlagSerializer(property, flag_attribute))); } else if (array_attribute != null) { elementSerializers.Add( CreateSerializer(property, CreateArraySerializer(property, array_attribute, array_item_attribute))); } else if (array_item_attribute != null) { elementSerializers.Add( CreateSerializer(property, CreateArrayItemSerializer(property, array_item_attribute))); } else if (value_attribute != null) { elementSerializers.Add( CreateSerializer(property, CreateValueSerializer(property))); } }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int Add(XmlArrayItemAttribute attribute) { return(List.Add(attribute)); }
/// <summary> /// Sets the <see cref="XmlArrayItemAttribute"/> for the property. /// </summary> public OverrideMemberXml <T> Attr(XmlArrayItemAttribute attribute) { Attributes.XmlArrayItems.Add(attribute); return(this); }
public void FormDefault() { XmlArrayItemAttribute attr = new XmlArrayItemAttribute(); Assert.AreEqual(XmlSchemaForm.None, attr.Form); }
public void IsNullableDefault() { XmlArrayItemAttribute attr = new XmlArrayItemAttribute(); Assert.AreEqual(false, attr.IsNullable); }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Remove(XmlArrayItemAttribute attribute) { List.Remove(attribute); }
private static void ImportPropertyInfo(StructMapping mapping, PropertyInfo prop) { Type type = prop.PropertyType; bool flag = false; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)) { flag = true; type = type.GetGenericArguments()[0]; } bool flag2 = false; XmlAttributes xmlAttributes = new XmlAttributes(); object[] array = type.GetCustomAttributes(inherit: true); object[] customAttributes = prop.GetCustomAttributes(inherit: true); bool flag3 = false; int num = array.Length; Array.Resize(ref array, num + customAttributes.Length); customAttributes.CopyTo(array, num); object[] array2 = array; foreach (object obj in array2) { Type type2 = obj.GetType(); if (type2 == typeof(XmlIgnoreAttribute)) { return; } if (typeof(DefaultValueAttribute).IsAssignableFrom(type2)) { xmlAttributes.XmlDefaultValue = ((DefaultValueAttribute)obj).Value; } else if (typeof(XmlElementAttribute).IsAssignableFrom(type2)) { XmlElementAttribute xmlElementAttribute = (XmlElementAttribute)obj; xmlAttributes.XmlElements.Add(xmlElementAttribute); if (xmlElementAttribute.Type != null) { if (string.IsNullOrEmpty(xmlElementAttribute.ElementName)) { type = xmlElementAttribute.Type; } else { flag2 = true; } } } else if (type2 == typeof(XmlArrayItemAttribute)) { XmlArrayItemAttribute xmlArrayItemAttribute = (XmlArrayItemAttribute)obj; int j; for (j = 0; j < xmlAttributes.XmlArrayItems.Count && xmlAttributes.XmlArrayItems[j].NestingLevel <= xmlArrayItemAttribute.NestingLevel; j++) { } xmlAttributes.XmlArrayItems.Insert(j, xmlArrayItemAttribute); } else if (typeof(XmlAttributeAttribute).IsAssignableFrom(type2)) { xmlAttributes.XmlAttribute = (XmlAttributeAttribute)obj; } else if (type2 == typeof(ValidValuesAttribute) || type2 == typeof(ValidEnumValuesAttribute)) { flag3 = true; } } string tagName = prop.Name; string ns = string.Empty; if (!flag2) { GetMemberName(xmlAttributes, ref tagName, ref ns); } if (mapping.GetElement(tagName, ns) != null || mapping.GetAttribute(tagName, ns) != null) { return; } PropertyMapping propertyMapping = new PropertyMapping(type, tagName, ns, prop); propertyMapping.XmlAttributes = xmlAttributes; mapping.Members.Add(propertyMapping); if (xmlAttributes.XmlAttribute != null) { if (xmlAttributes.XmlAttribute is XmlChildAttributeAttribute) { mapping.AddChildAttribute(propertyMapping); } else { mapping.Attributes[tagName, ns] = propertyMapping; } } else { mapping.Elements[tagName, ns] = propertyMapping; if (flag2) { mapping.AddUseTypeInfo(tagName, ns); } } Type declaringType = prop.DeclaringType; if (!declaringType.IsSubclassOf(typeof(ReportObject))) { return; } Type type3 = declaringType.Assembly.GetType(declaringType.FullName + "+Definition+Properties", throwOnError: false); FieldInfo field; if (type3 != null && type3.IsEnum && (field = type3.GetField(prop.Name)) != null) { propertyMapping.Index = (int)field.GetRawConstantValue(); propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.Object; if (flag) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.Object; } else if (type.IsSubclassOf(typeof(IContainedObject))) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.ContainedObject; } else if (type == typeof(bool)) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.Boolean; } else if (type == typeof(int)) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.Integer; } else if (type == typeof(ReportSize)) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.Size; } else if (type.IsEnum) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.Enum; } else if (type.IsValueType) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.ValueType; } if (flag3) { type3 = declaringType.Assembly.GetType(declaringType.FullName + "+Definition", throwOnError: false); propertyMapping.Definition = (IPropertyDefinition)type3.InvokeMember("GetProperty", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.InvokeMethod, null, null, new object[1] { propertyMapping.Index }, CultureInfo.InvariantCulture); } } }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool Contains(XmlArrayItemAttribute attribute) { return(List.Contains(attribute)); }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int IndexOf(XmlArrayItemAttribute attribute) { return(List.IndexOf(attribute)); }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Insert(int index, XmlArrayItemAttribute attribute) { List.Insert(index, attribute); }
public void CopyTo(XmlArrayItemAttribute[] array, int index) { }
public void NamespaceDefault() { XmlArrayItemAttribute attr = new XmlArrayItemAttribute(); Assert.IsNull(attr.Namespace); }
public void Insert(int index, XmlArrayItemAttribute attribute) { }
public void NestingLevelDefault() { XmlArrayItemAttribute attr = new XmlArrayItemAttribute(); Assert.AreEqual(0, attr.NestingLevel); }
public static ShaderWindowSettings LoadConfiguration(out DialogResult result) { if (!File.Exists(ShaderManager.DefaultConfigurationFile)) { result = DialogResult.OK; return(new ShaderWindowSettings()); } var olderVersion = false; using (var reader = XmlReader.Create(ShaderManager.DefaultConfigurationFile)) { olderVersion = reader.ReadToDescendant("ShaderConfiguration") && reader.AttributeCount == 0; } if (olderVersion) { result = MessageBox.Show( Resources.ConfigurationFileUpgrade_Message, Resources.ConfigurationFileUpgrade_Caption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if (result == DialogResult.Cancel) { return(null); } var overrides = new XmlAttributeOverrides(); var shaderAttributes = new XmlAttributes(); var materialElement = new XmlArrayItemAttribute(); materialElement.ElementName = "ShaderConfiguration"; materialElement.Type = typeof(MaterialConfiguration); shaderAttributes.XmlArrayItems.Add(materialElement); overrides.Add(typeof(ShaderWindowSettings), "Shaders", shaderAttributes); var bufferBindingAttributes = new XmlAttributes(); var textureBindingElement = new XmlArrayItemAttribute(); textureBindingElement.ElementName = "TextureBindingConfiguration"; textureBindingElement.Type = typeof(TextureBindingConfiguration); bufferBindingAttributes.XmlArray = new XmlArrayAttribute("TextureBindings"); bufferBindingAttributes.XmlArrayItems.Add(textureBindingElement); overrides.Add(typeof(ShaderConfiguration), "BufferBindings", bufferBindingAttributes); ShaderWindowSettings configuration; var serializer = new XmlSerializer(typeof(ShaderWindowSettings), overrides); using (var reader = XmlReader.Create(ShaderManager.DefaultConfigurationFile)) { configuration = (ShaderWindowSettings)serializer.Deserialize(reader); } if (result == DialogResult.Yes) { ShaderManager.SaveConfiguration(configuration); } else { return(configuration); } } result = DialogResult.OK; try { return(ShaderManager.LoadConfiguration()); } catch { result = DialogResult.Cancel; throw; } }
public void TypeDefault() { XmlArrayItemAttribute attr = new XmlArrayItemAttribute(); Assert.IsNull(attr.Type); }
private void writeObjectFolder(string filePath, object obj) { _ObjectStore.UnMarkSerialized(obj); Type objectType = obj.GetType(), stringType = typeof(String); string folderPath = Path.GetDirectoryName(filePath); HashSet <string> nestedProperties = new HashSet <string>(); List <Tuple <string, object, bool> > queued = new List <Tuple <string, object, bool> >(); IList <PropertyInfo> fields = this.GetFieldsOrdered(objectType); foreach (PropertyInfo propertyInfo in fields) { if (propertyInfo == null) { continue; } Type propertyType = propertyInfo.PropertyType; XmlArrayAttribute xmlArrayAttribute = propertyInfo.GetCustomAttribute <XmlArrayAttribute>(); XmlArrayItemAttribute xmlArrayItemAttribute = propertyInfo.GetCustomAttribute <XmlArrayItemAttribute>(); if (xmlArrayAttribute != null && xmlArrayItemAttribute != null) { bool isLeaf = xmlArrayItemAttribute != null && string.Compare(xmlArrayItemAttribute.DataType, "_leaf_", true) == 0; if (string.IsNullOrEmpty(xmlArrayItemAttribute.ElementName) && xmlArrayItemAttribute.NestingLevel > 0 && propertyType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(propertyType.GetGenericTypeDefinition())) { Type genericType = propertyType.GetGenericArguments()[0]; PropertyInfo uniqueIdProperty = genericType.GetProperty("id", typeof(string)); PropertyInfo folderNameProperty = genericType.GetProperty("_folderName", typeof(string)); if (folderNameProperty == null) { folderNameProperty = uniqueIdProperty; } PropertyInfo nameProp = objectType.GetProperty("Name", typeof(string)); if (uniqueIdProperty != null) { IEnumerable enumerable = propertyInfo.GetValue(obj) as IEnumerable; if (enumerable != null) { bool allSaved = true, nestingValid = true;; int count = 0; foreach (object nested in enumerable) { if (nested == null) { continue; } count++; if (!_ObjectStore.isSerialized(nested)) { allSaved = false; } object objId = uniqueIdProperty.GetValue(nested); if (objId == null || string.IsNullOrEmpty(objId.ToString())) { nestingValid = false; break; } } if (nestingValid && !allSaved) { string nestedPath = Path.Combine(folderPath, removeInvalidFile(propertyInfo.Name)); Directory.CreateDirectory(nestedPath); nestedProperties.Add(propertyInfo.Name); if (xmlArrayItemAttribute.NestingLevel > 1) { string prefix = m_NominatedTypeFilePrefix.Count > 0 ? hasFilePrefix(genericType) : ""; IEnumerable <IGrouping <char, object> > groups = null; if (string.IsNullOrEmpty(prefix)) { groups = enumerable.Cast <object>().GroupBy(x => char.ToLower(uniqueIdProperty.GetValue(x).ToString()[0])); } else { int prefixLength = prefix.Length; groups = enumerable.Cast <object>().GroupBy(x => char.ToLower(initialChar(uniqueIdProperty.GetValue(x).ToString(), prefix, prefixLength))); } foreach (IGrouping <char, object> group in groups) { string alphaPath = Path.Combine(nestedPath, group.Key.ToString()); Directory.CreateDirectory(alphaPath); foreach (object nested in group) { _ObjectStore.MarkSerialized(nested); string nestedObjectPath = isLeaf ? alphaPath : Path.Combine(alphaPath, removeInvalidFile(folderNameProperty.GetValue(nested).ToString())); Directory.CreateDirectory(nestedObjectPath); string fileName = removeInvalidFile((isLeaf ? uniqueIdProperty.GetValue(nested).ToString() : nested.GetType().Name) + ".xml"); queued.Add(new Tuple <string, object, bool>(Path.Combine(nestedObjectPath, fileName), nested, isLeaf)); } } continue; } foreach (object nested in enumerable) { if (nested == null) { continue; } _ObjectStore.MarkSerialized(nested); string nestedObjectPath = isLeaf ? nestedPath : Path.Combine(nestedPath, removeInvalidFile(isLeaf ? uniqueIdProperty.GetValue(nested).ToString() : folderNameProperty.GetValue(nested).ToString())); Directory.CreateDirectory(nestedObjectPath); string fileName = removeInvalidFile((isLeaf ? uniqueIdProperty.GetValue(nested).ToString() : nested.GetType().Name) + ".xml"); queued.Add(new Tuple <string, object, bool>(Path.Combine(nestedObjectPath, fileName), nested, isLeaf)); } } } } } } else { object propertyObject = propertyInfo.GetValue(obj); if (propertyObject == null) { nestedProperties.Add(propertyInfo.Name); } else { DataType dataType = DataType.Custom; string fileExtension = ".txt", txt = ""; foreach (DataTypeAttribute dataTypeAttribute in propertyInfo.GetCustomAttributes <DataTypeAttribute>()) { FileExtensionsAttribute fileExtensionsAttribute = dataTypeAttribute as FileExtensionsAttribute; if (fileExtensionsAttribute != null && !string.IsNullOrEmpty(fileExtensionsAttribute.Extensions)) { fileExtension = fileExtensionsAttribute.Extensions; } if (dataTypeAttribute.DataType != DataType.Custom) { dataType = dataTypeAttribute.DataType; } } if (dataType == DataType.Html) { string html = propertyObject.ToString(); if (!string.IsNullOrEmpty(html)) { nestedProperties.Add(propertyInfo.Name); string htmlPath = Path.Combine(folderPath, propertyInfo.Name + ".html"); File.WriteAllText(htmlPath, html.TrimEnd() + Environment.NewLine, Encoding.UTF8); continue; } } else if (dataType == DataType.MultilineText) { byte[] byteArray = propertyObject as byte[]; if (byteArray != null) { nestedProperties.Add(propertyInfo.Name); txt = Encoding.ASCII.GetString(byteArray); } else { txt = propertyObject.ToString(); } if (!string.IsNullOrEmpty(txt)) { nestedProperties.Add(propertyInfo.Name); string txtPath = Path.Combine(folderPath, propertyInfo.Name + fileExtension); File.WriteAllText(txtPath, txt.TrimEnd() + Environment.NewLine, Encoding.UTF8); continue; } } } } } if (nestedProperties.Count < fields.Count) { _ObjectStore.UnMarkSerialized(obj); using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { writeObject(fileStream, obj, nestedProperties); } } foreach (Tuple <string, object, bool> o in queued) { if (o.Item3) { _ObjectStore.UnMarkSerialized(o.Item2); using (FileStream fileStream = new FileStream(o.Item1, FileMode.Create, FileAccess.Write)) { writeObject(fileStream, o.Item2, new HashSet <string>()); } } else { writeObjectFolder(o.Item1, o.Item2); } } }
public void TimetableFileModelClass_SignalboxHoursSetsPropertyXmlArrayItemAttributeElementNamePropertyEqualsSignalboxHoursSet() { XmlArrayItemAttribute attr = typeof(TimetableFileModel).GetProperty("SignalboxHoursSets").GetCustomAttributes <XmlArrayItemAttribute>(false).First(); Assert.AreEqual("SignalboxHoursSet", attr.ElementName); }
private static void WalkFix(object obj) { #region Validations if (obj == null) { throw new ArgumentNullException(nameof(obj)); } #endregion Type t = obj.GetType(); foreach (var prop in t.GetProperties()) { /* * Array */ if (prop.PropertyType.IsArray == true) { Array arr = (Array)prop.GetValue(obj); if (arr == null) { continue; } if (arr.Length == 0) { continue; } var et = prop.PropertyType.GetElementType(); if (et == typeof(DateTime)) { XmlArrayItemAttribute attr = prop.GetCustomAttribute <XmlArrayItemAttribute>(); for (int i = 0; i < arr.Length; i++) { DateTime vx = (DateTime)arr.GetValue(i); DateTime fx; if (DateTimeFix(attr?.DataType ?? "dateTime", vx, out fx) == true) { arr.SetValue(fx, i); } } continue; } if (et.IsCustomClass() == true) { foreach (var o in arr) { WalkFix(o); } continue; } continue; } /* * DateTime? */ if (prop.PropertyType == typeof(DateTime? )) { DateTime? v = (DateTime?)prop.GetValue(obj); XmlElementAttribute attr = prop.GetCustomAttribute <XmlElementAttribute>(); DateTime f; if (v.HasValue == false) { continue; } if (DateTimeFix(attr?.DataType ?? "dateTime", v.Value, out f) == true) { prop.SetValue(obj, f); } continue; } /* * DateTime */ if (prop.PropertyType == typeof(DateTime)) { DateTime v = (DateTime)prop.GetValue(obj); XmlElementAttribute attr = prop.GetCustomAttribute <XmlElementAttribute>(); DateTime f; if (DateTimeFix(attr?.DataType ?? "dateTime", v, out f) == true) { prop.SetValue(obj, f); } continue; } /* * Nested type */ if (prop.PropertyType.IsCustomClass() == true) { var deep = prop.GetValue(obj); if (deep == null) { continue; } WalkFix(deep); continue; } } }
/// <summary> /// Devuelve un booleano indicando que el atributo es de serializacion en xml /// </summary> /// <param name="att"></param> /// <returns></returns> protected virtual bool InitializeAttribute(Attribute att) { bool output = false; if (att is XmlElementValueAttribute) { XmlElementValueAttribute a = att as XmlElementValueAttribute; if (a.Type == null) { if (TypeHelper.IsValueType(a.Type)) { this.DefaultAttributeName = a.AttributeName; } this.DefaultElementName = a.ElementName; } else { if (TypeHelper.IsValueType(a.Type)) { this.AddAttributeToTypeMap(a.AttributeName, a.Type); this.AddTypeToAttributeMap(a.Type, a.AttributeName); } this.AddElementToTypeMap(a.ElementName, a.Type); this.AddTypeToElementMap(a.Type, a.ElementName); if (!this.IncludeTypes.Contains(a.Type)) { this.AddIncludeTypes(a.Type); } } output = true; } else if (att is XmlContentAttribute) { this.AddAttribute(att); output = true; } else if (att is XmlDateTimeFormatAttribute) { this.AddAttribute(att); output = true; } else if (att is XmlTimeSpanFormatAttribute) { this.AddAttribute(att); output = true; } else if (att is XmlNumericFormatAttribute) { this.AddAttribute(att); output = true; } else if (att is XmlOrderAttribute) { this.Order = ((XmlOrderAttribute)att).Order; } else if (att is XmlIncludeAttribute) { this.IncludeTypes.Add(((XmlIncludeAttribute)att).Type); } else if (att is XmlArrayAttribute) { this.DefaultElementName = ((XmlArrayAttribute)att).ElementName; output = true; } else if (att is XmlInlineArrayAttributeAttribute) { XmlInlineArrayAttributeAttribute a = att as XmlInlineArrayAttributeAttribute; if (a.Type == null) { this.DefaultAttributeName = a.AttributeName; this.DefaultElementName = null; if (!string.IsNullOrEmpty(a.ItemSeparator)) { this.AddAttribute(a); } } else { Type itemType = a.Type.GetElementType(); if (itemType == null) { throw new Exception("No es posible inferir el tipo del item del array de la propiedad " + this.PropertyName + " del tipo " + this.OwnerType.Name); } if (this.PropertyType.IsArray) { Type dcItemType = this.PropertyType.GetElementType(); if (dcItemType == null || !dcItemType.Equals(itemType)) { throw new Exception("El tipo del item del array declarado en el atributo XmlInlineArrayAttributeAttribute es distinto al tipo del item del array de la propiedad " + this.PropertyName + " del tipo " + this.OwnerType.Name); } } //agrego el tipo de el arrar.. this.AddAttributeToTypeMap(a.AttributeName, a.Type); this.AddTypeToAttributeMap(a.Type, a.AttributeName); //agrego el tipo del item this.AddTypeToAttributeItemMap(itemType, a.AttributeName); this.AddAttributeToTypeItemMap(a.AttributeName, itemType); //si el tipo del array es object[], los item son por ej int, detecta que no es inline, pero al serializaer los items va //a detectar que cada item se tiene que serializar como attributo, pero no tiene elemento definido..... //this.AddTypeToElementItemMap(a.Type.GetElementType(), a.AttributeName); //this.AddElementToTypeItemMap(a.AttributeName, a.Type.GetElementType()); //el separador lo busco en la lista de attributos this.AddAttribute(att); if (!this.IncludeTypes.Contains(a.Type)) { this.AddIncludeTypes(a.Type); } } output = true; } else if (att is XmlInlineArrayElementAttribute) { XmlInlineArrayElementAttribute a = att as XmlInlineArrayElementAttribute; if (a.Type == null) { this.DefaultAttributeName = null; this.DefaultElementName = a.ElementName; if (!string.IsNullOrEmpty(a.ItemSeparator)) { this.AddAttribute(a); } } else { //agrego el tipo del item this.AddTypeToElementItemMap(a.Type.GetElementType(), a.ElementName); this.AddElementToTypeItemMap(a.ElementName, a.Type.GetElementType()); //agrego el tipo de el arrar.. this.AddElementToTypeMap(a.ElementName, a.Type); this.AddTypeToElementMap(a.Type, a.ElementName); //el separador lo busco en la lista de attributos this.AddAttribute(att); if (!this.IncludeTypes.Contains(a.Type)) { this.AddIncludeTypes(a.Type); } } output = true; } else if (att is XmlArrayItemValueAttribute) { XmlArrayItemValueAttribute a = att as XmlArrayItemValueAttribute; if (a.Type == null) { this.DefaulItemAttributeName = a.AttributeName; this.DefaultItemElementName = a.ElementName; } else { this.AddTypeToElementItemMap(a.Type, a.ElementName); this.AddElementToTypeItemMap(a.ElementName, a.Type); if (TypeHelper.IsValueType(a.Type)) { this.AddTypeToAttributeItemMap(a.Type, a.AttributeName); this.AddAttributeToTypeItemMap(a.AttributeName, a.Type); } if (!this.IncludeTypes.Contains(a.Type)) { this.AddIncludeTypes(a.Type); } } output = true; } else if (att is XmlArrayItemAttribute) { XmlArrayItemAttribute a = att as XmlArrayItemAttribute; if (a.Type == null) { this.DefaultItemElementName = a.ElementName; } else { this.AddTypeToElementItemMap(a.Type, a.ElementName); this.AddElementToTypeItemMap(a.ElementName, a.Type); if (!this.IncludeTypes.Contains(a.Type)) { this.AddIncludeTypes(a.Type); } } output = true; } else if (att is XmlDictionaryKeyElementAttribute) { XmlDictionaryKeyElementAttribute a = att as XmlDictionaryKeyElementAttribute; if (a.Type == null) { this.DefaultDictionaryKeyElementName = a.ElementName; } else { this.AddElementToTypeDictionaryKeyMap(a.ElementName, a.Type); this.AddTypeToElementDictionaryKeyMap(a.Type, a.ElementName); if (!this.IncludeTypes.Contains(a.Type)) { this.AddIncludeTypes(a.Type); } } output = true; } else if (att is XmlDictionaryValueElementAttribute) { XmlDictionaryValueElementAttribute a = att as XmlDictionaryValueElementAttribute; if (a.Type == null) { this.DefaultDictionaryValueElementName = a.ElementName; } else { this.AddElementToTypeDictionaryValueMap(a.ElementName, a.Type); this.AddTypeToElementDictionaryValueMap(a.Type, a.ElementName); if (!this.IncludeTypes.Contains(a.Type)) { this.AddIncludeTypes(a.Type); } } output = true; } else if (att is XmlDictionaryKeyAttributeAttribute) { XmlDictionaryKeyAttributeAttribute a = att as XmlDictionaryKeyAttributeAttribute; if (a.Type == null) { Type declaringType = this.PropertyType; Type keyType = typeof(object); if (declaringType.IsGenericType) { Type[] genercisTypes = declaringType.GetGenericArguments(); keyType = genercisTypes[0]; } if (TypeHelper.IsValueType(keyType)) { this.DefaultDictionaryKeyAttributeName = a.AttributeName; } } else { if (TypeHelper.IsValueType(a.Type)) { this.AddAttributeToTypeDictionaryKeyMap(a.AttributeName, a.Type); this.AddTypeToAttributeDictionaryKeyMap(a.Type, a.AttributeName); } if (!this.IncludeTypes.Contains(a.Type)) { this.AddIncludeTypes(a.Type); } } output = true; } else if (att is XmlDictionaryValueAttributeAttribute) { XmlDictionaryValueAttributeAttribute a = att as XmlDictionaryValueAttributeAttribute; if (a.Type == null) { Type declaringType = this.PropertyType; Type valueType = typeof(object); if (declaringType.IsGenericType) { Type[] genercisTypes = declaringType.GetGenericArguments(); valueType = genercisTypes[0]; } if (TypeHelper.IsValueType(valueType)) { this.DefaultDictionaryValueAttributeName = a.AttributeName; } } else { if (TypeHelper.IsValueType(a.Type)) { this.AddAttributeToTypeDictionaryValueMap(a.AttributeName, a.Type); this.AddTypeToAttributeDictionaryValueMap(a.Type, a.AttributeName); } if (!this.IncludeTypes.Contains(a.Type)) { this.AddIncludeTypes(a.Type); } } output = true; } else if (att is XmlDictionaryItemElementAttribute) { this.DictionaryItemElementName = ((XmlDictionaryItemElementAttribute)att).ElementName; output = true; } else if (att is XmlElementAttribute) { XmlElementAttribute atElem = (XmlElementAttribute)att; if (!string.IsNullOrEmpty(atElem.ElementName)) { if (atElem.Type != null) { this.AddElementToTypeMap(atElem.ElementName, atElem.Type); this.AddTypeToElementMap(atElem.Type, atElem.ElementName); if (!this.IncludeTypes.Contains(atElem.Type)) { this.AddIncludeTypes(atElem.Type); } } else { this.DefaultElementName = atElem.ElementName; } } else { this.DefaultElementName = this.PropertyName; } output = true; } else if (att is XmlAttributeAttribute) { XmlAttributeAttribute atElem = (XmlAttributeAttribute)att; if (!string.IsNullOrEmpty(atElem.AttributeName)) { if (atElem.Type != null) { if (TypeHelper.IsValueType(atElem.Type)) { this.AddAttributeToTypeMap(atElem.AttributeName, atElem.Type); this.AddTypeToAttributeMap(atElem.Type, atElem.AttributeName); } if (!this.IncludeTypes.Contains(atElem.Type)) { this.AddIncludeTypes(atElem.Type); } } else { if (TypeHelper.IsValueType(this.PropertyType)) { this.DefaultAttributeName = atElem.AttributeName; } } } else { this.DefaultAttributeName = this.PropertyName; } output = true; } else { this.AddAttribute(att as Attribute); } return(output); }
public void Configure(XmlArrayItemAttribute attribute) { itemAccessor.Configure(attribute); }
private object ReadArrayContent(object array, ArrayMapping mapping, MemberMapping member, int nestingLevel) { IList list = (IList)array; if (m_reader.IsEmptyElement) { m_reader.Skip(); } else { m_reader.ReadStartElement(); m_reader.MoveToContent(); while (m_reader.NodeType != XmlNodeType.EndElement && m_reader.NodeType != 0) { if (m_reader.NodeType == XmlNodeType.Element) { string localName = m_reader.LocalName; _ = m_reader.NamespaceURI; Type value = null; bool flag = false; if (member != null && member.XmlAttributes.XmlArrayItems.Count > nestingLevel) { if (localName == member.XmlAttributes.XmlArrayItems[nestingLevel].ElementName) { XmlArrayItemAttribute xmlArrayItemAttribute = member.XmlAttributes.XmlArrayItems[nestingLevel]; value = xmlArrayItemAttribute.Type; flag = xmlArrayItemAttribute.IsNullable; } } else { XmlElementAttributes xmlElementAttributes = null; if (base.XmlOverrides != null) { XmlAttributes xmlAttributes = base.XmlOverrides[mapping.ItemType]; if (xmlAttributes != null && xmlAttributes.XmlElements != null) { xmlElementAttributes = xmlAttributes.XmlElements; } } if (xmlElementAttributes == null) { mapping.ElementTypes.TryGetValue(localName, out value); } else { foreach (XmlElementAttribute item in xmlElementAttributes) { if (localName == item.ElementName) { value = item.Type; break; } } } } if (value != null) { object value2; if (flag && m_reader.GetAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance") == "true") { m_reader.Skip(); value2 = null; } else { value2 = ReadObject(value, member, nestingLevel + 1); } list.Add(value2); } else { m_reader.Skip(); } } else { m_reader.Skip(); } m_reader.MoveToContent(); } m_reader.ReadEndElement(); } return(array); }
void ProcessType() { attribute_deserializers = new Dictionary <string, ObjectDeserializer> (); element_deserializers = new Dictionary <string, ObjectDeserializer> (); foreach (var property in Properties) { XmlElementAttribute element_attribute = null; XmlFlagAttribute flag_attribute = null; XmlArrayAttribute array_attribute = null; XmlArrayItemAttribute array_item_attribute = null; XmlAttributeAttribute attribute_attribute = null; foreach (var custom_attribute in property.GetCustomAttributes(false)) { if (custom_attribute is DoNotDeserializeAttribute) { element_attribute = null; flag_attribute = null; array_attribute = null; attribute_attribute = null; value_property = null; break; } var element = custom_attribute as XmlElementAttribute; if (element != null) { element_attribute = element; continue; } var flag = custom_attribute as XmlFlagAttribute; if (flag != null) { flag_attribute = flag; continue; } var array = custom_attribute as XmlArrayAttribute; if (array != null) { array_attribute = array; continue; } var array_item = custom_attribute as XmlArrayItemAttribute; if (array_item != null) { array_item_attribute = array_item; continue; } var attribute = custom_attribute as XmlAttributeAttribute; if (attribute != null) { attribute_attribute = attribute; continue; } if (custom_attribute is XmlValueAttribute) { // TODO check if this isn't null and throw value_property = property; continue; } } if (element_attribute != null) { var deserializer = CreateCustomDeserializer(property) ?? CreateElementDeserializer(property); AddDeserializer(element_deserializers, CreateName(property.Name, element_attribute.Name, element_attribute.Namespace), deserializer); continue; } if (flag_attribute != null) { AddDeserializer(element_deserializers, CreateName(property.Name, flag_attribute.Name, flag_attribute.Namespace), CreateFlagDeserializer(property)); continue; } if (array_attribute != null) { AddDeserializer(element_deserializers, CreateName(property.Name, array_attribute.Name, array_attribute.Namespace), CreateArrayElementDeserializer(property)); continue; } else if (array_item_attribute != null) { var name = array_item_attribute.Name; var @namespace = array_item_attribute.Namespace; if (string.IsNullOrEmpty(name)) { var item_type = GetICollection(property.PropertyType).GetGenericArguments()[0]; var type_attribute = item_type.GetCustomAttributes(typeof(XmlTypeAttribute), false); if (type_attribute.Length == 0) { name = item_type.Name; } else { var xml_type = (XmlTypeAttribute)type_attribute[0]; name = string.IsNullOrEmpty(xml_type.Name) ? item_type.Name : xml_type.Name; @namespace = xml_type.Namespace; } } AddDeserializer(element_deserializers, CreateName(name, @namespace), CreateArrayItemElementDeserializer(property)); } if (attribute_attribute != null) { var deserializer = CreateCustomDeserializer(property) ?? CreateAttributeDeserializer(property); AddDeserializer(attribute_deserializers, CreateName(property.Name, attribute_attribute.Name, attribute_attribute.Namespace), deserializer); continue; } } }
public void TimetableDocumentTemplateModelClass_NoteDefinitionsPropertyXmlArrayItemAttributeElementNamePropertyEqualsNote() { XmlArrayItemAttribute attr = typeof(TimetableDocumentTemplateModel).GetProperty("NoteDefinitions").GetCustomAttributes <XmlArrayItemAttribute>(false).First(); Assert.AreEqual("Note", attr.ElementName); }
public void TimetableFileModelClassTrainListPropertyXmlArrayItemAttributeElementNamePropertyEqualsTrain() { XmlArrayItemAttribute attr = typeof(SerialData.Xml.Legacy.V3.TimetableFileModel).GetProperty("TrainList").GetCustomAttributes <XmlArrayItemAttribute>(false).First(); Assert.AreEqual("Train", attr.ElementName); }
public void TimetableDocumentTemplateModelClass_TrainClassesPropertyXmlArrayItemAttributeElementNamePropertyEqualsTrainClass() { XmlArrayItemAttribute attr = typeof(TimetableDocumentTemplateModel).GetProperty("TrainClasses").GetCustomAttributes <XmlArrayItemAttribute>(false).First(); Assert.AreEqual("TrainClass", attr.ElementName); }
public bool Contains(XmlArrayItemAttribute attribute) { }
public XmlSchemaType WriteArrayType(Type type, MemberInfo member) { if (generatedSchemaTypes.Contains(type.FullName)) // Caching { return(null); } XmlSchemaComplexType complexType = new XmlSchemaComplexType(); XmlQualifiedName qname = GetQualifiedName(type); if (qname == null) { complexType.Name = type.Name; } else { complexType.Name = qname.Name; } XmlSchemaSequence sequence = new XmlSchemaSequence(); XmlSchemaElement element = new XmlSchemaElement(); element.MinOccurs = 0; element.MaxOccursString = "unbounded"; element.IsNillable = true; element.Name = qname.Name.ToLower(); object [] attrs = member.GetCustomAttributes(false); if (attrs.Length > 0) { foreach (object o in attrs) { if (o is XmlArrayItemAttribute) { if (type.IsArray == false) { throw new ArgumentException( String.Format("XmlArrayAttribute is not applicable to {0}, because it is not an array.", member.Name)); } XmlArrayItemAttribute attr = (XmlArrayItemAttribute)o; if (attr.ElementName.Length != 0) { element.Name = attr.ElementName; } continue; } if (o is XmlAnyElementAttribute) { return(null); } } } element.SchemaTypeName = GetQualifiedName( type.FullName.Substring(0, type.FullName.Length - 2)); sequence.Items.Add(element); complexType.Particle = sequence; generatedSchemaTypes.Add(type.FullName, complexType); return(complexType); }
public int IndexOf(XmlArrayItemAttribute attribute) { }
public void LocationTemplateModelClass_MapsPropertyXmlArrayItemAttributeElementNamePropertyEqualsMap() { XmlArrayItemAttribute attr = typeof(LocationTemplateModel).GetProperty("Maps").GetCustomAttributes <XmlArrayItemAttribute>(false).First(); Assert.AreEqual("Map", attr.ElementName); }
public void Remove(XmlArrayItemAttribute attribute) { }
/// <summary> /// Fills the struct with information about the field /// </summary> /// <param name="info">Struct to fill</param> /// <param name="field">Field descrived by the struct</param> private static void _FillInfo(ref SFieldInfo info, MemberInfo field) { XmlAttributeAttribute attribute = field.GetAttribute <XmlAttributeAttribute>(); if (attribute != null) { info.IsAttribute = true; info.Name = attribute.AttributeName; } else { XmlElementAttribute element = field.GetAttribute <XmlElementAttribute>(); if (element != null) { info.Name = element.ElementName; } else { XmlArrayAttribute array = field.GetAttribute <XmlArrayAttribute>(); if (array != null) { Debug.Assert(info.Type.IsList() || info.Type.IsArray, "Only lists and arrays can have the array attribute"); Debug.Assert(!info.IsAttribute, "Lists cannot be attributes"); info.Name = array.ElementName; info.IsList = true; } } } if (string.IsNullOrEmpty(info.Name)) { info.Name = field.Name; } XmlAltNameAttribute altName = field.GetAttribute <XmlAltNameAttribute>(); if (altName != null) { info.AltName = altName.AltName; } if (info.Type.IsGenericType) { info.SubType = info.Type.GetGenericArguments().Last(); } else if (info.Type.IsArray) { info.SubType = info.Type.GetElementType(); } if (info.Type.IsList() || info.Type.IsArray) { if (!info.IsList) { Debug.Assert(!field.HasAttribute <XmlArrayAttribute>(), "A field cannot have an XmlElement- and XmlArray-Attribute"); if (info.Type.IsArray && info.SubType == typeof(byte)) { info.IsByteArray = true; } else { info.IsEmbeddedList = true; } } else { XmlArrayItemAttribute arrayItem = field.GetAttribute <XmlArrayItemAttribute>(); if (arrayItem != null && !string.IsNullOrEmpty(arrayItem.ElementName)) { info.ArrayItemName = arrayItem.ElementName; } } } else if (info.Type.IsNullable()) { info.IsNullable = true; } else if (info.Type.IsDictionary()) { Debug.Assert(info.Type.GetGenericArguments()[0] == typeof(string), "Keys of dictionaries must be strings"); info.IsDictionary = true; } if (field.HasAttribute <XmlNormalizedAttribute>()) { Debug.Assert(info.Type == typeof(float) || (info.IsNullable && info.SubType == typeof(float)), "Only floats can be normalized"); } info.Ranged = field.GetAttribute <XmlRangedAttribute>(); Type tmpType = info.IsNullable ? info.SubType : info.Type; Debug.Assert(info.Ranged == null || tmpType == typeof(int) || tmpType == typeof(float) || tmpType == typeof(double), "Only ints,floats and double can be ranged"); DefaultValueAttribute defAttr = field.GetAttribute <DefaultValueAttribute>(); if (defAttr != null) { Debug.Assert(!info.Type.IsList(), "Lists cannot have a default value"); info.HasDefaultValue = true; info.DefaultValue = defAttr.Value; } else if (info.IsNullable) { info.HasDefaultValue = true; info.DefaultValue = null; } }