-
Notifications
You must be signed in to change notification settings - Fork 865
/
Copy pathExample.cs
382 lines (325 loc) · 12.2 KB
/
Example.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
using Json.LitJson;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace ServiceClientGenerator
{
/// <summary>
/// Represents a code sample for an operation.
/// </summary>
public class Example : BaseModel
{
public const string
IdKey = "id",
TitleKey = "title",
DescriptionKey = "description",
InputKey = "input",
OutputKey = "output",
CommentsKey = "comments";
public Example(ServiceModel model, string operationName, JsonData data) : base(model, data)
{
this.OperationName = operationName;
}
/// <summary>
/// The name of the operation this sample is for
/// </summary>
public string OperationName { get; set; }
/// <summary>
/// The operation metadata associated with this example.
/// </summary>
public Operation Operation
{
get { return this.model.FindOperation(OperationName); }
}
/// <summary>
/// The example id taken from the model.
/// </summary>
/// <remarks>
/// This unique id is used for the region in the emitted code sample
/// that will be parsed to include the code in the documentation.
/// </remarks>
public string Id
{
get
{
return data.SafeGetString(IdKey);
}
}
/// <summary>
/// The title for the example.
/// </summary>
public string Title
{
get
{
return data.SafeGetString(TitleKey);
}
}
/// <summary>
/// Descriptive text for the example.
/// </summary>
public string Description
{
get
{
return data.SafeGetString(DescriptionKey);
}
}
/// <summary>
/// The sample data for the input parameters.
/// </summary>
public IDictionary<string, JsonData> InputParameters
{
get
{
var inputMap = data.SafeGet(InputKey);
if (null == inputMap)
return new Dictionary<string, JsonData>();
return inputMap.GetMap();
}
}
/// <summary>
/// The sample data for the output parameters.
/// </summary>
public IDictionary<string, JsonData> OutputParameters
{
get
{
var outputMap = data.SafeGet(OutputKey);
if (null == outputMap)
return new Dictionary<string, JsonData>();
return outputMap.GetMap();
}
}
/// <summary>
/// Comments for the sample input data.
/// </summary>
/// <remarks>
/// A map of property name to comment text.
/// </remarks>
public IDictionary<string, string> InputComments
{
get
{
return GetComments(InputKey);
}
}
/// <summary>
/// Comments for the sample response data.
/// </summary>
/// <remarks>
/// A map of property name to comment text.
/// </remarks>
public IDictionary<string, string> OutputComments
{
get
{
return GetComments(OutputKey);
}
}
// Common to the InputComments and OutputComments properties
private IDictionary<string, string> GetComments(string key)
{
var comments = this.data[CommentsKey];
if (null != comments)
{
var map = comments.SafeGet(key);
if (null != map)
return map.GetStringMap();
}
return new Dictionary<string, string>();
}
/// <summary>
/// For the request, build the literals and/or instantiators to assign to each
/// property in the request shape for which sample data was supplied in the example.
/// </summary>
/// <returns>A list of strings of the form 'PropertyName = value' with comments at the
/// end, if present.</returns>
public IList<string> GetRequestAssignments(int currentIndent)
{
var result = new List<string>();
if (!InputParameters.Any())
return result;
var last = InputParameters.Last().Key;
foreach (var param in InputParameters)
{
var member = Operation.RequestStructure.Members.GetMemberByName(param.Key);
if (null == member)
continue;
var sb = new StringBuilder();
var cb = new CodeBuilder(sb, currentIndent);
cb.Append(member.PropertyName).Append(" = ");
GetSampleLiteral(member, param.Value, cb);
if (param.Key != last)
cb.Append(",");
if (InputComments.ContainsKey(param.Key))
cb.Append(" // ").Append(InputComments[param.Key]);
result.Add(sb.ToString());
}
return result;
}
public IList<string> GetResponseAssignments()
{
var result = new List<string>();
foreach (var param in OutputParameters)
{
var member = Operation.ResponseStructure.Members.GetMemberByName(param.Key);
if (null == member)
continue;
var shapeType = ShapeType(member.Shape);
result.Add(string.Format("{0} {1} = response.{2};{3}",
shapeType,
member.ArgumentName,
member.PropertyName,
OutputComments.ContainsKey(param.Key) ? " // " + OutputComments[param.Key] : ""));
}
return result;
}
/// <summary>
/// Given a member and sample data, build a literal/instantation for the
/// member's type with the sample data.
/// </summary>
/// <param name="member">The member in the model</param>
/// <param name="data">Sample data to populate the literal with</param>
/// <param name="cb">A CodeBuilder instance to write the code to.</param>
public void GetSampleLiteral(Member member, JsonData data, CodeBuilder cb)
{
GetSampleLiteral(member.Shape, data, cb);
}
/// <summary>
/// Given a Shape and sample data, build a literal/instantiation for the
/// Shape's type with the sample data.
/// </summary>
/// <param name="shape">The Shape in the model</param>
/// <param name="data">Sample data to populate the literal with</param>
/// <param name="cb">A CodeBuilder instance to write the code to.</param>
public void GetSampleLiteral(Shape shape, JsonData data, CodeBuilder cb)
{
if (shape.IsString && data.IsString)
cb.AppendQuote(data.ToString());
else if (shape.IsBoolean)
cb.Append(data.ToString().ToLowerInvariant());
else if (shape.IsFloat || shape.IsInt || shape.IsDouble || shape.IsLong)
{
if (data.IsDouble)
cb.Append(((double)data).ToString(CultureInfo.InvariantCulture));
else
cb.Append(data.ToString());
}
else if (shape.IsList && data.IsArray)
{
var itemType = shape.ListShape;
cb.AppendFormat("new List<{0}> ", ShapeType(itemType)).OpenBlock();
for (int i = 0; i < data.Count; i++)
{
GetSampleLiteral(itemType, data[i], cb);
if (i < (data.Count - 1))
cb.AppendLine(",");
}
cb.CloseBlock();
}
else if (shape.IsMap && data.IsObject)
{
var keyType = shape.KeyShape;
var valType = shape.ValueShape;
cb.AppendFormat("new Dictionary<{0}, {1}> ", ShapeType(keyType), ShapeType(valType));
cb.OpenBlock();
foreach (var k in data.PropertyNames)
{
cb.Append("{ ");
GetSampleLiteral(keyType, k, cb);
cb.Append(", ");
GetSampleLiteral(valType, data[k], cb);
cb.Append(" }");
if (k != data.PropertyNames.Last())
cb.AppendLine(",");
}
cb.CloseBlock();
}
else if (shape.IsStructure && data.IsObject)
{
cb.AppendFormat("new {0} ", ShapeType(shape));
if (data.PropertyNames.Count() > 1)
cb.OpenBlock();
else
cb.Append("{ ");
foreach (var field in data.PropertyNames)
{
var property = shape.Members.GetMemberByName(field);
if (null == property)
continue;
cb.AppendFormat("{0} = ", property.PropertyName);
GetSampleLiteral(property, data[field], cb);
if (field != data.PropertyNames.Last())
cb.AppendLine(",");
}
if (data.PropertyNames.Count() > 1)
cb.CloseBlock();
else
cb.Append(" }");
}
else if (shape.IsMemoryStream && data.IsString)
{
cb.AppendFormat("new {0}({1})", ShapeType(shape), data.ToString());
}
else if (shape.IsTimeStamp)
{
string exampleValue = null;
if (data.IsString)
{
var textValue = data.ToString();
// Even though the date in the service example is in UTC format (i.e. ending with 'Z'), we need to tell TryParse about it.
// If not, the parsed result will have DateTimeKind = Local, and the output can change depending on where the generator runs.
if (DateTime.TryParse(textValue, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime parsedDateTime))
{
exampleValue = string.Format("new DateTime({0}, DateTimeKind.Utc)",
parsedDateTime.ToString("yyyy, M, d, h, m, s"));
}
}
if (string.IsNullOrEmpty(exampleValue))
{
exampleValue = "DateTime.UtcNow";
}
cb.Append(exampleValue);
}
else
{
// default value
cb.Append("<data>");
}
}
/// <summary>
/// Return the type name for a shape
/// </summary>
/// <param name="shape">The shape to get the type name for</param>
/// <returns></returns>
private string ShapeType(Shape shape)
{
if (shape.IsBoolean)
return "bool";
if (shape.IsInt)
return "int";
if (shape.IsLong)
return "long";
if (shape.IsFloat)
return "float";
if (shape.IsDouble)
return "double";
if (shape.IsTimeStamp)
return "DateTime";
if (shape.IsMemoryStream)
return "MemoryStream";
if (shape.IsMap)
return string.Format("Dictionary<{0}, {1}>", ShapeType(shape.KeyShape), ShapeType(shape.ValueShape));
if (shape.IsList)
return string.Format("List<{0}>", ShapeType(shape.ListShape));
if (shape.IsStructure)
return shape.Name;
if (shape.IsPrimitiveType)
return shape.Type;
throw new InvalidOperationException(string.Format("Unable to resolve type for shape {0}", shape.Name));
}
}
}