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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
|
//-----------------------------------------------------------------------
// <copyright file="MessagePart.cs" company="Andrew Arnott">
// Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace DotNetOAuth.Messaging.Reflection {
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net.Security;
using System.Reflection;
using System.Xml;
/// <summary>
/// Describes an individual member of a message and assists in its serialization.
/// </summary>
internal class MessagePart {
/// <summary>
/// A map of converters that help serialize custom objects to string values and back again.
/// </summary>
private static readonly Dictionary<Type, ValueMapping> converters = new Dictionary<Type, ValueMapping>();
/// <summary>
/// The string-object conversion routines to use for this individual message part.
/// </summary>
private ValueMapping converter;
/// <summary>
/// The property that this message part is associated with, if aplicable.
/// </summary>
private PropertyInfo property;
/// <summary>
/// The field that this message part is associated with, if aplicable.
/// </summary>
private FieldInfo field;
/// <summary>
/// The type of the message part. (Not the type of the message itself).
/// </summary>
private Type memberDeclaredType;
/// <summary>
/// The default (uninitialized) value of the member inherent in its type.
/// </summary>
private object defaultMemberValue;
/// <summary>
/// Initializes static members of the <see cref="MessagePart"/> class.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Much more efficient initialization when we can call methods.")]
static MessagePart() {
Map<Uri>(uri => uri.AbsoluteUri, str => new Uri(str));
Map<DateTime>(dt => XmlConvert.ToString(dt, XmlDateTimeSerializationMode.Utc), str => XmlConvert.ToDateTime(str, XmlDateTimeSerializationMode.Utc));
}
/// <summary>
/// Initializes a new instance of the <see cref="MessagePart"/> class.
/// </summary>
/// <param name="member">
/// A property or field of an <see cref="IProtocolMessage"/> implementing type
/// that has a <see cref="MessagePartAttribute"/> attached to it.
/// </param>
/// <param name="attribute">
/// The attribute discovered on <paramref name="member"/> that describes the
/// serialization requirements of the message part.
/// </param>
internal MessagePart(MemberInfo member, MessagePartAttribute attribute) {
if (member == null) {
throw new ArgumentNullException("member");
}
this.field = member as FieldInfo;
this.property = member as PropertyInfo;
if (this.field == null && this.property == null) {
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
MessagingStrings.UnexpectedType,
typeof(FieldInfo).Name + ", " + typeof(PropertyInfo).Name,
member.GetType().Name),
"member");
}
if (attribute == null) {
throw new ArgumentNullException("attribute");
}
this.Name = attribute.Name ?? member.Name;
this.RequiredProtection = attribute.RequiredProtection;
this.IsRequired = attribute.IsRequired;
this.memberDeclaredType = (this.field != null) ? this.field.FieldType : this.property.PropertyType;
this.defaultMemberValue = DeriveDefaultValue(this.memberDeclaredType);
if (!converters.TryGetValue(this.memberDeclaredType, out this.converter)) {
this.converter = new ValueMapping(
obj => obj != null ? obj.ToString() : null,
str => str != null ? Convert.ChangeType(str, this.memberDeclaredType, CultureInfo.InvariantCulture) : null);
}
// Validate a sane combination of settings
this.ValidateSettings();
}
/// <summary>
/// Gets or sets the name to use when serializing or deserializing this parameter in a message.
/// </summary>
internal string Name { get; set; }
/// <summary>
/// Gets or sets whether this message part must be signed.
/// </summary>
internal ProtectionLevel RequiredProtection { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this message part is required for the
/// containing message to be valid.
/// </summary>
internal bool IsRequired { get; set; }
/// <summary>
/// Sets the member of a given message to some given value.
/// Used in deserialization.
/// </summary>
/// <param name="message">The message instance containing the member whose value should be set.</param>
/// <param name="value">The string representation of the value to set.</param>
internal void SetValue(IProtocolMessage message, string value) {
if (this.property != null) {
this.property.SetValue(message, this.ToValue(value), null);
} else {
this.field.SetValue(message, this.ToValue(value));
}
}
/// <summary>
/// Gets the value of a member of a given message.
/// Used in serialization.
/// </summary>
/// <param name="message">The message instance to read the value from.</param>
/// <returns>The string representation of the member's value.</returns>
internal string GetValue(IProtocolMessage message) {
return this.ToString(this.GetValueAsObject(message));
}
/// <summary>
/// Gets whether the value has been set to something other than its CLR type default value.
/// </summary>
/// <param name="message">The message instance to check the value on.</param>
/// <returns>True if the value is not the CLR default value.</returns>
internal bool IsNondefaultValueSet(IProtocolMessage message) {
if (this.memberDeclaredType.IsValueType) {
return !this.GetValueAsObject(message).Equals(this.defaultMemberValue);
} else {
return this.defaultMemberValue != this.GetValueAsObject(message);
}
}
/// <summary>
/// Figures out the CLR default value for a given type.
/// </summary>
/// <param name="type">The type whose default value is being sought.</param>
/// <returns>Either null, or some default value like 0 or 0.0.</returns>
private static object DeriveDefaultValue(Type type) {
if (type.IsValueType) {
return Activator.CreateInstance(type);
} else {
return null;
}
}
/// <summary>
/// Adds a pair of type conversion functions to the static converstion map.
/// </summary>
/// <typeparam name="T">The custom type to convert to and from strings.</typeparam>
/// <param name="toString">The function to convert the custom type to a string.</param>
/// <param name="toValue">The function to convert a string to the custom type.</param>
private static void Map<T>(Func<T, string> toString, Func<string, T> toValue) {
Func<object, string> safeToString = obj => obj != null ? toString((T)obj) : null;
Func<string, object> safeToT = str => str != null ? toValue(str) : default(T);
converters.Add(typeof(T), new ValueMapping(safeToString, safeToT));
}
/// <summary>
/// Checks whether a type is a nullable value type (i.e. int?)
/// </summary>
/// <param name="type">The type in question.</param>
/// <returns>True if this is a nullable value type.</returns>
private static bool IsNonNullableValueType(Type type) {
if (!type.IsValueType) {
return false;
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
return false;
}
return true;
}
/// <summary>
/// Converts a string representation of the member's value to the appropriate type.
/// </summary>
/// <param name="value">The string representation of the member's value.</param>
/// <returns>An instance of the appropriate type for setting the member.</returns>
private object ToValue(string value) {
return this.converter.StringToValue(value);
}
/// <summary>
/// Converts the member's value to its string representation.
/// </summary>
/// <param name="value">The value of the member.</param>
/// <returns>The string representation of the member's value.</returns>
private string ToString(object value) {
return this.converter.ValueToString(value);
}
/// <summary>
/// Gets the value of the message part, without converting it to/from a string.
/// </summary>
/// <param name="message">The message instance to read from.</param>
/// <returns>The value of the member.</returns>
private object GetValueAsObject(IProtocolMessage message) {
if (this.property != null) {
return this.property.GetValue(message, null);
} else {
return this.field.GetValue(message);
}
}
/// <summary>
/// Validates that the message part and its attribute have agreeable settings.
/// </summary>
/// <exception cref="ArgumentException">
/// Thrown when a non-nullable value type is set as optional.
/// </exception>
private void ValidateSettings() {
if (!this.IsRequired && IsNonNullableValueType(this.memberDeclaredType)) {
MemberInfo member = (MemberInfo)this.field ?? this.property;
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
"Invalid combination: {0} on message type {1} is a non-nullable value type but is marked as optional.",
member.Name,
member.DeclaringType));
}
}
}
}
|