-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathMyPluginControl.cs
More file actions
2063 lines (1887 loc) · 120 KB
/
MyPluginControl.cs
File metadata and controls
2063 lines (1887 loc) · 120 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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using XrmToolBox.Extensibility;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Messages;
using System.ServiceModel;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;
using McTools.Xrm.Connection;
using XrmToolBox.Extensibility.Interfaces;
using Microsoft.Crm.Sdk.Messages;
using System.Web.Services.Description;
namespace DataImport
{
public partial class MyPluginControl : PluginControlBase, IGitHubPlugin, IHelpPlugin
{
// CREATE EXCEL OBJECTS.
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range xlRange;
EntityMetadata resultsaved;
EntityMetadata lkpresultsaved;
RichTextBox richTextBoxErrors = new RichTextBox();
RichTextBox richTextBoxImported = new RichTextBox();
RichTextBox richTextBoxAll = new RichTextBox();
RichTextBox richTextBoxWarning = new RichTextBox();
//DataGridViewComboBoxCell dcc; //??
string sFileName;
bool strIsKey;
bool IsReadyToImport = false;
string qestr;
int iRow, iCol = 1;
bool flaglookup;
int lookupscount;
StringBuilder boxall = new StringBuilder();
StringBuilder boxwarning = new StringBuilder();
StringBuilder boxerror = new StringBuilder();
StringBuilder boxsuccess = new StringBuilder();
int successnumber = 0;
int errornumber = 0;
int creatednumber = 0;
int updatednumber = 0;
int deletednumber = 0;
int importRunNumber = 0; // Number of times the Excel Import process has been run
// The Settings for the import
private Settings settings = Settings.Instance;
// To store the table logs
DataTable tableLogEntries = new DataTable();
// To store the Excel Mapping once ready for import
DataTable tableMapping = new DataTable();
#region Initialising Plugin
public MyPluginControl()
{
InitializeComponent();
}
public void MyPluginControl_Load(object sender, System.EventArgs e)
{
mainTableLayout.RowStyles[1] = new RowStyle(SizeType.Absolute, 0); // Hides the logs
dataGridViewMapping.Enabled = false; // Locks all the mapping until Excel is loaded.
settingsLookupFoundMultipleRecords.SelectedIndex = 0;
settingsCrmAction.SelectedIndex = 0;
textView.SelectedIndex = 0;
settingsOptionSetValuesOrLabel.SelectedIndex = 0;
settingsKeyFoundMultipleRecords.SelectedIndex = 0;
completeRecords.Checked = false;
ExecuteMethod(InitEntities);
// Initialise the table logs
tableLogEntries.Columns.Add("Import", typeof(int));
tableLogEntries.Columns.Add("Line", typeof(int));
tableLogEntries.Columns.Add("Result", typeof(string));
tableLogEntries.Columns.Add("Updates", typeof(int));
tableLogEntries.Columns.Add("GUID", typeof(string));
tableLogEntries.Columns.Add("Logs", typeof(string));
dataGridViewLogs.DataSource = tableLogEntries;
tableMapping.TableName = "TableMapping";
// Initialise the table mapping
tableMapping.Columns.Add("ExcelColumn");
tableMapping.Columns.Add("isKey", typeof(bool));
tableMapping.Columns.Add("CRMField");
tableMapping.Columns.Add("IsLookup");
tableMapping.Columns.Add("lkpTargetEntity");
tableMapping.Columns.Add("lkpTargetfield");
tableMapping.Columns.Add("Truevalue");
tableMapping.Columns.Add("Falsevalue");
tableMapping.Columns.Add("DefaultValue");
tableMapping.Columns.Add("BlankBehaviour");
tableMapping.Columns.Add("DataType");
this.dataGridViewMapping.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridViewMapping_CellValueChanged);
}
#endregion Initialising Plugin
#region XRMToolbox Commands
// If the connection is updated and another environment is chosen.
public override void UpdateConnection(IOrganizationService newService, ConnectionDetail detail, string actionName, object parameter)
{
base.UpdateConnection(newService, detail, actionName, parameter);
InitEntities();
}
private void TsbClose_Click(object sender, EventArgs e)
{
CloseTool();
}
#region IGitHubPlugin implementation
public string RepositoryName => "XTBPlugins.DataImport";
public string UserName => "YesWeCandrew";
#endregion IGitHubPlugin implementation
#region IHelpPlugin implementation
public string HelpUrl => "https://github.com/YesWeCandrew/XTBPlugins.DataImport/blob/master/README.md";
#endregion IHelpPlugin implementation
#endregion XRMToolbox Commands
#region Retrieving Data From Dynamics
public void InitEntities()
{
WorkAsync(new WorkAsyncInfo
{
Message = "Getting entities",
Work = (worker, args) =>
{
RetrieveAllEntitiesResponse metaDataResponse = new RetrieveAllEntitiesResponse();
RetrieveAllEntitiesRequest retrieveAllEntitiesRequest = new RetrieveAllEntitiesRequest
{
RetrieveAsIfPublished = true,
EntityFilters = EntityFilters.Attributes
};
retrieveAllEntitiesRequest.EntityFilters = EntityFilters.Entity;
// Execute the request.
args.Result = (RetrieveAllEntitiesResponse)Service.Execute(retrieveAllEntitiesRequest);
},
PostWorkCallBack = (args) =>
{
if (args.Error != null)
{
MessageBox.Show(args.Error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
settingsEntity.Items.Clear();
lkpTargetEntity.Items.Clear();
var result = args.Result as RetrieveAllEntitiesResponse;
if (result != null)
{
var entities = result.EntityMetadata;
foreach (EntityMetadata Entity in entities)
{
settingsEntity.Items.Add(Entity.LogicalName);
lkpTargetEntity.Items.Add(Entity.LogicalName);
}
}
}
});
}
private void InitEntityFields()
{
if (settingsEntity.SelectedItem == null)
{
//MessageBox.Show("Please load entities first and pick your entity then press this button.");
//ExecuteMethod(InitEntities);
return;
}
CRMField.Items.Clear();
WorkAsync(new WorkAsyncInfo
{
Message = "Getting entity fields",
Work = (worker, args) =>
{
Dictionary<string, string> attributesData = new Dictionary<string, string>();
RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.All,
LogicalName = settings.Entity
};
// Execute the request
args.Result = (RetrieveEntityResponse)Service.Execute(retrieveEntityRequest);
},
PostWorkCallBack = (args) =>
{
if (args.Error != null)
{
MessageBox.Show(args.Error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
var result = args.Result as RetrieveEntityResponse;
resultsaved = result.EntityMetadata;
if (result != null)
{
CRMField.Items.Add("");
foreach (object attribute in resultsaved.Attributes)
{
AttributeMetadata a = (AttributeMetadata)attribute;
if (a.AttributeType.ToString() == "DateTime" || a.AttributeType.ToString() == "State" || a.AttributeType.ToString() == "Status" || a.AttributeType.ToString() == "Memo" || a.AttributeType.ToString() == "String" || (a.AttributeType.ToString() == "Virtual" && a.SourceType == 0) || a.AttributeType.ToString() == "Picklist" || a.AttributeType.ToString() == "Boolean" || a.AttributeType.ToString() == "Integer" || a.AttributeType.ToString() == "Decimal" || a.AttributeType.ToString() == "Money" || a.AttributeType.ToString() == "Lookup" || a.AttributeType.ToString() == "Customer" || a.AttributeType.ToString() == "PartyList" || a.AttributeType.ToString() == "Uniqueidentifier" || a.AttributeType.ToString() == "Owner")
CRMField.Items.Add(a.LogicalName.ToString());
}
}
ProcessFields();
setInstructionVisibility(false);
dataGridViewMapping.Enabled = true;
}
});
}
private void InitLookupFields(string myentity, int thatRow)
{
if (myentity == null || myentity == "")
{
return;
}
//lkpTargetfield.Items.Clear();
DataGridViewComboBoxCell datalkpfield = dataGridViewMapping.Rows[thatRow].Cells[5] as DataGridViewComboBoxCell;
datalkpfield.Items.Clear();
WorkAsync(new WorkAsyncInfo
{
Message = "Getting entity fields",
Work = (worker, args) =>
{
Dictionary<string, string> attributesData = new Dictionary<string, string>();
RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.All,
LogicalName = myentity
};
// Execute the request
args.Result = (RetrieveEntityResponse)Service.Execute(retrieveEntityRequest);
},
PostWorkCallBack = (args) =>
{
if (args.Error != null)
{
MessageBox.Show(args.Error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
var result = args.Result as RetrieveEntityResponse;
lkpresultsaved = result.EntityMetadata;
if (result != null)
{
DataGridViewComboBoxCell stateCell = (DataGridViewComboBoxCell)(dataGridViewMapping.Rows[thatRow].Cells[5]);
foreach (object attribute in lkpresultsaved.Attributes)
{
AttributeMetadata a = (AttributeMetadata)attribute;
if (a.AttributeType.ToString() == "Uniqueidentifier" || a.AttributeType.ToString() == "String" || a.AttributeType.ToString() == "State" /*|| a.AttributeType.ToString() == "DateTime" || a.AttributeType.ToString() == "Integer" || a.AttributeType.ToString() == "Decimal" || a.AttributeType.ToString() == "Money"*/)
{
stateCell.Items.Add(a.LogicalName.ToString());
}
}
}
}
});
}
#endregion Retrieving Data From Dynamics
#region Get Excel
private void BrowseFileButton_Click(object sender, EventArgs e)
{
GetFile();
}
private void GetFile()
{
openFileDialog.FileName = "";
openFileDialog.Title = "Excel File to Import";
openFileDialog.Filter = "Excel File|*.xlsx;*.xls";
DialogResult result = openFileDialog.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
EmptyDataGrid();
string file = openFileDialog.FileName;
try
{
sFileName = openFileDialog.FileName;
if (sFileName.Trim() != "")
{
ReadExcel(sFileName);
settingsPanel.Enabled = true; // Enable all controls now that Excel is loaded
loadSettingsButton.Enabled = true;
saveSettingsButton.Enabled = true;
}
}
catch (IOException ex)
{
MessageBox.Show("Failed to load Excel file correctly:" + ex.Message.ToString());
}
}
}
// GET DATA FROM EXCEL AND POPULATE COMB0 BOX.
private void ReadExcel(string sFile)
{
WorkAsync(new WorkAsyncInfo
{
Message = "Reading Excel File..",
Work = (worker, args) =>
{
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(sFile); // WORKBOOK TO OPEN THE EXCEL FILE.
xlWorkSheet = xlWorkBook.Worksheets[1]; // NAME OF THE SHEET.
xlRange = xlWorkSheet.UsedRange;
},
PostWorkCallBack = (args) =>
{
for (iCol = 1; iCol <= xlRange.Columns.Count; iCol++) // START FROM THE SECOND ROW.
{
if (xlRange.Cells[1, iCol].value == null)
{
break; // BREAK LOOP.
}
else
{
dataGridViewMapping.Rows.Add(xlRange.Cells[1, iCol].value);
// Set default for load to CRM to Keeps CRM Value
dataGridViewMapping.Rows[iCol-1].Cells[9].Value = "Keeps CRM value";
}
}
// Set the labels and row values to the correct values.
toolStripStatusRowsNum.Text = ((xlRange.Rows.Count) - 1).ToString();
rowEndNum.Maximum = xlRange.Rows.Count;
rowEndNum.Minimum = 2;
rowEndNum.Value = xlRange.Rows.Count;
rowStartNum.Maximum = xlRange.Rows.Count;
rowStartNum.Value = 2;
xlWorkBook.Close();
xlApp.Quit();
processFieldsButton.Enabled = true;
}
});
}
#endregion Get Excel
#region Logging
#region OriginalLogging
private void SetTextBox1()
{
if (textView.SelectedItem.ToString() == "📙 ALL")
{
logTextBox.Text = richTextBoxAll.Text;
}
else if (textView.SelectedItem.ToString() == "✓ SUCCESS")
{
logTextBox.Text = richTextBoxImported.Text;
}
else if (textView.SelectedItem.ToString() == "❌ ERRORS")
{
logTextBox.Text = richTextBoxErrors.Text;
}
else if (textView.SelectedItem.ToString() == "⚠ WARNINGS")
{
logTextBox.Text = richTextBoxWarning.Text;
}
toolStripStatusSuccessNum.Text = successnumber.ToString();
toolStripStatusErrorNum.Text = errornumber.ToString();
toolStripStatusCreatedNum.Text = creatednumber.ToString();
toolStripStatusUpdatedNum.Text = updatednumber.ToString();
toolStripStatusDeletedNum.Text = deletednumber.ToString();
}
private void TextView_DropDownClosed(object sender, EventArgs e)
{
//SetTextBox1();
if (textView.SelectedItem.ToString() == "📙 ALL")
{
logTextBox.Text = richTextBoxAll.Text;
}
else if (textView.SelectedItem.ToString() == "✓ SUCCESS")
{
logTextBox.Text = richTextBoxImported.Text;
}
else if (textView.SelectedItem.ToString() == "❌ ERRORS")
{
logTextBox.Text = richTextBoxErrors.Text;
}
else if (textView.SelectedItem.ToString() == "⚠ WARNINGS")
{
logTextBox.Text = richTextBoxWarning.Text;
}
toolStripStatusSuccessNum.Text = successnumber.ToString();
toolStripStatusErrorNum.Text = errornumber.ToString();
toolStripStatusCreatedNum.Text = creatednumber.ToString();
toolStripStatusUpdatedNum.Text = updatednumber.ToString();
toolStripStatusDeletedNum.Text = deletednumber.ToString();
}
private void CopyText_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (string line in logTextBox.Lines)
sb.AppendLine(line);
if (sb.Length != 0)
Clipboard.SetText(sb.ToString());
else
MessageBox.Show("Logs are empty");
}
#endregion Original Logging
#region New Logging
private void LogToggle_Click(object sender, EventArgs e)
{
if (mainTableLayout.RowStyles[1].Height == 0) // Log sections are hidden
{
LogTableShow();
}
else
{
LogTableHide();
}
}
private void LogTableHide()
{
mainTableLayout.RowStyles[1] = new RowStyle(SizeType.Percent, 0);
LogToggle.Text = "Show Logs";
}
private void LogTableShow()
{
mainTableLayout.RowStyles[1] = new RowStyle(SizeType.Percent, 45);
LogToggle.Text = "Hide Logs";
}
private void RefreshLogs_Click_2(object sender, EventArgs e)
{
SetTextBox1();
dataGridViewLogs.Refresh();
}
private void AddToLogRow(string[] row, string log = null, string GUID = null, string result = null)
{
// 0 = #
// 1 = Line
// 2 = Result
// 3 = Updates
// 4 = GUID
// 5 = Logs
// add the GUID to the cell if GUID is not null
if (GUID != null)
{
if (row[4] == null)
{
row[3] = "1";
row[4] = GUID;
}
else
{
row[3] = (int.Parse(row[3]) + 1).ToString();
row[4] += " " + GUID;
}
}
// Add the logs to the log cell
if (log != null)
{
if (row[5] == null)
{
row[5] = log;
}
else
{
row[5] += " | " + log;
}
}
// If a result is provided, add it to the result cell
if (result == null)
{ return; }
else
{
row[2] = result;
}
}
#endregion New Logging
#endregion Logging
#region Clearing
private void resetButton_Click(object sender, EventArgs e)
{
///CLEAR ALL
xlWorkBook = null;
xlWorkSheet = null;
xlRange = null;
xlApp = null;
settingsEntity.SelectedItem = null;
settingsLookupFoundMultipleRecords.Visible = false;
settingsCrmAction.SelectedIndex = 0;
settingsLookupFoundMultipleRecords.SelectedIndex = 0;
settingsOptionSetValuesOrLabel.SelectedIndex = 0;
settingsKeyFoundMultipleRecords.SelectedIndex = 0;
completeRecords.Checked = false;
settings.Reset();
labelOptionSetValuesOrLabel.Visible = false;
settingsOptionSetValuesOrLabel.Visible = false;
labelLookupFoundMultipleRecords.Visible = false;
mainTableLayout.RowStyles[1] = new RowStyle(SizeType.Percent, 0);
saveSettingsButton.Enabled = false;
loadSettingsButton.Enabled = false;
setInstructionVisibility(true);
settingsPanel.Enabled = false;
dataGridViewMapping.Enabled = false;
EmptyDataGrid();
CRMField.Items.Clear();
}
private void EmptyDataGrid()
{
dataGridViewMapping.Rows.Clear();
dataGridViewMapping.Columns["lkpTargetEntity"].Visible = false;
dataGridViewMapping.Columns["lkpTargetfield"].Visible = false;
dataGridViewMapping.Columns["Truevalue"].Visible = false;
dataGridViewMapping.Columns["Falsevalue"].Visible = false;
dataGridViewMapping.Columns["DefaultValue"].Visible = false;
}
#endregion Clearing
#region Sidebar Options
private void rowStartNum_ValueChanged(object sender, EventArgs e)
{
// Set row end equal to start if start is after end
if (rowEndNum.Value <= rowStartNum.Value) {
rowEndNum.Value = rowStartNum.Value;
}
// Make the minimum equal to the new start
rowEndNum.Minimum = new decimal(new int[] {
(int) rowStartNum.Value,
0,
0,
0
});
}
private void settingsEntity_DropDownClosed(object sender, EventArgs e)
{
if (settingsEntity.SelectedItem != null)
{
settings.Entity = settingsEntity.SelectedItem.ToString();
for (int o = 0; o < dataGridViewMapping.RowCount; o++)
{
DataGridViewComboBoxCell data = dataGridViewMapping.Rows[o].Cells[2] as DataGridViewComboBoxCell;
data.Value = null;
}
ExecuteMethod(InitEntityFields);
}
else if (settingsEntity.Items.Count == 0)
{
ExecuteMethod(InitEntities);
}
}
private void settingsCrmAction_SelectedIndexChanged(object sender, EventArgs e)
{
settings.CrmAction = settingsCrmAction.SelectedItem.ToString();
if (settings.CrmAction == "Create")
{
settingsKeyFoundMultipleRecords.Visible = false;
labelKeyFoundMultipleRecords.Visible = false;
dataGridViewMapping.Columns[1].Visible = false;
if(settings.Entity == "activity" || settings.Entity == "letter" || settings.Entity == "task")
{
completeRecords.Visible = true;
}
else
{
completeRecords.Visible = false;
}
}
else
{
settingsKeyFoundMultipleRecords.Visible = true;
labelKeyFoundMultipleRecords.Visible = true;
dataGridViewMapping.Columns[1].Visible = true;
completeRecords.Visible = false;
}
}
private void settingsKeyFoundMultipleRecords_SelectedIndexChanged(object sender, EventArgs e)
{
settings.KeyFoundMultipleRecords = settingsKeyFoundMultipleRecords.SelectedItem.ToString();
}
private void settingsOptionSetValuesOrLabel_SelectedIndexChanged(object sender, EventArgs e)
{
settings.OptionSetValuesOrLabel = settingsOptionSetValuesOrLabel.SelectedItem.ToString();
}
private void settingsLookupFoundMultipleRecords_SelectedIndexChanged(object sender, EventArgs e)
{
settings.LookupFoundMultipleRecords = settingsLookupFoundMultipleRecords.SelectedItem.ToString();
}
private void settingscompleteRecords_SelectionChanged(object sender, EventArgs e)
{
settings.CompleteRecordsPostAction = completeRecords.Checked;
}
#endregion Sidebar Options
#region Data Grid
private void dataGridViewMapping_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
switch (e.ColumnIndex)
{
// If the user changes the CRM Field, check if it is a lookup and process it
case 2:
foreach (object attribute in resultsaved.Attributes)
{
AttributeMetadata a = (AttributeMetadata)attribute;
if (a.LogicalName.ToString() == dataGridViewMapping.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue.ToString()) //Find the CRM field between the metadata
{
if (a.AttributeType.ToString() == "Lookup" || a.AttributeType.ToString() == "Customer" || a.AttributeType.ToString() == "PartyList" || a.AttributeType.ToString() == "Owner") // check if the CRM field is of type Lookup
{
processLookupEntity(e.RowIndex, a.AttributeType.ToString());
}
else
{
processNonLookupEntity(e.RowIndex, a.AttributeType.ToString());
}
if (a.AttributeType.ToString() == "Boolean")
{
processBoolean(e.RowIndex, a.AttributeType.ToString());
}
if (a.AttributeType.ToString() == "Picklist" || a.AttributeType.ToString() == "State" || a.AttributeType.ToString() == "Status")
{
processChoice(e.RowIndex, a.AttributeType.ToString());
}
}
}
break;
case 4:
dataGridViewMapping.Rows[e.RowIndex].Cells["lkpTargetfield"].Value = null;
processLookupField(e.RowIndex);
break;
}
}
private void processLookupEntity(int row, string dataType)
{
// make the lookup columns visible
dataGridViewMapping.Columns["lkpTargetEntity"].Visible = true;
dataGridViewMapping.Columns["lkpTargetfield"].Visible = true;
labelLookupFoundMultipleRecords.Visible = true;
settingsLookupFoundMultipleRecords.Visible = true;
//Flag row as lookup
lookupscount++;
dataGridViewMapping.Rows[row].Cells["IsLookup"].Value = true;
// Unlock the lookup fields
DataGridViewComboBoxCell data1 = dataGridViewMapping.Rows[row].Cells[4] as DataGridViewComboBoxCell;
data1.ReadOnly = false;
data1.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton;
DataGridViewComboBoxCell data2 = dataGridViewMapping.Rows[row].Cells[5] as DataGridViewComboBoxCell;
data2.ReadOnly = false;
data2.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton;
//Set Data Type
DataGridViewCell data3 = dataGridViewMapping.Rows[row].Cells["DataType"] as DataGridViewCell;
data3.ReadOnly = true;
data3.Style.BackColor = Color.LightGray;
data3.Value = dataType;
}
private void processLookupField(int row)
{
string lkpentityname = Convert.ToString((dataGridViewMapping.Rows[row].Cells[4] as DataGridViewComboBoxCell).FormattedValue.ToString());
InitLookupFields(lkpentityname, row);
}
private void processNonLookupEntity(int row, string dataType)
{
// set is Lookup to false
dataGridViewMapping.Rows[row].Cells["IsLookup"].Value = false;
// Lock the lookup fields
DataGridViewComboBoxCell data1 = dataGridViewMapping.Rows[row].Cells[4] as DataGridViewComboBoxCell;
data1.ReadOnly = true;
data1.Value = null;
data1.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
DataGridViewComboBoxCell data2 = dataGridViewMapping.Rows[row].Cells[5] as DataGridViewComboBoxCell;
data2.ReadOnly = true;
data2.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
data2.Value = null;
//Set Data Type
DataGridViewCell data3 = dataGridViewMapping.Rows[row].Cells["DataType"] as DataGridViewCell;
data3.ReadOnly = true;
data3.Style.BackColor = Color.LightGray;
data3.Value = dataType;
}
private void processBoolean(int row, string dataType)
{
dataGridViewMapping.Columns["Truevalue"].Visible = true;
dataGridViewMapping.Columns["Falsevalue"].Visible = true;
dataGridViewMapping.Columns["DefaultValue"].Visible = true;
DataGridViewCell databooltrue = dataGridViewMapping.Rows[row].Cells["Truevalue"] as DataGridViewCell;
databooltrue.ReadOnly = false;
databooltrue.Style.BackColor = Color.LightGray;
DataGridViewCell databoolfalse = dataGridViewMapping.Rows[row].Cells["Falsevalue"] as DataGridViewCell;
databoolfalse.ReadOnly = false;
databoolfalse.Style.BackColor = Color.LightGray;
DataGridViewCell databooldefault = dataGridViewMapping.Rows[row].Cells["DefaultValue"] as DataGridViewCell;
databooldefault.ReadOnly = false;
databooldefault.Style.BackColor = Color.LightGray;
//Set Data Type
DataGridViewCell data3 = dataGridViewMapping.Rows[row].Cells["DataType"] as DataGridViewCell;
data3.ReadOnly = true;
data3.Style.BackColor = Color.LightGray;
data3.Value = dataType;
//fetch for true and false boolean values
RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = settingsEntity.SelectedItem.ToString(),
LogicalName = Convert.ToString((dataGridViewMapping.Rows[row].Cells[2] as DataGridViewComboBoxCell).FormattedValue.ToString()),
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)Service.Execute(retrieveAttributeRequest);
BooleanAttributeMetadata retrievedBooleanAttributeMetadata = (BooleanAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
string boolTextTrue = retrievedBooleanAttributeMetadata.OptionSet.TrueOption.Label.UserLocalizedLabel.Label;
string boolTextFalse = retrievedBooleanAttributeMetadata.OptionSet.FalseOption.Label.UserLocalizedLabel.Label;
bool boolDefault = retrievedBooleanAttributeMetadata.DefaultValue.Value;
string boolTextDefault;
if (boolDefault)
boolTextDefault = boolTextTrue;
else
boolTextDefault = boolTextFalse;
dataGridViewMapping.Rows[row].Cells["Truevalue"].Value = boolTextTrue;
dataGridViewMapping.Rows[row].Cells["Falsevalue"].Value = boolTextFalse;
dataGridViewMapping.Rows[row].Cells["DefaultValue"].Value = boolTextDefault;
}
private void processChoice(int row, string dataType)
{
labelOptionSetValuesOrLabel.Visible = true;
settingsOptionSetValuesOrLabel.Visible = true;
//Set Data Type
DataGridViewCell data3 = dataGridViewMapping.Rows[row].Cells["DataType"] as DataGridViewCell;
data3.ReadOnly = true;
data3.Style.BackColor = Color.LightGray;
data3.Value = dataType;
}
private void ProcessFields()
{
if (dataGridViewMapping.RowCount == 0)
{
MessageBox.Show("Please BROWSE EXCEL FILE and Pick your entity and fields mapping first.");
return;
}
dataGridViewMapping.CurrentCell = dataGridViewMapping.Rows[0].Cells[0];
string acrmfield;
int dRow;
lookupscount = 0;
for (dRow = 0; dRow < dataGridViewMapping.RowCount; dRow++)
{
string lkpentityname = Convert.ToString((dataGridViewMapping.Rows[dRow].Cells[4] as DataGridViewComboBoxCell).FormattedValue.ToString());
acrmfield = Convert.ToString((dataGridViewMapping.Rows[dRow].Cells[2] as DataGridViewComboBoxCell).FormattedValue.ToString());
if (resultsaved is null)
{ return; }
foreach (object attribute in resultsaved.Attributes)
{
AttributeMetadata a = (AttributeMetadata)attribute;
if (a.LogicalName.ToString() == acrmfield) //Find the CRM field between the metadata
{
if (a.AttributeType.ToString() == "Lookup" || a.AttributeType.ToString() == "Customer" || a.AttributeType.ToString() == "PartyList" || a.AttributeType.ToString() == "Owner") // check if the CRM field is of type Lookup
{
processLookupEntity(dRow, a.AttributeType.ToString());
processLookupField(dRow);
}
else
{
processNonLookupEntity(dRow, a.AttributeType.ToString());
}
if (a.AttributeType.ToString() == "Boolean")
{
processBoolean(dRow, a.AttributeType.ToString());
}
if (a.AttributeType.ToString() == "Picklist" || a.AttributeType.ToString() == "State" || a.AttributeType.ToString() == "Status")
{
processChoice(dRow, a.AttributeType.ToString());
}
}
}
}
IsReadyToImport = true;
importDataButton.Enabled = true;
}
private void ProcessFieldsButton_Click(object sender, EventArgs e)
{
ExecuteMethod(ProcessFields);
}
private void SetMappingTableFromDataGridView()
{
tableMapping.Clear();
foreach (DataGridViewRow row in dataGridViewMapping.Rows)
{
DataRow dRow = tableMapping.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value == null)
{
if (cell.ColumnIndex == 1 || cell.ColumnIndex == 3)
{
dRow[cell.ColumnIndex] = false;
}
else
{
dRow[cell.ColumnIndex] = DBNull.Value;
}
}
else
{
dRow[cell.ColumnIndex] = cell.Value;
}
}
tableMapping.Rows.Add(dRow);
}
SerializableDataTable serializableMappingTable = new SerializableDataTable(tableMapping);
settings.XMLTableMapping = serializableMappingTable;
}
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
if (e.Exception is ArgumentException && e.Context == DataGridViewDataErrorContexts.Commit)
{
DataGridView view = (DataGridView)sender;
DataGridViewComboBoxColumn column = (DataGridViewComboBoxColumn)view.Columns[e.ColumnIndex];
string value = view.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
MessageBox.Show($"Error in column '{column.Name}' at row {e.RowIndex + 1}. Value '{value}' is not valid.");
}
}
#endregion Data Grid
#region Settings
private void saveSettingsButton_Click(object sender, EventArgs e)
{
// Ensure that the mapping table in Settings reflects the current state of the table.
SetMappingTableFromDataGridView();
DialogResult result = saveFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
string fileName = saveFileDialog.FileName;
try
{
if (fileName.Trim() != "")
{
settings.SaveSettingsToXML(fileName);
}
}
catch (IOException ex)
{
MessageBox.Show("Failed to save settings file correctly:" + ex.Message.ToString());
}
}
}
private void loadSettingsButton_Click(object sender, EventArgs e)
{
openFileDialog.Title = "Settings File";
openFileDialog.FileName = "";
openFileDialog.Filter = "XML File|*.xml";
// Set the default directory of the file dialog to be the current working directory / Settings
openFileDialog.InitialDirectory = Path.Combine(Environment.CurrentDirectory);
DialogResult result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
string fileName = openFileDialog.FileName;
try
{
if (fileName.Trim() != "")
{
settings.LoadSettingsFromXML(fileName);
settingsEntity.SelectedItem = settings.Entity;
InitEntityFields();
settingsCrmAction.SelectedItem = settings.CrmAction;
settingsKeyFoundMultipleRecords.SelectedItem = settings.KeyFoundMultipleRecords;
settingsLookupFoundMultipleRecords.SelectedItem = settings.LookupFoundMultipleRecords;
settingsOptionSetValuesOrLabel.SelectedItem = settings.OptionSetValuesOrLabel;
completeRecords.Checked = settings.CompleteRecordsPostAction;
dataGridViewMapping.Rows.Clear();
// Add rows
foreach (DataRow row in settings.XMLTableMapping.Table.Rows)
{
int rowIndex = dataGridViewMapping.Rows.Add(row.ItemArray);
foreach (DataGridViewColumn col in dataGridViewMapping.Columns)
{
if (col is DataGridViewComboBoxColumn)
{
DataGridViewComboBoxColumn comboCol = col as DataGridViewComboBoxColumn;
if (!comboCol.Items.Contains(dataGridViewMapping.Rows[rowIndex].Cells[col.Index].Value))
{
comboCol.Items.Add(dataGridViewMapping.Rows[rowIndex].Cells[col.Index].Value);
}
}
}
}
}
}
catch (IOException ex)
{
MessageBox.Show("Failed to load Settings file correctly:" + ex.Message.ToString());
}
}
}
#endregion Settings
#region Import
private void ImportDataButton_Click(object sender, EventArgs e)
{
if (dataGridViewMapping.RowCount == 0)
{
MessageBox.Show("Please choose an Excel file to import, pick your target entity and field mapping before Importing to CRM.");
return;
}
dataGridViewMapping.CurrentCell = dataGridViewMapping.Rows[0].Cells[0];
if (settingsCrmAction.SelectedIndex != 1)
{
bool wehavekey = false;
foreach (DataGridViewRow dataGridRow in dataGridViewMapping.Rows)
{