-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
AvroContractResolver.cs
218 lines (187 loc) · 9.09 KB
/
AvroContractResolver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
/** Modifications copyright(C) 2021 Adrian Strugala **/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using SolTechnology.Avro.Infrastructure.Attributes;
using SolTechnology.Avro.Infrastructure.Extensions;
namespace SolTechnology.Avro.AvroObjectServices.BuildSchema
{
/// <summary>
/// Allows optionally using standard <see cref="T:System.Runtime.Serialization.DataContractAttribute"/> and
/// <see cref="T:System.Runtime.Serialization.DataMemberAttribute"/> attributes for defining what types/properties/fields
/// should be serialized.
/// </summary>
internal class AvroContractResolver
{
private readonly bool _allowNullable;
private readonly bool _useAlphabeticalOrder;
private readonly bool _includeOnlyDataContractMembers;
/// <summary>
/// Initializes a new instance of the <see cref="AvroContractResolver"/> class.
/// </summary>
/// <param name="usePropertyNameAsAlias">If set to <c>true</c>, Aliases get set to property names.</param>
/// <param name="allowNullable">If set to <c>true</c>, null values are allowed.</param>
/// <param name="useAlphabeticalOrder">If set to <c>true</c> use alphabetical data member order during serialization/deserialization.</param>
/// <param name="includeOnlyDataContractMembers">If set to <c>true</c> members without DataMemberAttribute won't be taken into consideration in serialization/deserialization.</param>
internal AvroContractResolver(
bool allowNullable = false,
bool useAlphabeticalOrder = false,
bool includeOnlyDataContractMembers = false)
{
_allowNullable = allowNullable;
_useAlphabeticalOrder = useAlphabeticalOrder;
_includeOnlyDataContractMembers = includeOnlyDataContractMembers;
}
/// <summary>
/// Gets the serialization information about the type.
/// This information is used for creation of the corresponding schema node.
/// </summary>
/// <param name="type">The type to resolve.</param>
/// <param name="member">The member type containing the type, if specified</param>
/// <returns>
/// Serialization information about the type.
/// </returns>
/// <exception cref="System.ArgumentNullException">The type argument is null.</exception>
internal TypeSerializationInfo ResolveType(Type type, MemberInfo member = null)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (type.IsUnsupported())
{
throw new NotSupportedException(
string.Format(CultureInfo.InvariantCulture, "Type [{0}] is not supported by the AvroConvert.", type));
}
bool isNullable = this._allowNullable || type.CanContainNull() || (!type.IsValueType && member?.IsNullableReferenceType() == true);
if (type.IsInterface() ||
type.IsNativelySupported() ||
(type.IsEnum() && !type.GetTypeInfo().GetCustomAttributes(false).OfType<DataContractAttribute>().Any()))
{
return new TypeSerializationInfo
{
Name = SolTechnology.Avro.Infrastructure.Extensions.TypeExtensions.StripAvroNonCompatibleCharacters(type.Name),
Namespace = SolTechnology.Avro.Infrastructure.Extensions.TypeExtensions.StripAvroNonCompatibleCharacters(type.Namespace),
Nullable = isNullable
};
}
type = Nullable.GetUnderlyingType(type) ?? type;
var attributes = type.GetTypeInfo().GetCustomAttributes(false);
var dataContract = attributes.OfType<DataContractAttribute>().SingleOrDefault();
if (dataContract == null && _includeOnlyDataContractMembers)
{
throw new SerializationException(
string.Format(CultureInfo.InvariantCulture, "Type '{0}' is not supported by the resolver.", type));
}
var result = new TypeSerializationInfo
{
Name = SolTechnology.Avro.Infrastructure.Extensions.TypeExtensions.StripAvroNonCompatibleCharacters(dataContract?.Name ?? type.Name),
Namespace = SolTechnology.Avro.Infrastructure.Extensions.TypeExtensions.StripAvroNonCompatibleCharacters(dataContract?.Namespace ?? type.Namespace),
Nullable = isNullable,
Doc = attributes.OfType<DescriptionAttribute>().SingleOrDefault()?.Description
};
return result;
}
/// <summary>
/// Gets the serialization information about the type members.
/// This information is used for creation of the corresponding schema nodes.
/// </summary>
/// <param name="type">The type, members of which should be serialized.</param>
/// <returns>
/// Serialization information about the fields/properties.
/// </returns>
/// <exception cref="System.ArgumentNullException">The type argument is null.</exception>
internal MemberSerializationInfo[] ResolveMembers(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (type.IsKeyValuePair())
{
var keyValueProperties = type.GetAllProperties();
return keyValueProperties.Select(p => new MemberSerializationInfo
{
Name = p.Name,
MemberInfo = p,
Nullable = false
}).ToArray();
}
var allMembers = type.GetFieldsAndProperties(
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
var membersToSerialize = type.GetFieldsAndProperties(
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
var attributes = allMembers
.ToDictionary(x => x, x => x.GetCustomAttributes(false));
// add members that are explicitly marked with DataMember attribute
foreach (var memberInfo in allMembers)
{
if (membersToSerialize.Contains(memberInfo))
{
continue;
}
if (attributes[memberInfo].OfType<DataMemberAttribute>().Any())
{
membersToSerialize.Add(memberInfo);
}
}
var members = membersToSerialize
.Where(x => !attributes[x].OfType<IgnoreDataMemberAttribute>().Any())
.Select(m =>
{
var customAttributes = attributes[m];
return new
{
Member = m,
Attribute = customAttributes.OfType<DataMemberAttribute>().SingleOrDefault(),
Nullable = customAttributes.OfType<NullableSchemaAttribute>().Any(), // m.GetType().CanContainNull() ||
DefaultValue = customAttributes.OfType<DefaultValueAttribute>().FirstOrDefault()?.Value,
HasDefaultValue = customAttributes.OfType<DefaultValueAttribute>().Any(),
Doc = customAttributes.OfType<DescriptionAttribute>().FirstOrDefault()?.Description
};
});
if (_includeOnlyDataContractMembers)
{
members = members.Where(m => m.Attribute != null);
}
var result = members.Select(m => new MemberSerializationInfo
{
Name = m.Attribute?.Name ?? m.Member.Name,
MemberInfo = m.Member,
Nullable = m.Nullable,
Aliases = m.Attribute?.Name != null ? new List<string> { m.Member.Name } : new List<string>(),
HasDefaultValue = m.HasDefaultValue,
DefaultValue = m.DefaultValue,
Doc = m.Doc
});
if (this._useAlphabeticalOrder)
{
result = result.OrderBy(p => p.Name);
}
return result.ToArray();
}
}
}