-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathSimulateDataverseFunction.cs
More file actions
395 lines (327 loc) · 14.4 KB
/
SimulateDataverseFunction.cs
File metadata and controls
395 lines (327 loc) · 14.4 KB
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
382
383
384
385
386
387
388
389
390
391
392
393
394
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
using System.Dynamic;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Playwright;
using Microsoft.PowerApps.TestEngine.Config;
using Microsoft.PowerApps.TestEngine.TestInfra;
using Microsoft.PowerFx;
using Microsoft.PowerFx.Core.Utils;
using Microsoft.PowerFx.Types;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using static System.Net.Mime.MediaTypeNames;
using static System.Net.WebRequestMethods;
namespace testengine.module
{
/// <summary>
/// This will execute Simulate request to Dataverse
/// </summary>
public class SimulateDataverseFunction : ReflectionFunction
{
private readonly ITestInfraFunctions _testInfraFunctions;
private readonly ITestState _testState;
private readonly ILogger _logger;
private static readonly RecordType dataverseRequest = RecordType.Empty();
public SimulateDataverseFunction(ITestInfraFunctions testInfraFunctions, ITestState testState, ILogger logger)
: base(DPath.Root.Append(new DName("Preview")), "SimulateDataverse", FormulaType.Blank, dataverseRequest)
{
_testInfraFunctions = testInfraFunctions;
_testState = testState;
_logger = logger;
}
public BlankValue Execute(RecordValue intercept)
{
ExecuteAsync(intercept).Wait();
return FormulaValue.NewBlank();
}
private async Task ExecuteAsync(RecordValue intercept)
{
_logger.LogInformation("------------------------------\n\n" +
"Executing SimulateDataverse function.");
List<NamedValue> fields = new List<NamedValue>();
await foreach (var field in intercept.GetFieldsAsync(CancellationToken.None))
{
fields.Add(field);
}
StringValue actionName = FormulaValue.New("");
var actionField = fields.FirstOrDefault(f => f.Name.ToLower() == "action");
if (actionField != null)
{
actionName = intercept.GetField(actionField.Name) as StringValue;
}
if (String.IsNullOrEmpty(actionName.Value))
{
throw new InvalidDataException("Missing field action");
}
switch (actionName.Value.ToLower())
{
case "query":
break;
default:
throw new InvalidDataException($"Unsupported action {actionName.Value}");
}
StringValue entityName = FormulaValue.New("");
var entityField = fields.FirstOrDefault(f => f.Name.ToLower() == "entity");
if (entityField != null)
{
entityName = intercept.GetField(entityField.Name) as StringValue;
}
if (String.IsNullOrEmpty(entityName.Value))
{
throw new InvalidDataException("Missing field Entity");
}
TableValue thenResult = null;
var thenField = fields.FirstOrDefault(f => f.Name.ToLower() == "then");
if (thenField != null)
{
thenResult = intercept.GetField(thenField.Name) as TableValue;
}
// TODO handle case Then field is a record rather than a Table
if (thenResult == null)
{
throw new InvalidDataException("Missing field then");
}
await _testInfraFunctions.Page.RouteAsync($"**/api/data/v*/$batch", async (IRoute route) =>
{
var request = route.Request;
if (request.Method == "POST")
{
await HandleBatchRequest(route, entityName.Value, thenResult);
}
else
{
await route.ContinueAsync();
}
});
// TODO: Handle When field
// 1. Convert When field to fetchXML or $filter clause
// TODO:
// 1. Handle request for entity vs list
// 2. Make the route async conditional on query string for different When clause
await _testInfraFunctions.Page.RouteAsync($"**/api/data/v*/{entityName.Value.ToLower()}*", async (IRoute route) =>
{
var request = route.Request;
// TODO: Handle POST and PATCH commands
// 1. POST to add new Record. Add POST record to collection so caller can Assert
// 2. PATCH to update Record. Add Patched record to collection so caller can Assert
if (request.Method == "GET")
{
_logger.LogDebug($"Simulated Dataverse GET request {route.Request.Url}");
// TODO:
// 1. Check for Query conditions and if this request if a match
// 2. Handle multiple GET requests based on query string - fetchXML (From MDA)
// 3. Handle multiple GET requests based on query string - $filter clause (From connector)
// Generate a new response with HTTP body for OData call
await route.FulfillAsync(new RouteFulfillOptions
{
Status = 200,
ContentType = "application/json",
Body = await ConvertTableToOData(thenResult)
});
// TODO: Handle count of simulation to conditionally UnRoute the request
}
else
{
await route.ContinueAsync();
}
});
}
private async Task<string> ConvertTableToOData(TableValue value)
{
// Convert the TableValue to JSON
var data = await ConvertToObject(value);
var responseData = new Dictionary<string, object?>();
responseData["@odata.count"] = data.Count();
responseData["@Microsoft.Dynamics.CRM.totalrecordcount"] = data.Count();
responseData["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] = false;
responseData["value"] = data;
var jObject = JObject.FromObject(responseData);
string jsonString = jObject.ToString(Newtonsoft.Json.Formatting.None);
return jsonString;
}
private async Task HandleBatchRequest(IRoute route, string entity, TableValue value)
{
var request = route.Request.PostData;
var id = GetRequestId(request);
var uri = GetRequestUri(request);
var parts = GetQueryParameters(uri);
if (parts.ContainsKey("apply"))
{
/* Example request
--batch_a3faec5d-befd-4ca0-973e-8dcbfc0981ca
Content-Type: application/http
Content-Transfer-Encoding: binary
GET accounts?%24apply=aggregate%28%24count+as+result%29 HTTP/1.1
Accept: application/json
--batch_a3faec5d-befd-4ca0-973e-8dcbfc0981ca--
*/
await HandleBatchCount(route, id, entity, value);
}
else
{
/* Example Request
--batch_31b8538b-fdf5-4d97-b78f-83517f4ef163
Content-Type: application/http
Content-Transfer-Encoding: binary
GET accounts?%24select=accountid%2Caccountnumber%2Centityimage%2Cemailaddress1%2Centityimage_timestamp&%24count=true HTTP/1.1
Accept: application/json
Prefer: odata.maxpagesize=100,odata.include-annotations=*
--batch_31b8538b-fdf5-4d97-b78f-83517f4ef163--
*/
await HandleBatchResults(route, id, entity, value);
}
}
private async Task HandleBatchResults(IRoute route, string id, string entity, TableValue value)
{
/*
--batchresponse_31b8538b-fdf5-4d97-b78f-83517f4ef163
Content-Type: application/http
Content-Transfer-Encoding: binary
HTTP/1.1 200 OK
Content-Type: application/json; odata.metadata=minimal
OData-Version: 4.0
Preference-Applied: odata.include-annotations="*",odata.maxpagesize=100
{"@odata.context":"https://contoso.crm.dynamics.com/api/data/v9.0/$metadata#accounts(accountid,emailaddress1,entityimage,name,entityimage_timestamp)","@odata.count":2,"@Microsoft.Dynamics.CRM.totalrecordcount":2,"@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded":false,"@Microsoft.Dynamics.CRM.globalmetadataversion":"3073697","value":[{"@odata.etag":"W/\"3073589\"","accountid":"751d2108-5896-ef11-8a6a-6045bd02adee","emailaddress1":null,"entityimage":null,"name":"New Org","entityimage_timestamp":null},{"@odata.etag":"W/\"2446917\"","accountid":"8a2a5404-9753-ef11-a316-6045bd05082d","emailaddress1":null,"entityimage":null,"name":"Microsoft","entityimage_timestamp":null}]}
--batchresponse_31b8538b-fdf5-4d97-b78f-83517f4ef163--
*/
var multilineText = @"--batchresponse_{id}
Content-Type: application/http
Content-Transfer-Encoding: binary
HTTP/1.1 200 OK
Content-Type: application/json; odata.metadata=minimal
OData-Version: 4.0
Preference-Applied: odata.include-annotations=""*"",odata.maxpagesize=100
{json}
--batchresponse_{id}--";
StringBuilder sb = new StringBuilder(multilineText);
sb.Replace("{id}", id);
sb.Replace("{entity}", entity.ToLower());
sb.Replace("{json}", await ConvertTableToOData(value));
await route.FulfillAsync(new RouteFulfillOptions
{
Status = 200,
ContentType = $"multipart /mixed; boundary=batchresponse_{id}",
Body = sb.ToString()
});
}
private async Task HandleBatchCount(IRoute route, string id, string entity, TableValue value)
{
/*
--batchresponse_a3faec5d-befd-4ca0-973e-8dcbfc0981ca
Content-Type: application/http
Content-Transfer-Encoding: binary
HTTP/1.1 200 OK
Content-Type: application/json; odata.metadata=minimal
OData-Version: 4.0
{"@odata.context":"https://contoso.crm.dynamics.com/api/data/v9.0/$metadata#accounts","value":[{"result":2}]}
--batchresponse_a3faec5d-befd-4ca0-973e-8dcbfc0981ca--
*/
var multilineText = @"--batchresponse_{id}
Content-Type: application/http
Content-Transfer-Encoding: binary
HTTP/1.1 200 OK
Content-Type: application/json; odata.metadata=minimal
OData-Version: 4.0
{""@odata.context"":""https://{host}/api/data/v9.0/$metadata#{entity}"",""value"":[{""result"":{count}}]}
--batchresponse_{id}--";
StringBuilder sb = new StringBuilder(multilineText);
sb.Replace("{id}", id);
sb.Replace("{entity}", entity.ToLower());
sb.Replace("{count}", value.Rows.Count().ToString());
await route.FulfillAsync(new RouteFulfillOptions
{
Status = 200,
ContentType = "application/json",
Body = sb.ToString()
});
}
private string GetRequestId(string request)
{
using (var reader = new StringReader(request))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith("--batch_"))
{
var id = line.Replace("--batch_", "");
return id;
}
}
}
return String.Empty;
}
public Dictionary<string, string> GetQueryParameters(Uri uri)
{
// Convert the relative URI to an absolute URI so can get Query
Uri absoluteUri = new Uri(new Uri("https://example"), uri);
var queryParameters = new Dictionary<string, string>();
string query = absoluteUri.Query.TrimStart('?');
string[] pairs = query.Split('&');
foreach (string pair in pairs)
{
string[] keyValue = pair.Split('=');
if (keyValue.Length == 2)
{
string key = Uri.UnescapeDataString(keyValue[0]);
string value = Uri.UnescapeDataString(keyValue[1]);
queryParameters[key] = value;
}
}
return queryParameters;
}
private Uri? GetRequestUri(string request)
{
using (var reader = new StringReader(request))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith("GET "))
{
var text = line.Replace("GET ", "");
text = text.Replace(" HTTP/1.1", "");
return new Uri(text, UriKind.Relative);
}
}
}
return null;
}
private async Task<List<object>> ConvertToObject(TableValue value)
{
var data = new List<object>();
foreach (var item in value.Rows)
{
var row = new Dictionary<string, object?>(new ExpandoObject());
await foreach (var field in item.Value.GetFieldsAsync(CancellationToken.None))
{
if (field.Value.TryGetPrimitiveValue(out object val))
{
row.Add(field.Name, val);
continue;
}
// TODO: Handle complex non primative types
}
row.Add("@odata.etag", GenerateETag(row));
data.Add(row);
}
return data;
}
private string GenerateETag(object jsonObject)
{
// Serialize the JSON object to a string
string jsonString = JsonConvert.SerializeObject(jsonObject);
// Compute the hash of the JSON string
using (var sha256 = SHA256.Create())
{
byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(jsonString));
return Convert.ToBase64String(hash);
}
}
}
}