generated from Kentico/repo-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDefaultDynamics365EntityMapper.cs
342 lines (280 loc) · 13.1 KB
/
DefaultDynamics365EntityMapper.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
using CMS;
using CMS.Activities;
using CMS.Core;
using CMS.DataEngine;
using CMS.Helpers;
using Kentico.Xperience.Dynamics365.Sales.Constants;
using Kentico.Xperience.Dynamics365.Sales.Models.Activities;
using Kentico.Xperience.Dynamics365.Sales.Models.Mapping;
using Kentico.Xperience.Dynamics365.Sales.Services;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
[assembly: RegisterImplementation(typeof(IDynamics365EntityMapper), typeof(DefaultDynamics365EntityMapper), Lifestyle = Lifestyle.Singleton, Priority = RegistrationPriority.SystemDefault)]
namespace Kentico.Xperience.Dynamics365.Sales.Services
{
/// <summary>
/// The default implementation of <see cref="IDynamics365EntityMapper"/>.
/// </summary>
public class DefaultDynamics365EntityMapper : IDynamics365EntityMapper
{
private readonly ISettingsService settingsService;
private readonly IDynamics365Client dynamics365Client;
private readonly IEventLogService eventLogService;
private readonly IProgressiveCache progressiveCache;
private string DefaultOwner
{
get
{
return settingsService[Dynamics365Constants.SETTING_DEFAULTOWNER];
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DefaultDynamics365EntityMapper"/> class.
/// </summary>
public DefaultDynamics365EntityMapper(
ISettingsService settingsService,
IDynamics365Client dynamics365Client,
IEventLogService eventLogService,
IProgressiveCache progressiveCache)
{
this.settingsService = settingsService;
this.dynamics365Client = dynamics365Client;
this.eventLogService = eventLogService;
this.progressiveCache = progressiveCache;
}
public string MapActivityType(string activityType)
{
return activityType;
}
public JObject MapActivity(string entityName, string dynamicsId, object relatedData)
{
var entity = new JObject();
MapCommonActivityProperties(dynamicsId, entity, relatedData);
switch (entityName)
{
case Dynamics365Constants.ACTIVITY_APPOINTMENT:
MapAppointmentProperties(dynamicsId, entity, relatedData);
break;
case Dynamics365Constants.ACTIVITY_TASK:
MapTaskProperties(dynamicsId, entity, relatedData);
break;
}
DecodeValues(entity);
return entity;
}
public Dictionary<string, string> MapChangedColumns(MappingModel mapping, BaseInfo xperienceObject, JObject entity)
{
var result = new Dictionary<string, string>();
foreach (var item in mapping.Items.Where(i => !String.IsNullOrEmpty(i.Dynamics365Field)))
{
if (!xperienceObject.ContainsColumn(item.XperienceFieldName))
{
continue;
}
var baseInfoValue = GetXperienceValue(item, xperienceObject);
var dynamicsValue = entity.Value<string>(item.Dynamics365Field);
if (String.IsNullOrEmpty(dynamicsValue) || ValidationHelper.GetString(baseInfoValue, String.Empty) == dynamicsValue)
{
continue;
}
result.Add(item.XperienceFieldName, dynamicsValue);
}
return result;
}
public JObject MapEntity(string entityName, MappingModel mapping, BaseInfo sourceObject)
{
var entity = new JObject();
foreach (var item in mapping.Items)
{
var baseInfoValue = GetXperienceValue(item, sourceObject);
if (baseInfoValue == null)
{
continue;
}
entity.Add(item.Dynamics365Field, JToken.FromObject(baseInfoValue));
}
DecodeValues(entity);
return entity;
}
public JObject MapPartialEntity(string entityName, MappingModel mapping, string dynamicsId, BaseInfo sourceObject)
{
var fullEntity = MapEntity(entityName, mapping, sourceObject);
try
{
// Get contact info from Dynamics
var endpoint = String.Format(Dynamics365Constants.ENDPOINT_ENTITY_PATCH_GETSINGLE, entityName, dynamicsId);
var response = dynamics365Client.SendRequest(endpoint, HttpMethod.Get);
var responseContent = response.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();
if (!response.IsSuccessStatusCode)
{
eventLogService.LogError(nameof(DefaultDynamics365EntityMapper), nameof(MapPartialEntity), $"Error while retrieving existing Dynamics 365 Entity: {responseContent}");
return null;
}
var dynamicsObject = JObject.Parse(responseContent);
foreach (var item in mapping.Items)
{
var baseInfoValue = GetXperienceValue(item, sourceObject);
var dynamicsValue = dynamicsObject.Value<string>(item.Dynamics365Field);
if (baseInfoValue == null || ValidationHelper.GetString(baseInfoValue, String.Empty) == dynamicsValue)
{
// Column doesn't exist in Xperience, or the value matches Dynamics
fullEntity.Remove(item.Dynamics365Field);
}
}
return fullEntity;
}
catch (Exception ex)
{
eventLogService.LogError(nameof(DefaultDynamics365EntityMapper), nameof(MapPartialEntity), ex.Message);
return null;
}
}
/// <summary>
/// Calls <see cref="HTMLHelper.HTMLDecode"/> on all string values in the <paramref name="entity"/>.
/// </summary>
private void DecodeValues(JObject entity)
{
foreach(var property in entity.Properties())
{
if (property.Value.Type == JTokenType.String)
{
property.Value = JToken.FromObject(HTMLHelper.HTMLDecode(property.Value.Value<string>()));
}
}
}
/// <summary>
/// Gets the value of the <see cref="MappingItem.XperienceFieldName"/> from the <paramref name="baseInfo"/>.
/// </summary>
/// <param name="mapping">The mapping containing the Xperience field name to retrieve the value of.</param>
/// <param name="baseInfo">The Xperience object to retrieve the value from.</param>
/// <returns>The Xperience object's field value.</returns>
private object GetXperienceValue(MappingItem mapping, BaseInfo baseInfo)
{
var baseInfoValue = baseInfo.GetValue(mapping.XperienceFieldName);
if (mapping.DynamicsAttributeType == EntityAttributeType.DATETIME)
{
// Convert DateTime to either Date and Time or only Date
return GetValidDateTime(baseInfoValue, mapping);
}
return baseInfoValue;
}
/// <summary>
/// Converts an Xperience object's value into the proper format for upserting into Dynamics 365.
/// </summary>
/// <param name="xperienceValue">The Xperience object's field value.</param>
/// <param name="mapping">The mapping that was used to retrieve the <paramref name="xperienceValue"/>.</param>
/// <returns>A valid Edm.Date value in string format.</returns>
private string GetValidDateTime(object xperienceValue, MappingItem mapping)
{
var retVal = ValidationHelper.GetDateTime(xperienceValue, DateTime.MinValue);
if (retVal == DateTime.MinValue)
{
return null;
}
if (mapping.DynamicsAttributeFormat == "DateOnly")
{
return retVal.ToString("yyyy-MM-dd");
}
else if (mapping.DynamicsAttributeFormat == "DateAndTime")
{
return retVal.ToString();
}
return null;
}
/// <summary>
/// Maps Entity properties which all activities should contain.
/// </summary>
/// <param name="dynamicsId">The internal Dynamics 365 contact ID associated with the activity.</param>
/// <param name="entity">The Entity to map.</param>
/// <param name="relatedData">An object containing the required data for the activity, such as <see cref="ActivityInfo"/>.</param>
private void MapCommonActivityProperties(string dynamicsId, JObject entity, object relatedData)
{
if (relatedData is ActivityInfo)
{
entity.Add("scheduledstart", (relatedData as ActivityInfo).ActivityCreated);
}
entity.Add("isregularactivity", true);
entity.Add($"regardingobjectid_{Dynamics365Constants.ENTITY_CONTACT}@odata.bind", $"/{Dynamics365Constants.ENTITY_CONTACT}s({dynamicsId})");
if (!String.IsNullOrEmpty(DefaultOwner))
{
entity.Add("[email protected]", DefaultOwner);
}
}
private void MapAppointmentProperties(string dynamicsId, JObject entity, object relatedData)
{
if (!(relatedData is Dynamics365AppointmentModel))
{
throw new InvalidOperationException($"{nameof(Dynamics365AppointmentModel)} is required to map the appointment activity.");
}
var appointmentModel = relatedData as Dynamics365AppointmentModel;
entity.Add("subject", appointmentModel.Subject);
entity.Add("isalldayevent", appointmentModel.IsAllDay);
entity.Add("scheduleddurationminutes", appointmentModel.IsAllDay ? 1440 : ValidationHelper.GetInteger(appointmentModel.EndTime.Subtract(appointmentModel.StartTime).TotalMinutes, 0));
if (!String.IsNullOrEmpty(appointmentModel.Description))
{
entity.Add("description", appointmentModel.Description);
}
var parties = new JArray();
if (!String.IsNullOrEmpty(appointmentModel.RequiredAttendee))
{
parties.Add(new JObject(new JProperty("participationtypemask", ParticipationTypeMaskEnum.RequiredAttendee), new JProperty($"partyid_{Dynamics365Constants.ENTITY_USER}@odata.bind", appointmentModel.RequiredAttendee)));
}
if (!String.IsNullOrEmpty(appointmentModel.OptionalAttendee))
{
parties.Add(new JObject(new JProperty("participationtypemask", ParticipationTypeMaskEnum.OptionalAttendee), new JProperty($"partyid_{Dynamics365Constants.ENTITY_USER}@odata.bind", appointmentModel.OptionalAttendee)));
}
if (!String.IsNullOrEmpty(DefaultOwner) && DefaultOwner.StartsWith($"/{Dynamics365Constants.ENTITY_USER}"))
{
parties.Add(new JObject(new JProperty("participationtypemask", ParticipationTypeMaskEnum.Organizer), new JProperty($"partyid_{Dynamics365Constants.ENTITY_USER}@odata.bind", DefaultOwner)));
}
if (parties.Count > 0)
{
entity.Add("appointment_activity_parties", parties);
}
if (!String.IsNullOrEmpty(appointmentModel.Location))
{
entity.Add("location", appointmentModel.Location);
}
if (appointmentModel.StartTime > DateTime.MinValue)
{
entity.Add("scheduledstart", appointmentModel.StartTime);
}
if (appointmentModel.EndTime > DateTime.MinValue)
{
entity.Add("scheduledend", appointmentModel.EndTime);
}
else if (appointmentModel.IsAllDay)
{
entity.Add("scheduledend", appointmentModel.StartTime.AddDays(1));
}
}
private void MapTaskProperties(string dynamicsId, JObject entity, object relatedData)
{
if (!(relatedData is Dynamics365TaskModel))
{
throw new InvalidOperationException($"{nameof(Dynamics365TaskModel)} is required to map the task activity.");
}
var taskModel = relatedData as Dynamics365TaskModel;
entity.Add("subject", taskModel.Subject);
if (!String.IsNullOrEmpty(taskModel.Description))
{
entity.Add("description", taskModel.Description);
}
if (taskModel.DueDate != DateTime.MinValue)
{
entity.Add("scheduledend", taskModel.DueDate);
}
if (taskModel.DurationMinutes > 0)
{
entity.Add("actualdurationminutes", taskModel.DurationMinutes);
}
if (taskModel.Priority > -1)
{
entity.Add("prioritycode", taskModel.Priority);
}
}
}
}