-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathProgram.cs
More file actions
390 lines (359 loc) · 17.1 KB
/
Program.cs
File metadata and controls
390 lines (359 loc) · 17.1 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
// ======================================================================================
// This file is part of the Microsoft Dynamics CRM SDK code samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft Development Tools and/or
// on-line documentation. See these other materials for detailed information regarding
// Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ======================================================================================
using Microsoft.Crm.Sdk.Samples.HelperCode;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace Microsoft.Crm.Sdk.Samples
{
/// <summary>
/// This program performs basic create, retrieve, update, and delete (CRUD) and related
/// operations against a CRM Online 2016 or later organization using the Web API.
/// </summary>
/// <remarks>
/// Before building this application, you must first modify the following configuration
/// information in the app.config file:
/// - All deployments: Provide connection string service URL's for your organization.
/// - CRM Online: Replace the app settings with the correct values for your Azure
/// application registration.
/// See the provided app.config file for more information.
/// </remarks>
internal class BatchOperations
{
private const string PREFER_HEADER = "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"";
//Provides a persistent client-to-CRM server communication channel.
private HttpClient _httpClient;
//Start with base version and update with actual version later.
private Version _webAPIVersion = new Version(8, 2);
//Centralized collection of entity URIs used to manage lifetimes.
private List<string> _entityUris = new List<string>();
//A set of variables to hold the state of and URIs for primary entity instances.
private JObject contact1 = new JObject(), contact2 = new JObject();
private HttpMessageContent CreateHttpMessageContent(HttpMethod httpMethod, string requestUri, int contentId = 0, string content = null)
{
string baseUrl = _httpClient.BaseAddress.AbsoluteUri.Trim() + GetVersionedWebAPIPath();
if (!requestUri.StartsWith(baseUrl))
{
requestUri = baseUrl + requestUri;
}
HttpRequestMessage requestMessage = new HttpRequestMessage(httpMethod, requestUri);
HttpMessageContent messageContent = new HttpMessageContent(requestMessage);
messageContent.Headers.Remove("Content-Type");
messageContent.Headers.Add("Content-Type", "application/http");
messageContent.Headers.Add("Content-Transfer-Encoding", "binary");
// only GET request requires Accept header
if (httpMethod == HttpMethod.Get)
{
requestMessage.Headers.Add("Accept", "application/json");
}
else
{
// request other than GET may have content, which is normally JSON
if (!string.IsNullOrEmpty(content))
{
StringContent stringContent = new StringContent(content);
stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;type=entry");
requestMessage.Content = stringContent;
}
messageContent.Headers.Add("Content-ID", contentId.ToString());
}
return messageContent;
}
private async Task<List<HttpResponseMessage>> SendBatchRequestAsync(List<HttpMessageContent> httpContents)
{
if (httpContents == null)
{
throw new ArgumentNullException(nameof(httpContents));
}
string batchName = $"batch_{Guid.NewGuid()}";
MultipartContent batchContent = new MultipartContent("mixed", batchName);
string changesetName = $"changeset_{Guid.NewGuid()}";
MultipartContent changesetContent = new MultipartContent("mixed", changesetName);
httpContents.ForEach((c) => changesetContent.Add(c));
batchContent.Add(changesetContent);
return await SendBatchRequestAsync(batchContent);
}
private async Task<List<HttpResponseMessage>> SendBatchRequestAsync(MultipartContent batchContent)
{
HttpRequestMessage batchRequest = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(_httpClient.BaseAddress.AbsoluteUri.Trim() + GetVersionedWebAPIPath() + "$batch")
};
batchRequest.Content = batchContent;
batchRequest.Headers.Add("Prefer", PREFER_HEADER);
batchRequest.Headers.Add("OData-MaxVersion", "4.0");
batchRequest.Headers.Add("OData-Version", "4.0");
batchRequest.Headers.Add("Accept", "application/json");
HttpResponseMessage response = await _httpClient.SendAsync(batchRequest);
MultipartMemoryStreamProvider body = await response.Content.ReadAsMultipartAsync();
List<HttpResponseMessage> contents = await ReadHttpContents(body);
return contents;
}
private async Task<List<HttpResponseMessage>> ReadHttpContents(MultipartMemoryStreamProvider body)
{
List<HttpResponseMessage> results = new List<HttpResponseMessage>();
if (body?.Contents != null)
{
foreach (HttpContent c in body.Contents)
{
if (c.IsMimeMultipartContent())
{
results.AddRange(await ReadHttpContents((await c.ReadAsMultipartAsync())));
}
else if (c.IsHttpResponseMessageContent())
{
HttpResponseMessage responseMessage = await c.ReadAsHttpResponseMessageAsync();
if (responseMessage != null)
{
results.Add(responseMessage);
}
}
else
{
HttpResponseMessage responseMessage = DeserializeToResponse(await c.ReadAsStreamAsync());
if (responseMessage != null)
{
results.Add(responseMessage);
}
}
}
}
return results;
}
private HttpResponseMessage DeserializeToResponse(Stream stream)
{
HttpResponseMessage response = new HttpResponseMessage();
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
response.Content = new ByteArrayContent(memoryStream.ToArray());
response.Content.Headers.Add("Content-Type", "application/http;msgtype=response");
return response.Content.ReadAsHttpResponseMessageAsync().Result;
}
private string GetVersionedWebAPIPath()
{
return string.Format("v{0}/", _webAPIVersion.ToString(2));
}
public async Task GetWebAPIVersion()
{
HttpRequestMessage RetrieveVersionRequest = new HttpRequestMessage(HttpMethod.Get, GetVersionedWebAPIPath() + "RetrieveVersion");
HttpResponseMessage RetrieveVersionResponse = await _httpClient.SendAsync(RetrieveVersionRequest);
if (RetrieveVersionResponse.StatusCode == HttpStatusCode.OK) //200
{
JObject retrievedVersion = JsonConvert.DeserializeObject<JObject>(await RetrieveVersionResponse.Content.ReadAsStringAsync());
//Capture the actual version available in this organization
_webAPIVersion = Version.Parse((string)retrievedVersion.GetValue("Version"));
Console.WriteLine("RetrieveVersion: {0}", retrievedVersion.GetValue("Version"));
}
else
{
Console.WriteLine("Failed to retrieve the version for reason: {0}", RetrieveVersionResponse.ReasonPhrase);
throw new CrmHttpResponseException(RetrieveVersionResponse.Content);
}
}
public async Task Sample1Async()
{
string batchName = $"batch_{Guid.NewGuid()}";
MultipartContent batchContent = new MultipartContent("mixed", batchName);
string changesetName = $"changeset_{Guid.NewGuid()}";
MultipartContent changesetContent = new MultipartContent("mixed", changesetName);
contact1.Add("firstname", "Peter");
contact1.Add("lastname", "Cambel");
changesetContent.Add(CreateHttpMessageContent(HttpMethod.Post, "contacts", 1, contact1.ToString()));
contact2.Add("firstname", "Susie");
contact2.Add("lastname", "Curtis");
contact2.Add("jobtitle", "Coffee Master");
contact2.Add("annualincome", 48000);
changesetContent.Add(CreateHttpMessageContent(HttpMethod.Post, "contacts", 2, contact2.ToString()));
batchContent.Add(changesetContent);
batchContent.Add(CreateHttpMessageContent(HttpMethod.Get, "Account_Tasks?$select=subject"));
List<HttpResponseMessage> responses = await SendBatchRequestAsync(batchContent);
HandleResponses(responses);
}
public async Task Sample2Async()
{
List<HttpMessageContent> httpContents = new List<HttpMessageContent>();
for (int i = 1; i <= 5; i++)
{
JObject taskJson = new JObject
{
{ "subject", $"Task {i} in batch" },
{ "description", "Tackle Business Complexity" }
};
httpContents.Add(CreateHttpMessageContent(HttpMethod.Post, "tasks", i, taskJson.ToString()));
}
List<HttpResponseMessage> responses = await SendBatchRequestAsync(httpContents);
HandleResponses(responses);
}
private async void HandleResponses(List<HttpResponseMessage> responses)
{
foreach (HttpResponseMessage response in responses)
{
if (response.StatusCode == HttpStatusCode.NoContent) //204
{
string entityUri = response.Headers.GetValues("OData-EntityId").FirstOrDefault();
_entityUris.Add(entityUri);
Console.WriteLine("Entity URI: {0}", entityUri);
}
else if (response.StatusCode == HttpStatusCode.OK) //200
{
Console.WriteLine("Request was successful: {0}", await response.Content.ReadAsStringAsync());
}
else
{
Console.WriteLine("Request failed for reason: {0}", response.ReasonPhrase);
}
}
}
/// <summary>
///Provides the high-level logical flow of the program, as well as a section
/// containing cleanup code.
/// </summary>
public async Task RunAsync()
{
try
{
await GetWebAPIVersion();
await Sample1Async();
await Sample2Async();
}
catch (Exception ex)
{
DisplayException(ex);
}
finally
{
if (_entityUris.Any())
{
Console.WriteLine("\n--Section 5 started--");
//Delete all the created sample entities. Note that explicit deletion is not required
// for contact tasks because these are automatically cascade-deleted with owner.
Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
string answer = Console.ReadLine();
answer = answer.Trim();
if (!(answer.StartsWith("y") || answer.StartsWith("Y") || answer == string.Empty))
{
_entityUris.Clear();
}
HttpResponseMessage deleteResponse1;
int successCnt = 0, notFoundCnt = 0, failCnt = 0;
HttpContent lastBadResponseContent = null;
foreach (string ent in _entityUris)
{
deleteResponse1 = await _httpClient.DeleteAsync(ent);
if (deleteResponse1.IsSuccessStatusCode) //200-299
{
Console.WriteLine("Entity deleted: \n{0}.", ent);
successCnt++;
}
else if (deleteResponse1.StatusCode == HttpStatusCode.NotFound) //404
{
//May have been deleted by another user or via cascade operation
Console.WriteLine("Entity not found: {0}.", ent);
notFoundCnt++;
}
else
{
Console.WriteLine("Failed to delete: {0}.", ent);
failCnt++;
lastBadResponseContent = deleteResponse1.Content;
}
}
Console.WriteLine("Entities deleted: {0}, not found: {1}, delete " +
"failures: {2}. \n", successCnt, notFoundCnt, failCnt);
_entityUris.Clear();
if (failCnt > 0)
{
//Throw last failure
throw new CrmHttpResponseException(lastBadResponseContent);
}
}
}
}
public static void Main(string[] args)
{
BatchOperations app = new BatchOperations();
try
{
//Read configuration file and connect to specified CRM server.
app.ConnectToCRM(args);
Task.WaitAll(Task.Run(async () => await app.RunAsync()));
}
catch (System.Exception ex)
{
DisplayException(ex);
}
finally
{
if (app._httpClient != null)
{
app._httpClient.Dispose();
}
Console.WriteLine("Press <Enter> to exit the program.");
Console.ReadLine();
}
}
/// <summary>
/// Obtains the connection information from the application's configuration file, then
/// uses this info to connect to the specified CRM service.
/// </summary>
/// <param name="args"> Command line arguments. The first specifies the name of the
/// connection string setting. </param>
private void ConnectToCRM(string[] cmdargs)
{
//Create a helper object to read app.config for service URL and application
// registration settings.
Configuration config = null;
if (cmdargs.Length > 0)
{
config = new FileConfiguration(cmdargs[0]);
}
else
{
config = new FileConfiguration(null);
}
//Create a helper object to authenticate the user with this connection info.
Authentication auth = new Authentication(config);
//Next use a HttpClient object to connect to specified CRM Web service.
_httpClient = new HttpClient(auth.ClientHandler, true)
{
//Define the Web API base address, the max period of execute time, the
// default OData version, and the default response payload format.
BaseAddress = new Uri(config.ServiceUrl + "api/data/"),
Timeout = new TimeSpan(0, 2, 0)
};
_httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
_httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
/// <summary> Helper method to display caught exceptions </summary>
private static void DisplayException(Exception ex)
{
Console.WriteLine("The application terminated with an error.");
Console.WriteLine(ex.Message);
while (ex.InnerException != null)
{
Console.WriteLine("\t* {0}", ex.InnerException.Message);
ex = ex.InnerException;
}
}
}
}