forked from splunk/splunk-sdk-csharp-pcl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArgs.cs
356 lines (299 loc) · 13.6 KB
/
Args.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
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/*
* Copyright 2014 Splunk, Inc.
*
* 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using Splunk.Client.Arguments;
//// TODO: Ensure this code is solid
//// [ ] Support more than one level of inheritance => move away from generic implementation.
//// [O] Contracts
//// [O] Documentation
namespace Splunk.Client
{
/// <summary>
/// Provides a base class for representing strongly typed arguments to Splunk
/// endpoints.
/// </summary>
/// <typeparam name="TArgs">
/// Type of the arguments.
/// </typeparam>
/// <seealso cref="T:System.Collections.Generic.IEnumerable{Splunk.Client.Argument}"/>
public abstract partial class Args<TArgs> : IEnumerable<Argument> where TArgs : Args<TArgs>
{
static Args()
{
var propertyFormatters = new Dictionary<Type, Formatter>()
{
{ typeof(bool), new Formatter { Format = FormatBoolean } },
{ typeof(bool?), new Formatter { Format = FormatBoolean } },
{ typeof(byte), new Formatter { Format = FormatNumber } },
{ typeof(byte?), new Formatter { Format = FormatNumber } },
{ typeof(sbyte), new Formatter { Format = FormatNumber } },
{ typeof(sbyte?), new Formatter { Format = FormatNumber } },
{ typeof(short), new Formatter { Format = FormatNumber } },
{ typeof(short?), new Formatter { Format = FormatNumber } },
{ typeof(ushort), new Formatter { Format = FormatNumber } },
{ typeof(ushort?), new Formatter { Format = FormatNumber } },
{ typeof(int), new Formatter { Format = FormatNumber } },
{ typeof(int?), new Formatter { Format = FormatNumber } },
{ typeof(uint), new Formatter { Format = FormatNumber } },
{ typeof(uint?), new Formatter { Format = FormatNumber } },
{ typeof(long), new Formatter { Format = FormatNumber } },
{ typeof(long?), new Formatter { Format = FormatNumber } },
{ typeof(ulong), new Formatter { Format = FormatNumber } },
{ typeof(ulong?), new Formatter { Format = FormatNumber } },
{ typeof(float), new Formatter { Format = FormatNumber } },
{ typeof(float?), new Formatter { Format = FormatNumber } },
{ typeof(double), new Formatter { Format = FormatNumber } },
{ typeof(double?), new Formatter { Format = FormatNumber } },
{ typeof(decimal), new Formatter { Format = FormatNumber } },
{ typeof(decimal?), new Formatter { Format = FormatNumber } },
{ typeof(string), new Formatter { Format = FormatString } }
};
var defaultFormatter = new Formatter { Format = FormatString };
var parameters = new SortedSet<Parameter>();
foreach (var propertyInfo in typeof(TArgs).GetRuntimeProperties())
{
var dataMember = propertyInfo.GetCustomAttribute<DataMemberAttribute>();
if (dataMember is null)
{
var text = string.Format(CultureInfo.CurrentCulture, "Missing DataMemberAttribute on {0}.{1}", propertyInfo.PropertyType.Name, propertyInfo.Name);
throw new InvalidDataContractException(text);
}
var propertyName = propertyInfo.Name;
var propertyType = propertyInfo.PropertyType;
var propertyTypeInfo = propertyType.GetTypeInfo();
var formatter = GetPropertyFormatter(propertyName, null, propertyType, propertyTypeInfo, propertyFormatters);
if (formatter is null)
{
var interfaces = propertyType.GetTypeInfo().ImplementedInterfaces;
var isCollection = false;
formatter = defaultFormatter;
foreach (var @interface in interfaces)
{
if (@interface.IsConstructedGenericType)
{
if (@interface.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
//// IEnumerable<T> implements IEnumerable => we are good to go
var itemType = @interface.GenericTypeArguments[0];
formatter = GetPropertyFormatter(propertyName, propertyType, itemType, itemType.GetTypeInfo(), propertyFormatters);
isCollection = true;
break;
}
}
else if (@interface == typeof(IEnumerable))
{
//// Keep looking because we'd prefer to use a more specific formatter
isCollection = true;
}
}
formatter = new Formatter { Format = formatter.Value.Format, IsCollection = isCollection };
}
var defaultValue = propertyInfo.GetCustomAttribute<DefaultValueAttribute>();
_ = parameters.Add(new Parameter(dataMember.Name, dataMember.Order, propertyInfo)
{
// Properties
DefaultValue = defaultValue?.Value,
EmitDefaultValue = dataMember.EmitDefaultValue,
IsCollection = formatter.Value.IsCollection,
IsRequired = dataMember.IsRequired,
// Methods
Format = (formatter ?? defaultFormatter).Format
});
}
Parameters = parameters;
}
/// <summary>
/// Initializes a new instance of the <see cref="Args<TArgs>"/> class.
/// </summary>
protected Args()
{
foreach (var serializationEntry in Parameters.Where(entry => entry.DefaultValue != null))
{
serializationEntry.SetValue(this, serializationEntry.DefaultValue);
}
}
/// <summary>
/// Gets an enumerator that produces an <see cref="Argument"/> sequence
/// based on the serialization attributes of the properties of the
/// current <see cref="Args<TArgs>"/> instance.
/// </summary>
/// <exception cref="SerializationException">
/// Thrown when a Serialization error condition occurs.
/// </exception>
/// <returns>
/// An object for enumerating the <see cref="Argument"/> sequence.
/// </returns>
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<Argument>)this).GetEnumerator();
/// <summary>
/// Gets an enumerator that produces an <see cref="Argument"/> sequence
/// based on the serialization attributes of the properties of the
/// current <see cref="Args<TArgs>"/> instance.
/// </summary>
/// <exception cref="SerializationException">
/// Thrown when a Serialization error condition occurs.
/// </exception>
/// <returns>
/// An object for enumerating the <see cref="Argument"/> sequence.
/// </returns>
IEnumerator<Argument> IEnumerable<Argument>.GetEnumerator()
{
foreach (var parameter in Args<TArgs>.Parameters)
{
var value = parameter.GetValue(this);
if (value is null)
{
if (parameter.IsRequired)
{
throw new SerializationException(string.Format("Missing value for required parameter {0}", parameter.Name));
}
continue;
}
if (!parameter.EmitDefaultValue && value.Equals(parameter.DefaultValue))
{
continue;
}
if (!parameter.IsCollection)
{
yield return new Argument(parameter.Name, parameter.Format(value));
continue;
}
foreach (var item in (IEnumerable)value)
{
yield return new Argument(parameter.Name, parameter.Format(item));
}
}
}
/// <summary>
/// Gets a string representation for the current
/// <see cref="Args<TArgs>"/>.
/// </summary>
/// <returns>
/// A string representation of the current <see cref="Args<TArgs>"/>.
/// </returns>
/// <seealso cref="M:System.Object.ToString()"/>
public override string ToString()
{
var builder = new StringBuilder();
void append(object item, string name, Func<object, string> format)
{
_ = builder.Append(name);
_ = builder.Append('=');
_ = builder.Append(format(item));
_ = builder.Append("; ");
}
foreach (var parameter in Args<TArgs>.Parameters)
{
var value = parameter.GetValue(this);
if (value is null)
{
append("null", parameter.Name, FormatString);
continue;
}
if (!parameter.IsCollection)
{
append(value, parameter.Name, parameter.Format);
continue;
}
foreach (var item in (IEnumerable)value)
{
append(item, parameter.Name, parameter.Format);
}
}
if (builder.Length > 0)
{
builder.Length -= 2;
}
return builder.ToString();
}
private static readonly SortedSet<Parameter> Parameters;
private static string FormatBoolean(object? value) => ((bool?)value ?? false) ? "1" : "0";
private static string? FormatNumber(object? value) => value?.ToString();
private static string? FormatString(object? value) => value?.ToString();
private static Formatter? GetPropertyFormatter(string propertyName, Type? container, Type type, TypeInfo info, Dictionary<Type, Formatter> formatters)
{
if (formatters.TryGetValue(container ?? type, out var formatter))
{
return formatter;
}
if (container != null && formatters.TryGetValue(type, out formatter))
{
formatter.IsCollection = true;
}
else
{
var enumType = GetEnum(type, info);
if (enumType != null)
{
//// TODO: Add two items to formatters for each enum:
//// formatters.Add(enumType, formatter)
//// formatters.Add(info.IsEnum ? typeof(Nullable<>).MakeGenericType(type), formatter)
var map = new Dictionary<int, string>();
foreach (var value in Enum.GetValues(enumType))
{
var name = Enum.GetName(enumType, value);
var field = name is null ? null : enumType.GetRuntimeField(name);
var enumMember = field?.GetCustomAttribute<EnumMemberAttribute>();
map[(int)value] = enumMember is null ? name : enumMember.Value;
}
string format(object value)
{
if (map.TryGetValue((int)value, out var name))
{
return name;
}
var text = string.Format(CultureInfo.CurrentCulture, "{0}.{1}: {2}",
typeof(TArgs).Name, propertyName, value);
throw new ArgumentException(text);
}
formatter = new Formatter
{
Format = format,
IsCollection = container != null
};
}
else if (container != null)
{
formatter = new Formatter { Format = FormatString, IsCollection = true };
}
else
{
return null;
}
}
formatters.Add(container ?? type, formatter);
return formatter;
}
private static Type? GetEnum(Type type, TypeInfo info)
{
if (info.IsEnum)
{
return type;
}
var t = type is null ? null : Nullable.GetUnderlyingType(type);
if (t is null)
{
return null;
}
info = t.GetTypeInfo();
return info.IsEnum ? type : null;
}
}
}