public SetterFieldDescription GetSetterFieldDescription() { TypeSyntax fieldType; if (ContainingType != null && ContainingType.IsValueType) { fieldType = _libraryTypes.ValueTypeSetter_2.ToTypeSyntax(GetTypeSyntax(ContainingType), TypeSyntax); } else { fieldType = _libraryTypes.Action_2.ToTypeSyntax(GetTypeSyntax(ContainingType), TypeSyntax); } // Generate syntax to initialize the field in the constructor var fieldAccessorUtility = AliasQualifiedName("global", IdentifierName("Orleans.Serialization")).Member("Utilities").Member("FieldAccessor"); var fieldInfo = SerializableMember.GetGetFieldInfoExpression(ContainingType, FieldName); var isContainedByValueType = ContainingType != null && ContainingType.IsValueType; var accessorMethod = isContainedByValueType ? "GetValueSetter" : "GetReferenceSetter"; var accessorInvoke = CastExpression( fieldType, InvocationExpression(fieldAccessorUtility.Member(accessorMethod)) .AddArgumentListArguments(Argument(fieldInfo))); var initializationSyntax = ExpressionStatement( AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(SetterFieldName), accessorInvoke)); return(new SetterFieldDescription(fieldType, SetterFieldName, initializationSyntax)); }
public IEnumerable <SerializableMember> EnumerateMembersToSerialize(TypeInfo forType) { var ix = SerializableMember.ForProperty(typeof(_BridgeDelegate).GetProperty(nameof(_BridgeDelegate.Ix))); var foo = SerializableMember.ForProperty(typeof(_BridgeDelegate).GetProperty(nameof(_BridgeDelegate.Foo))); return(new[] { ix, foo }); }
public void SetUp() { member = new SerializableMember { ClassCoupling = 1, CylomaticComplexity = 2, LinesOfCode = 3, MissingDefaultCase = 4, Name = "member", NoFallthrough = 5, NumberOfParameters = 6 }; toSerialize = new SerializableClass { ClassCoupling = 1, CyclomaticComplexity = 2, DepthOfInheritance = 3, LinesOfCode = 4, NumberOfMethods = 5, Toxicity = 6, Name = "MyClass", CodeBag = new SerializeableCodeBag { Name = "MyNamespace" }, Members = new[] { member } }; }
/// <summary> /// 序列化指定成员; /// </summary> /// <exception cref="ObjectDisposedException"></exception> /// <exception cref="InvalidOperationException"></exception> private void Serialize(Content writableContent, ref T instance, SerializableMember member) { using (var stream = writableContent.GetOutputStream(member.MemberInfo.RelativePath)) { var value = member.MemberInfo.GetValue(instance); member.Serializer.Serialize(stream, value); } }
static XmlObjectSerializer() { var members = ResolveFields(typeof(T)) .Select(field => Handle( field, field.FieldType, field.IsPublic ) ).Concat(ResolveProperties(typeof(T)) // Ignore index properties .Where(property => property.GetIndexParameters().IsNullOrEmpty()) .Select(property => Handle( property, property.PropertyType, property.CanRead && property.CanWrite && (property.IsPublic() || property.HasPublicSetter()) ) ) ) .Where(Func.NotNull) .ToLookup(member => member.NodeType); AttributeMembers = members[XmlNodeType.Attribute].Where(member => !member.MatchAny).ToDictionary(member => member.MemberName); AnyAttributeMember = members[XmlNodeType.Attribute].Where(member => member.MatchAny).FirstOrDefault(); ElementMembers = members[XmlNodeType.Element] .GroupBy(member => member.Order) .OrderBy(grp => grp.Key) .Select(grp => grp.ToList()) .ToList(); TextMember = members[XmlNodeType.Text].SingleOrDefault(); var knownTypes = new Queue <XmlIncludeAttribute>(typeof(T).GetCustomAttributes <XmlIncludeAttribute>(inherit: false)); if (knownTypes.Any()) { KnownTypeSerializers = new Dictionary <Type, Tuple <String, IXmlSerializer> >(); KnownTypeSerializersByName = new Dictionary <String, IXmlSerializer>(); while (knownTypes.Any()) { var knownType = knownTypes.Dequeue(); var serializer = XmlSerializerBase.ForType(knownType.Type); // TODO figure out the type name mapping for primitives. var typeName = knownType.Type.Name; KnownTypeSerializers.Add(knownType.Type, Tuple.Create(typeName, serializer)); KnownTypeSerializersByName.Add(typeName, serializer); foreach (var subKnownType in knownType.Type.GetCustomAttributes <XmlIncludeAttribute>(inherit: false)) { knownTypes.Enqueue(subKnownType); } } } }
ComponentBlueprint ParseComponentBlueprint(string name, JsonData componentData) { var componentBlueprint = new ComponentBlueprint(name); var members = new SerializableMember[componentData.Count]; int i = 0; foreach (KeyValuePair <string, JsonData> n in componentData) { members[i] = new JsonSerializableMember(n.Key, n.Value); i++; } componentBlueprint.Members = members; return(componentBlueprint); }
private void Add(MemberInfo info, object value) { if (Utility.IsNull(value)) { throw new NullReferenceException(); } Debugging.Verbose("Adding member " + Utility.GetObjectMemberName(info) + " with value " + value + " IsNull: " + (value == null)); SerializableMember member = new SerializableMember(info, value); if (!member.IsJSONEmpty()) { _members.Add(member); } }
/// <summary> /// 反序列化成员; /// </summary> /// <exception cref="FileNotFoundException"></exception> /// <exception cref="ObjectDisposedException"></exception> private void Deserialize(Content content, T instance, SerializableMember member) { try { using (var stream = content.GetInputStream(member.MemberInfo.RelativePath)) { var value = member.Serializer.Deserialize(stream); member.MemberInfo.SetValue(instance, value); } } catch (FileNotFoundException ex) { if (member.MemberInfo.IsNecessaryAsset) { throw ex; } } }
public void Simple_Serialize() { var surrogate = new SurrogateTypeDescriber(false); surrogate.AddSurrogateType(typeof(_Simple_Real).GetTypeInfo(), typeof(_Simple_Surrogate).GetTypeInfo()); // maps! { var res = surrogate.EnumerateMembersToSerialize(typeof(_Simple_Real).GetTypeInfo()); Assert.Collection( res, a => { Assert.True(a.EmitDefaultValue); Assert.Null(a.Field); Assert.Equal(SerializableMember.GetDefaultFormatter(typeof(string).GetTypeInfo()), a.Formatter); Assert.Equal("bar", a.Name); Assert.Equal(typeof(_Simple_Real).GetProperty(nameof(_Simple_Real.Foo)).GetMethod, a.Getter); Assert.Null(a.ShouldSerialize); } ); } // doesn't map { var res = surrogate.EnumerateMembersToSerialize(typeof(_Simple_Surrogate).GetTypeInfo()); Assert.Collection( res, a => { Assert.True(a.EmitDefaultValue); Assert.Null(a.Field); Assert.Equal(SerializableMember.GetDefaultFormatter(typeof(string).GetTypeInfo()), a.Formatter); Assert.Equal("bar", a.Name); Assert.Equal(typeof(_Simple_Surrogate).GetProperty(nameof(_Simple_Surrogate.Foo)).GetMethod, a.Getter); Assert.Null(a.ShouldSerialize); } ); } }
public void SetUp() { versionInfo = new SerializableClassVersionInfo { CommitMessage = "msg", FileName = "filename", TimeStamp = DateTime.Now }; member = new SerializableMember { ClassCoupling = 1, CylomaticComplexity = 2, LinesOfCode = 3, MissingDefaultCase = 4, Name = "member", NoFallthrough = 5, NumberOfParameters = 6 }; toSerialize = new SerializableClass { ClassCoupling = 1, CyclomaticComplexity = 2, DepthOfInheritance = 3, LinesOfCode = 4, NumberOfMethods = 5, Toxicity = 6, Name = "MyClass", CodeBag = new SerializeableCodeBag { Name = "MyNamespace" }, Meta = new[] { versionInfo }, Members = new[] { member } }; }
public GetterFieldDescription(TypeSyntax fieldType, string fieldName, ITypeSymbol targetFieldType, SerializableMember member) : base(fieldType, fieldName) { this.TargetFieldType = targetFieldType; this.Member = member; }
private static SerializableMember Handle <TMember>(TMember member, Type memberType, Boolean includeByDefault) where TMember : MemberInfo { var xmlAttribute = Attribute.GetCustomAttributes(member, inherit: false) .Where(attr => XmlObjectSerializer <T> .SupportedAttributeTypes.Contains(attr.GetType()) || XmlObjectSerializer <T> .UnsupportedAttributeTypes.Contains(attr.GetType())) .SingleOrDefault(); SerializableMember result; if (xmlAttribute == null) { if (includeByDefault) { result = new SerializableMember(XmlNodeType.Element, new XmlNameDeclaration(member.Name), -1, member); } else { // Skip result = null; } } else if (xmlAttribute is XmlElementAttribute) { var elem = (XmlElementAttribute)xmlAttribute; if (XmlCollectionSerializer.IsCollection(memberType) && !typeof(IXmlSerializable).IsAssignableFrom(memberType)) { result = new SerializableMember( XmlNodeType.Element, new XmlNameDeclaration( elem.ElementName.EmptyAsNull() ?? member.Name, elem.Namespace.EmptyAsNull() ), elem.Order, member, // If an XmlElement is specified on a collection type the members of the collection are serialized without a containing element. wrapCollection: false ); } else { result = new SerializableMember( XmlNodeType.Element, new XmlNameDeclaration( elem.ElementName.EmptyAsNull() ?? member.Name, elem.Namespace.EmptyAsNull() ), elem.Order, member ); } } else if (xmlAttribute is XmlAnyElementAttribute) { var elem = (XmlAnyElementAttribute)xmlAttribute; result = new SerializableMember( XmlNodeType.Element, elem.Order, member ); } else if (xmlAttribute is XmlArrayAttribute) { if (!XmlCollectionSerializer.IsCollection(memberType)) { throw new InvalidOperationException( String.Format( "The XmlArrayAttribute was used on a member of type '{0}' which does not implement ICollection<>.", memberType.FullName ) ); } var array = (XmlArrayAttribute)xmlAttribute; var arrayItems = member.GetCustomAttributes <XmlArrayItemAttribute>().EmptyAsNull(); result = new SerializableMember( XmlNodeType.Element, new XmlNameDeclaration( array.ElementName.EmptyAsNull() ?? member.Name, array.Namespace.EmptyAsNull() ), array.Order, member, arrayItems: arrayItems ); } else if (xmlAttribute is XmlAttributeAttribute) { var attr = (XmlAttributeAttribute)xmlAttribute; // Attribute children do not inherit the namespace of their parent. result = new SerializableMember( XmlNodeType.Attribute, new XmlNameDeclaration( attr.AttributeName.EmptyAsNull() ?? member.Name, attr.Namespace.EmptyAsNull() ), -1, member ); } else if (xmlAttribute is XmlAnyAttributeAttribute) { result = new SerializableMember( XmlNodeType.Attribute, -1, member ); } else if (xmlAttribute is XmlTextAttribute) { // var txt = (XmlTextAttribute)xmlAttribute; // TODO: support DataType/Type/TypeId parameters result = new SerializableMember(XmlNodeType.Text, null, -1, member); } else if (xmlAttribute is XmlIgnoreAttribute) { // Skip result = null; } else { throw new NotSupportedException( String.Format( "The XML serialization attribute '{0}' is not yet supported", xmlAttribute.GetType().Name ) ); } return(result); }
public override T Deserialize(XmlReader reader, T instance, Action <XmlReader> onUnknownElement = null) { // See if we should be using a subtype serializer if (KnownTypeSerializersByName != null) { var xsiType = reader.GetAttribute("type", "http://www.w3.org/2001/XMLSchema-instance"); if (xsiType != null) { IXmlSerializer subTypeSerializer; if (KnownTypeSerializersByName.TryGetValue(xsiType, out subTypeSerializer)) { return((T)subTypeSerializer.Deserialize(reader, subTypeSerializer.CreateInstance())); } } } // We're the actual serializer that should be used for this element. // Here comes the heavy lifting. var startElement = reader.Name; while (reader.MoveToNextAttribute()) { SerializableMember member; if (AttributeMembers.TryGetValue(reader.GetQualifiedName(), out member) || AttributeMembers.TryGetValue(new XmlQualifiedName(reader.LocalName), out member)) { instance = member.DeserializeMember(reader, instance); } else if (AnyAttributeMember != null) { instance = AnyAttributeMember.DeserializeMember(reader, instance); } } reader.MoveToElement(); if (!reader.IsEmptyElement) { // Advance to the first child reader.Read(); var pos = 0; while (reader.NodeType != XmlNodeType.EndElement) { switch (reader.NodeType) { case XmlNodeType.Element: SerializableMember member = null; var nextPos = pos; while (member == null && nextPos < ElementMembers.Count) { member = ElementMembers[nextPos].SingleOrDefault( mem => !mem.MatchAny && mem.MemberName.Equals(reader.GetQualifiedName()) ); if (member == null) { member = ElementMembers[nextPos].SingleOrDefault( mem => mem.MatchAny ); } if (member == null) { nextPos++; } } if (member != null) { pos = nextPos; var xsiNil = reader.GetAttribute("nil", XsiNamespace); if (xsiNil != null && String.Equals(xsiNil, "true", StringComparison.OrdinalIgnoreCase)) { if (member.Setter != null) { instance = member.Setter(instance, member.MemberType.GetDefaultValue()); } } else { instance = member.DeserializeMember(reader, instance); } } else { // Ignore unexpected elements if (onUnknownElement != null) { onUnknownElement(reader); } else { reader.Skip(); } } break; case XmlNodeType.Text: case XmlNodeType.CDATA: if (TextMember != null) { instance = TextMember.DeserializeMember(reader, instance); } else { reader.Skip(); } break; case XmlNodeType.None: throw new XmlException("Unexpected end of document."); default: reader.Skip(); break; } } if (reader.NodeType != XmlNodeType.EndElement || reader.Name != startElement) { throw new XmlException("Unexpected end element found."); } else { reader.ReadEndElement(); } } else { // Done reader.Skip(); } return(instance); }