forked from JoseFuentesDevAp/CRMSDKExample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAccountHandler.cs
More file actions
545 lines (430 loc) · 20.1 KB
/
Copy pathAccountHandler.cs
File metadata and controls
545 lines (430 loc) · 20.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.PowerPlatform.Dataverse.Client;
public class AccountHandler
{
public void getAccountInfo(string accountId, ServiceClient serviceClient)
{
Entity accountInfo = serviceClient.Retrieve("account", new Guid(accountId), new ColumnSet(true));
Console.WriteLine($"Account Name: {accountInfo.Attributes["name"]}");
Console.WriteLine($"Account ExchRate: {accountInfo.Attributes["exchangerate"]}");
/*
customertypecode
msdyn_company
transactioncurrencyid
msdyn_language
msdyn_segmentid
*/
}
public void CreateAccount(Account _account, ServiceClient serviceClient)
{
Entity account = new Entity("account");
account["accountnumber"] = _account.AccountNum;
account["name"] = _account.Name;
account["exchangerate"] = _account.ExchangeRate;
account["emailaddress1"] = _account.EmailAddress1;
account["telephone1"] = _account.Telephone1;
account["address1_country"] = _account.Address1_Country;
account["address1_postalcode"] = _account.Address1_PostalCode;
account["transactioncurrencyid"] = this.GetCurrencyReference(_account.CurrencyId, serviceClient);
account["customertypecode"] = new OptionSetValue(_account.CustomerTypeCode);
account["shippingmethodcode"] = new OptionSetValue(_account.ShippingMethodCode);
account["industrycode"] = new OptionSetValue(_account.IndustryCode);
account["creditlimit"] = new Money(_account.Creditlimit);
account["creditonhold"] = (bool)_account.CreditOnHold;
account["lastonholdtime"] = _account.LastOnHoldTime;
Guid accountId = serviceClient.Create(account);
Console.WriteLine($"Account created with ID: {accountId.ToString()}");
}
public void UpdateAccount(Account _account, ServiceClient serviceClient)
{
Entity account = new Entity("account", new Guid(_account.AccountId));
account["name"] = _account.Name;
account["exchangerate"] = _account.ExchangeRate;
account["emailaddress1"] = _account.EmailAddress1;
account["telephone1"] = _account.Telephone1;
serviceClient.Update(account);
Console.WriteLine($"Account updated with ID: {_account.AccountId}");
}
public void DeleteAccount(string accountId, ServiceClient serviceClient)
{
serviceClient.Delete("account", new Guid(accountId));
Console.WriteLine($"Account deleted with ID: {accountId}");
}
public void getAccountPerCountry(string country, ServiceClient serviceClient)
{
Console.WriteLine($"Retrieving accounts in country: {country}");
QueryExpression query = new QueryExpression("account");
query.ColumnSet = new ColumnSet("name", "exchangerate", "telephone1", "address1_country");
query.Criteria.AddCondition("address1_country", ConditionOperator.Equal, country);
EntityCollection accounts = serviceClient.RetrieveMultiple(query);
foreach (var account in accounts.Entities)
{
Console.WriteLine($"Account Name: {account["name"]}, Exchange Rate: {account["exchangerate"]}, Country: {account["address1_country"]}");
}
}
public void updateTelephoneByCountryCode(string countryCode, string phoneCode, ServiceClient serviceClient)
{
Console.WriteLine($"Updating telephone for accounts in country code: {countryCode}");
QueryExpression query = new QueryExpression("account");
query.ColumnSet = new ColumnSet("name", "telephone1", "address1_country");
query.Criteria.AddCondition("address1_country", ConditionOperator.Equal, countryCode);
EntityCollection accounts = serviceClient.RetrieveMultiple(query);
foreach (var account in accounts.Entities)
{
if (account["telephone1"] is null)
{
continue;
}
string newTelephone = account["telephone1"].ToString();
if (newTelephone.StartsWith(phoneCode))
{
Console.WriteLine($"Account {account["name"]} already has the phone code {phoneCode}. Skipping update.");
continue;
}
account["telephone1"] = phoneCode + account["telephone1"].ToString();
serviceClient.Update(account);
Console.WriteLine($"Updated Account Name: {account["name"]}, New Telephone: {newTelephone}");
}
}
public void createOrUpdateAccount(Account _account, ServiceClient serviceClient)
{
/*
creditlimit
creditonhold
paymenttermscode
transactioncurrencyid
*/
bool existsAccount = false;
if (string.IsNullOrEmpty(_account.AccountNum))
{
Console.WriteLine("Code is required for creating or updating an account.");
return;
}
QueryExpression accountQuery = new QueryExpression("account");
accountQuery.ColumnSet = new ColumnSet("accountnumber", "accountid");
accountQuery.Criteria.AddCondition("accountnumber", ConditionOperator.Equal, _account.AccountNum);
EntityCollection accounts = serviceClient.RetrieveMultiple(accountQuery);
Entity account;
if (accounts.Entities.Count > 0)
{
existsAccount = true;
_account.AccountId = accounts.Entities[0].Id.ToString();
account = new Entity("account", new Guid(_account.AccountId));
}
else
{
existsAccount = false;
account = new Entity("account");
account["accountnumber"] = _account.AccountNum;
}
account["name"] = _account.Name;
account["exchangerate"] = _account.ExchangeRate;
account["emailaddress1"] = _account.EmailAddress1;
account["telephone1"] = _account.Telephone1;
account["address1_country"] = _account.Address1_Country;
account["address1_postalcode"] = _account.Address1_PostalCode;
account["creditlimit"] = new Money(_account.Creditlimit); // Tipo Moneda
account["creditonhold"] = _account.CreditOnHold; // Dos opciones
account["paymenttermscode"] = new OptionSetValue(_account.CustomerTypeCode); // Condciones de Pago (opción múltiple)
//account["transactioncurrencyid"] = new EntityReference("transactioncurrency", new Guid(_account.CurrencyId));
EntityReference currencyReference = GetCurrencyReference(_account.CurrencyId, serviceClient);
if (currencyReference != null)
{
account["transactioncurrencyid"] = currencyReference; // Dato referencia de búsqueda (lookup)
}
else
{
Console.WriteLine($"Currency with ISO code {_account.CurrencyId} not found.");
return;
}
if (existsAccount)
{
serviceClient.Update(account);
Console.WriteLine($"Account updated with ID: {_account.AccountId}");
}
else
{
Guid accountId = serviceClient.Create(account);
Console.WriteLine($"Account created with ID: {accountId.ToString()}");
}
}
public EntityReference GetCustomerGroup(string _customerGroupId, ServiceClient serviceClient)
{
if (string.IsNullOrEmpty(_customerGroupId))
{
return null;
}
/*
Entidad Divisa: transactioncurrency
Criterio de búsqueda: isocurrencycode
*/
QueryExpression query = new QueryExpression("msdyn_customergroup");
query.ColumnSet = new ColumnSet("msdyn_groupid", "msdyn_customergroupid");
query.Criteria.AddCondition("msdyn_groupid", ConditionOperator.Equal, _customerGroupId);
EntityCollection currencyCollection = serviceClient.RetrieveMultiple(query);
if (currencyCollection.Entities.Count == 0)
{
return null;
}
Entity currency = currencyCollection.Entities[0];
return new EntityReference("msdyn_customergroup", currency.Id);
}
public EntityReference GetCurrencyReference(string _isoCurrencyCode, ServiceClient serviceClient)
{
if (string.IsNullOrEmpty(_isoCurrencyCode))
{
return null;
}
/*
Entidad Divisa: transactioncurrency
Criterio de búsqueda: isocurrencycode
*/
QueryExpression query = new QueryExpression("transactioncurrency");
query.ColumnSet = new ColumnSet("isocurrencycode", "transactioncurrencyid");
query.Criteria.AddCondition("isocurrencycode", ConditionOperator.Equal, _isoCurrencyCode);
EntityCollection currencyCollection = serviceClient.RetrieveMultiple(query);
if (currencyCollection.Entities.Count == 0)
{
return null; // No se encontró la divisa con el código ISO proporcionado
}
Entity currency = currencyCollection.Entities[0];
return new EntityReference("transactioncurrency", currency.Id);
}
public void CreateAccountsBulk(List<Account> accounts, ServiceClient serviceClient)
{
// Configurar ExecuteMultipleRequest
var executeMultipleRequest = new ExecuteMultipleRequest()
{
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = true, // Continuar aunque fallen algunos registros
ReturnResponses = true // Devolver respuestas individuales
},
Requests = new OrganizationRequestCollection()
};
// Agregar cada account como CreateRequest
foreach (var _account in accounts)
{
Entity account = new Entity("account");
account["accountnumber"] = _account.AccountNum;
account["name"] = _account.Name;
account["exchangerate"] = _account.ExchangeRate;
account["emailaddress1"] = _account.EmailAddress1;
account["telephone1"] = _account.Telephone1;
account["address1_country"] = _account.Address1_Country;
account["address1_postalcode"] = _account.Address1_PostalCode;
account["transactioncurrencyid"] = this.GetCurrencyReference(_account.CurrencyId, serviceClient);
account["customertypecode"] = new OptionSetValue(_account.CustomerTypeCode);
account["shippingmethodcode"] = new OptionSetValue(_account.ShippingMethodCode);
account["industrycode"] = new OptionSetValue(_account.IndustryCode);
account["creditlimit"] = new Money(_account.Creditlimit);
account["creditonhold"] = (bool)_account.CreditOnHold;
account["lastonholdtime"] = _account.LastOnHoldTime;
CreateRequest createRequest = new CreateRequest { Target = account };
executeMultipleRequest.Requests.Add(createRequest);
}
// Ejecutar la inserción masiva
Console.WriteLine($"Iniciando inserción masiva de {accounts.Count} cuentas...");
var executeMultipleResponse = (ExecuteMultipleResponse)serviceClient.Execute(executeMultipleRequest);
// Procesar resultados
int successCount = 0;
int errorCount = 0;
for (int i = 0; i < executeMultipleResponse.Responses.Count; i++)
{
var responseItem = executeMultipleResponse.Responses[i];
if (responseItem.Fault == null)
{
var createdId = ((CreateResponse)responseItem.Response).id;
Console.WriteLine($"✓ Account '{accounts[i].Name}' creada con ID: {createdId}");
successCount++;
}
else
{
Console.WriteLine($"✗ Error al crear '{accounts[i].Name}': {responseItem.Fault.Message}");
errorCount++;
}
}
Console.WriteLine($"\nResumen: {successCount} exitosas, {errorCount} fallidas de {accounts.Count} totales");
}
public void getAccountFetch(ServiceClient serviceClient)
{
string fetchXml = @"
<fetch version='1.0' output-format='xml-platform' mapping='logical' no-lock='false' distinct='true'>
<entity name='account'>
<attribute name='accountid'/>
<attribute name='telephone1'/>
<attribute name='name'/>
<attribute name='statecode'/>
<filter type='and'>
<condition attribute='telephone1' operator='not-null' />
</filter>
</entity>
</fetch>";
string fetchXMLERP = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' no-lock='false'>
<entity name='account'>
<attribute name='statecode'/>
<attribute name='name'/>
<attribute name='accountid'/>
<attribute name='transactioncurrencyid'/>
<attribute name='creditlimit'/>
<attribute name='shippingmethodcode'/>
<attribute name='accountnumber'/>
<order attribute='accountnumber' descending='false'/>
<filter type='and'>
<condition attribute='accountnumber' operator='not-null'/>
</filter>
</entity>
</fetch>";
FetchExpression fetchExpression = new FetchExpression(fetchXMLERP);
EntityCollection accounts = serviceClient.RetrieveMultiple(fetchExpression);
if (accounts.Entities.Count == 0)
{
Console.WriteLine("No accounts found.");
return;
}
Console.WriteLine("Accounts found:");
foreach (Entity account in accounts.Entities)
{
Console.WriteLine($"ERP Code {account["accountnumber"]} - Name: {account["name"]} - Credit Limit {((Money)account["creditlimit"]).Value} - Payment Terms : {((OptionSetValue)account["shippingmethodcode"]).Value}");
}
}
public void getAcountByCodeFetch(ServiceClient serviceClient, string erpCode)
{
string fetchXMLERP = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' no-lock='false'>
<entity name='account'>
<attribute name='statecode'/>
<attribute name='name'/>
<attribute name='accountid'/>
<attribute name='transactioncurrencyid'/>
<attribute name='creditlimit'/>
<attribute name='shippingmethodcode'/>
<attribute name='accountnumber'/>
<order attribute='accountnumber' descending='false'/>
<filter type='and'>
<condition attribute='accountnumber' operator='eq' value='{0}'/>
</filter>
</entity>
</fetch>";
fetchXMLERP = string.Format(fetchXMLERP, erpCode);
FetchExpression fetchExpression = new FetchExpression(fetchXMLERP);
EntityCollection accounts = serviceClient.RetrieveMultiple(fetchExpression);
if (accounts.Entities.Count == 0)
{
Console.WriteLine("No accounts found.");
return;
}
Console.WriteLine("Accounts found:");
foreach (Entity account in accounts.Entities)
{
string currencyIsoCode = string.Empty;
if (account.Contains("transactioncurrencyid"))
{
EntityReference currencyRef = (EntityReference)account["transactioncurrencyid"];
Entity currency = serviceClient.Retrieve(currencyRef.LogicalName, currencyRef.Id, new ColumnSet("isocurrencycode"));
if (currency != null && currency.Contains("isocurrencycode"))
{
currencyIsoCode = currency["isocurrencycode"].ToString();
}
}
Console.WriteLine($"ERP Code {account["accountnumber"]} - Name: {account["name"]} - Currency {currencyIsoCode} - Credit Limit {((Money)account["creditlimit"]).Value} - Payment Terms : {((OptionSetValue)account["shippingmethodcode"]).Value}");
}
}
public void getAcountByCodeFetchLinkEntity(ServiceClient serviceClient, string erpCode)
{
string fetchXMLERP = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' no-lock='false'>
<entity name='account'>
<attribute name='accountnumber'/>
<attribute name='statecode'/>
<attribute name='name'/>
<attribute name='accountid'/>
<attribute name='transactioncurrencyid'/>
<attribute name='creditlimit'/>
<attribute name='paymenttermscode'/>
<filter type='and'>
<condition attribute='accountnumber' operator='eq' value='{0}'/>
</filter>
<link-entity alias='currency' name='transactioncurrency' to='transactioncurrencyid' from='transactioncurrencyid' link-type='outer' >
<attribute name='isocurrencycode'/>
</link-entity>
</entity>
</fetch>";
fetchXMLERP = string.Format(fetchXMLERP, erpCode);
FetchExpression fetchExpression = new FetchExpression(fetchXMLERP);
EntityCollection accounts = serviceClient.RetrieveMultiple(fetchExpression);
if (accounts.Entities.Count == 0)
{
Console.WriteLine("No accounts found.");
return;
}
Console.WriteLine("Accounts found:");
foreach (Entity account in accounts.Entities)
{
string currencyIsoCode = string.Empty;
if (account.Contains("transactioncurrencyid"))
{
AliasedValue currencyAliased = (AliasedValue)account["currency.isocurrencycode"];
if (currencyAliased != null && currencyAliased.Value != null)
{
currencyIsoCode = currencyAliased.Value.ToString();
}
}
Console.WriteLine($"Code {(account.Contains("accountnumber") ? account["accountnumber"] : "")} - " +
$"Name: {(account.Contains("name") ? account["name"] : "")} - " +
$"Currency {currencyIsoCode} - " +
$"Credit Limit {(account.Contains("creditlimit") ? ((Money)account["creditlimit"]).Value : 0)} - " +
$"Payment Terms: {(account.Contains("paymenttermscode") ? ((OptionSetValue)account["paymenttermscode"]).Value : 0)}");
}
}
public void getAcountByCurrencyFetchLinkEntity(ServiceClient serviceClient, string _currencyIsoCode)
{
string fetchXMLERP = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' no-lock='false'>
<entity name='account'>
<attribute name='statecode'/>
<attribute name='name'/>
<attribute name='accountid'/>
<attribute name='transactioncurrencyid'/>
<attribute name='creditlimit'/>
<attribute name='paymenttermscode'/>
<attribute name='accountnumber'/>
<order attribute='accountnumber' descending='false'/>
<filter type='and'>
<condition attribute='accountnumber' operator='not-null'/>
</filter>
<link-entity alias='currency' name='transactioncurrency' to='transactioncurrencyid' from='transactioncurrencyid' link-type='inner' >
<attribute name='isocurrencycode'/>
<filter type='and'>
<condition attribute='isocurrencycode' operator='eq' value='{0}'/>
</filter>
</link-entity>
</entity>
</fetch>";
fetchXMLERP = string.Format(fetchXMLERP, _currencyIsoCode);
FetchExpression fetchExpression = new FetchExpression(fetchXMLERP);
EntityCollection accounts = serviceClient.RetrieveMultiple(fetchExpression);
if (accounts.Entities.Count == 0)
{
Console.WriteLine("No accounts found.");
return;
}
Console.WriteLine($"Accounts found with Currency Code:{_currencyIsoCode}");
foreach (Entity account in accounts.Entities)
{
string currencyIsoCode = string.Empty;
if (account.Contains("transactioncurrencyid"))
{
AliasedValue currencyAliased = (AliasedValue)account["currency.isocurrencycode"];
if (currencyAliased != null && currencyAliased.Value != null)
{
currencyIsoCode = currencyAliased.Value.ToString();
}
}
Console.WriteLine($"Code {(account.Contains("accountnumber") ? account["accountnumber"] : "")} - " +
$"Name: {(account.Contains("name") ? account["name"] : "")} - " +
$"Currency {currencyIsoCode} - " +
$"Credit Limit {(account.Contains("creditlimit") ? ((Money)account["creditlimit"]).Value : 0)} - " +
$"Payment Terms: {(account.Contains("paymenttermscode") ? ((OptionSetValue)account["paymenttermscode"]).Value : 0)}");
}
}
}