-
Notifications
You must be signed in to change notification settings - Fork 8
/
AutoNumMgr.cs
947 lines (874 loc) · 37.8 KB
/
AutoNumMgr.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
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
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using XrmToolBox.Extensibility;
using XrmToolBox.Extensibility.Args;
using XrmToolBox.Extensibility.Interfaces;
namespace Rappen.XTB.AutoNumManager
{
public partial class AutoNumMgr : PluginControlBase, IStatusBarMessenger, IMessageBusHost, IGitHubPlugin, IPayPalPlugin, IHelpPlugin, IAboutPlugin
{
#region Private Fields
private const string aiEndpoint = "https://dc.services.visualstudio.com/v2/track";
//private const string aiKey = "cc7cb081-b489-421d-bb61-2ee53495c336"; // [email protected] tenant, TestAI
private const string aiKey1 = "eed73022-2444-45fd-928b-5eebd8fa46a6"; // [email protected] tenant, XrmToolBox
private const string aiKey2 = "d46e9c12-ee8b-4b28-9643-dae62ae7d3d4"; // [email protected], XrmToolBoxTools
private readonly AppInsights ai1;
private readonly AppInsights ai2;
private List<EntityMetadataProxy> entities;
private Settings settings;
#endregion Private Fields
#region Public Constructors
public AutoNumMgr()
{
InitializeComponent();
ai1 = new AppInsights(aiEndpoint, aiKey1, Assembly.GetExecutingAssembly(), "Auto Number Manager");
ai2 = new AppInsights(aiEndpoint, aiKey2, Assembly.GetExecutingAssembly(), "Auto Number Manager");
}
#endregion Public Constructors
#region Public Events
public event EventHandler<MessageBusEventArgs> OnOutgoingMessage;
public event EventHandler<StatusBarMessageEventArgs> SendMessageToStatusBar;
#endregion Public Events
#region Public Properties
public string DonationDescription
{ get { return "Auto Number Manager Fan Club"; } }
public string EmailAccount
{ get { return "[email protected]"; } }
public string HelpUrl
{ get { return "https://jonasr.app/ANM"; } }
public string RepositoryName
{ get { return "AutoNumManager"; } }
public string UserName
{ get { return "Rappen"; } }
#endregion Public Properties
#region Public Methods
public override void ClosingPlugin(PluginCloseInfo info)
{
SettingsManager.Instance.Save(GetType(), settings);
LogUse("Close", true);
base.ClosingPlugin(info);
}
public void OnIncomingMessage(MessageBusEventArgs message)
{
// This plugin does not accept incoming messages
}
public void ShowAboutDialog()
{
tslAbout_Click(null, null);
}
#endregion Public Methods
#region Form Event Handlers
private void AutoNumMgr_ConnectionUpdated(object sender, ConnectionUpdatedEventArgs e)
{
LogInfo("Connection has changed to: {0}", e.ConnectionDetail.WebApplicationUrl);
gbAttribute.Enabled = false;
tsbFXB.Enabled = false;
cmbSolution.Enabled = false;
cmbEntities.Enabled = false;
rbShowAttributesOnlyNumber.Enabled = false;
rbShowAttributesAllString.Enabled = false;
entities = new List<EntityMetadataProxy>();
var orgver = new Version(e.ConnectionDetail.OrganizationVersion);
LogInfo("Connected CRM version: {0}", orgver);
var orgok = orgver >= new Version(9, 0);
if (orgok)
{
LoadSolutions();
LoadEntities();
LoadUserSettings();
}
else
{
LogError("CRM version too old for Auto Number Manager");
LogUse("IncompatibleCRM");
MessageBox.Show($"Auto Number feature was introduced in\nMicrosoft Dynamics 365 July 2017 (9.0)\nCurrent version is {orgver}\n\nPlease connect to a newer organization to use this cool tool.",
"Organization too old", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void AutoNumMgr_Load(object sender, EventArgs e)
{
if (settings == null)
{
LoadSettings();
}
LogUse("Load", true);
}
private void btnCreateUpdate_Click(object sender, EventArgs e)
{
var seed = txtSeed.Enabled ? txtSeed.Text.Trim() : string.Empty;
var format = txtNumberFormat.Text.Trim();
var message = "Creating auto number attribute.";
var log = "Create";
if (!txtLogicalName.Enabled)
{
log = "Update";
var attribute = gridAttributes.SelectedRows[0].DataBoundItem as AttributeProxy;
if (string.IsNullOrEmpty(attribute.Format) && !string.IsNullOrEmpty(format))
{ // Numbering a previously not numbered attribute
message = "Adding auto number format to an existing attribute will make this field read-only on all forms.\nNumber will be assigned instead.";
log = "ConvertToNumbered";
}
else if (!string.IsNullOrEmpty(attribute.Format) && string.IsNullOrWhiteSpace(format))
{ // Removing numbering from an attribute
message = "This will remove auto numbering from the attribute.\nAttribute will now be editable by users.";
log = "ConvertFromNumbered";
}
else if (!attribute.Format.Trim().Equals(format))
{ // Changing the number format
message = $"Auto Number format will be changed from\n {attribute.Format}\nto\n {format}";
}
else
{ // Format is not changed
if (!string.IsNullOrWhiteSpace(seed))
{
if (!format.Contains("{SEQNUM:"))
{ // Setting seed on attribute without numbering
message = "Setting seed for attribute without auto numbering sequence does not make sense.";
}
else
{ // Updating seed for existing numbering
message = $"Setting seed to: {seed}";
}
}
else
{
message = "Update seems totally irrelevant...";
}
}
}
if (DialogResult.OK != MessageBox.Show($"{message}\n\nPlease confirm!", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
{
return;
}
LogUse(log);
WriteAttribute(!txtLogicalName.Enabled);
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (DialogResult.OK != MessageBox.Show($"This will delete the attribute.\nAny data in existing records WILL be lost.\nThis is a one way ticket with no refund!\nDo you really want to delete attribute {lblPrefix.Text + txtLogicalName.Text}?", "Confirm delete", MessageBoxButtons.OKCancel))
{
return;
}
DeleteAttribute();
}
private void btnGuessSeed_Click(object sender, EventArgs e)
{
try
{
var seed = GuessSeed();
MessageBox.Show($"Parsed existing value as:\n {seed}.", "Guess current SEQNUM", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Guess current SEQNUM", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void btnNew_Click(object sender, EventArgs e)
{
lblPrefix.Text = (cmbSolution.SelectedItem as SolutionProxy)?.Prefix;
txtLogicalName.Enabled = true;
txtLogicalName.Text = string.Empty;
txtDisplayName.Text = string.Empty;
txtDescription.Text = string.Empty;
txtMaxLen.Text = "100";
txtNumberFormat.Text = "{SEQNUM:5}";
txtSeed.Text = "1";
NumberConditionsChanged();
btnCreateUpdate.Text = "Create";
btnDelete.Enabled = false;
gbAttribute.Enabled = true;
}
private void chkAllowNoSeqNo_CheckedChanged(object sender, EventArgs e)
{
NumberConditionsChanged();
}
private void cmbEntities_SelectedIndexChanged(object sender, EventArgs e)
{
var entityselected = cmbEntities.SelectedItem is EntityMetadataProxy;
gridAttributes.Enabled = false;
gbAttribute.Enabled = false;
rbShowAttributesOnlyNumber.Enabled = entityselected;
rbShowAttributesAllString.Enabled = entityselected;
tsbFXB.Enabled = entityselected;
btnNew.Enabled = entityselected;
LoadAttributes(false);
}
private void cmbSolution_SelectedIndexChanged(object sender, EventArgs e)
{
FilterEntities();
cmbEntities.Enabled = true;
rbShowAttributesOnlyNumber.Enabled = false;
rbShowAttributesAllString.Enabled = false;
tsbFXB.Enabled = false;
gridAttributes.Enabled = false;
gbAttribute.Enabled = false;
gridAttributes.DataSource = null;
}
private void gridAttributes_SelectionChanged(object sender, EventArgs e)
{
txtHint.Text = string.Empty;
var grid = sender as DataGridView;
if (grid?.SelectedRows?.Count == 0)
{
gbAttribute.Enabled = false;
return;
}
var row = grid.SelectedRows[0];
var attribute = row.DataBoundItem as AttributeProxy;
if (attribute == null)
{
gbAttribute.Enabled = false;
return;
}
var logical = attribute.LogicalName;
if (logical.Contains("_"))
{
lblPrefix.Text = logical.Split('_')[0] + "_";
txtLogicalName.Text = logical.Substring(logical.IndexOf("_") + 1);
}
else
{
lblPrefix.Text = "";
txtLogicalName.Text = logical;
}
txtDisplayName.Text = attribute.attributeMetadata.DisplayName?.UserLocalizedLabel?.Label;
txtDescription.Text = attribute.attributeMetadata.Description?.UserLocalizedLabel?.Label;
txtMaxLen.Text = attribute.attributeMetadata.MaxLength?.ToString();
txtNumberFormat.Text = attribute.attributeMetadata.AutoNumberFormat;
txtSeed.Text = string.Empty;
NumberConditionsChanged();
txtLogicalName.Enabled = false;
btnCreateUpdate.Text = "Update";
btnDelete.Enabled = attribute.attributeMetadata.IsPrimaryName.Value != true;
gbAttribute.Enabled = true;
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("https://jonasrapp.net/2017/10/anm/");
}
private void llDocs_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/create-auto-number-attributes");
}
private void llDatetime_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
AddMacro("{DATETIMEUTC:yyyyMMddhhmmss}");
}
private void llRandom_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
AddMacro("{RANDSTRING:4}");
}
private void llSeqnum_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
AddMacro("{SEQNUM:5}");
}
private void rbShowAttributes_CheckedChanged(object sender, EventArgs e)
{
LoadAttributes(false);
}
private void tslAbout_Click(object sender, EventArgs e)
{
LogUse("OpenAbout");
var about = new About(this);
about.StartPosition = FormStartPosition.CenterParent;
about.lblVersion.Text = Assembly.GetExecutingAssembly().GetName().Version.ToString();
about.ShowDialog();
}
private void tsbClose_Click(object sender, EventArgs e)
{
CloseTool();
}
private void tsbFXB_Click(object sender, EventArgs e)
{
OpenFXB();
}
private void txtLanguageId_TextChanged(object sender, EventArgs e)
{
txtHint.Text = string.Empty;
if (!int.TryParse(txtLanguageId.Text, out int max))
{
txtHint.Text = $"Language Id '{txtLanguageId.Text}' is not a valid number.";
return;
}
}
private void txtMaxLen_TextChanged(object sender, EventArgs e)
{
NumberConditionsChanged();
}
private void txtNumberFormat_TextChanged(object sender, EventArgs e)
{
NumberConditionsChanged();
}
private void txtSeed_TextChanged(object sender, EventArgs e)
{
NumberConditionsChanged();
}
#endregion Form Event Handlers
#region My Methods
internal void LogUse(string action, bool ai2 = false)
{
ai1.WriteEvent(action);
if (ai2)
{
this.ai2.WriteEvent(action);
}
}
internal void UpdateUI(Action action)
{
MethodInvoker mi = delegate
{
action();
};
if (InvokeRequired)
{
Invoke(mi);
}
else
{
mi();
}
}
private void AddMacro(string macro)
{
var selstart = txtNumberFormat.SelectionStart;
var seloffset = macro.IndexOf(':') + 1;
var sellen = macro.IndexOf('}') - seloffset;
txtNumberFormat.SelectedText = "";
txtNumberFormat.Text = txtNumberFormat.Text.Insert(selstart, macro);
txtNumberFormat.SelectionStart = selstart + seloffset;
txtNumberFormat.SelectionLength = sellen;
txtNumberFormat.Focus();
}
private void DeleteAttribute()
{
var entityname = ((EntityMetadataProxy)cmbEntities.SelectedItem).Metadata.LogicalName;
var attributename = lblPrefix.Text + txtLogicalName.Text;
var req = new DeleteAttributeRequest
{
EntityLogicalName = entityname,
LogicalName = attributename
};
WorkAsync(new WorkAsyncInfo("Deleting attribute...",
(eventargs) =>
{
LogUse("Delete");
Service.Execute(req);
})
{
PostWorkCallBack = (completedargs) =>
{
if (completedargs.Error != null)
{
MessageBox.Show($"Delete attribute failed:\n{completedargs.Error}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Attribute deleted!");
}
UpdateUI(ForceLoadAttributes);
}
});
}
private void EnableControls(bool enabled)
{
//Enabled = enabled;
}
private void FilterEntities()
{
cmbEntities.Items.Clear();
btnNew.Enabled = false;
var solution = cmbSolution.SelectedItem as SolutionProxy;
if (solution == null)
{
return;
}
lblPrefix.Text = solution.Prefix;
WorkAsync(new WorkAsyncInfo("Filtering entities...",
(eventargs) =>
{
EnableControls(false);
var qx = new QueryExpression("solutioncomponent");
qx.ColumnSet.AddColumns("objectid");
qx.Criteria.AddCondition("componenttype", ConditionOperator.Equal, 1);
qx.Criteria.AddCondition("solutionid", ConditionOperator.Equal, solution.Solution.Id);
eventargs.Result = Service.RetrieveMultiple(qx);
})
{
PostWorkCallBack = (completedargs) =>
{
if (completedargs.Error != null)
{
MessageBox.Show(completedargs.Error.Message);
}
else
{
if (completedargs.Result is EntityCollection)
{
var includedentities = (EntityCollection)completedargs.Result;
var filteredentities = entities.Where(e => includedentities.Entities.Select(i => i["objectid"]).Contains(e.Metadata.MetadataId));
cmbEntities.Items.AddRange(filteredentities.ToArray());
}
}
EnableControls(true);
}
});
}
private void ForceLoadAttributes()
{
LoadAttributes(true);
}
private int GuessSeed()
{
LogUse("GuessSeed");
var format = txtNumberFormat.Text;
var sample = ParseNumberFormat(format, "9999999999");
if (!format.Contains("{SEQNUM:") || !format.Contains("}"))
{
throw new FormatException("Format string must contain a {SEQNUM:n} placeholder.");
}
var seqstart = sample.IndexOf("9999999999");
var lenghtstr = format.Split(new string[] { "{SEQNUM:" }, StringSplitOptions.None)[1];
lenghtstr = lenghtstr.Split('}')[0];
var length = 0;
if (int.TryParse(lenghtstr, out length))
{
if (length < 1)
{
throw new FormatException("Failed to parse SEQNUM length.");
}
}
var entity = ((EntityMetadataProxy)cmbEntities.SelectedItem).Metadata;
var attributename = lblPrefix.Text + txtLogicalName.Text;
var fetchxml = "<fetch top='1' ><entity name='" + entity.LogicalName + "' >" +
"<attribute name='" + attributename + "' />" +
"<filter><condition attribute='" + attributename + "' operator='not-null' /></filter>" +
"<order attribute='createdon' descending='true' /></entity></fetch>";
var lastrecord = Service.RetrieveMultiple(new FetchExpression(fetchxml)).Entities.FirstOrDefault();
var result = 0;
if (lastrecord == null)
{
throw new Exception("No numbered data found for attribute " + attributename);
}
var lastvalue = lastrecord[attributename].ToString();
if (lastvalue.Length >= seqstart + length)
{
var lastseqstr = lastvalue.Substring(seqstart, length);
if (int.TryParse(lastseqstr, out int lastseq))
{
LogUse("GuessSeed succeeded");
result = lastseq;
}
}
if (result == 0)
{
LogUse("GuessSeed failed");
throw new Exception("That was hard. Couldn't even guess what current SEQNUM is.\n" +
"Numbered value for last created record is: \n" + lastvalue);
}
return result;
}
private void LoadAttributes(bool force)
{
gridAttributes.DataSource = null;
var entity = cmbEntities.SelectedItem as EntityMetadataProxy;
var onlyNumbered = rbShowAttributesOnlyNumber.Checked;
WorkAsync(new WorkAsyncInfo("Loading auto number attributes...",
(eventargs) =>
{
if (force || entity.Metadata.Attributes == null)
{
eventargs.Result = MetadataHelper.LoadEntityDetails(Service, entity.Metadata.LogicalName).EntityMetadata.FirstOrDefault();
}
else
{
eventargs.Result = entity.Metadata;
}
})
{
PostWorkCallBack = (completedargs) =>
{
if (completedargs.Result is EntityMetadata)
{
try
{
entity.Metadata = (EntityMetadata)completedargs.Result;
var attributes = entity.Metadata.Attributes
.Where(a => a.AttributeType == AttributeTypeCode.String &&
a.IsValidForCreate.Value == true &&
a.IsCustomizable.Value == true &&
(!onlyNumbered || !string.IsNullOrEmpty(a.AutoNumberFormat)))
.Select(a => new AttributeProxy((StringAttributeMetadata)a)).OrderBy(a => a.LogicalName).ToList();
var bindingList = new BindingList<AttributeProxy>(attributes);
var source = new BindingSource(bindingList, null);
UpdateUI(() =>
{
gridAttributes.DataSource = source;
gridAttributes.Enabled = true;
gridAttributes.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
});
}
catch (MissingMethodException mex)
{
LogUse("IncompatibleSDK");
MessageBox.Show("It seems you are using too old SDK, that is unaware of the AutoNumberFormat property.", "SDK error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
});
}
private void LoadEntities()
{
entities = new List<EntityMetadataProxy>();
WorkAsync(new WorkAsyncInfo("Loading entities...",
(eventargs) =>
{
EnableControls(false);
eventargs.Result = MetadataHelper.LoadEntities(Service);
})
{
PostWorkCallBack = (completedargs) =>
{
if (completedargs.Error != null)
{
MessageBox.Show(completedargs.Error.Message);
}
else
{
if (completedargs.Result is RetrieveMetadataChangesResponse)
{
var metaresponse = ((RetrieveMetadataChangesResponse)completedargs.Result).EntityMetadata;
entities.AddRange(metaresponse
.Where(e => e.IsCustomizable.Value == true && e.IsIntersect.Value != true)
.Select(m => new EntityMetadataProxy(m))
.OrderBy(e => e.ToString()));
}
}
EnableControls(true);
}
});
}
private void LoadSolutions()
{
cmbSolution.Items.Clear();
cmbSolution.Enabled = false;
WorkAsync(new WorkAsyncInfo("Loading solutions...",
(eventargs) =>
{
EnableControls(false);
var qx = new QueryExpression("solution");
qx.ColumnSet.AddColumns("friendlyname", "uniquename");
qx.AddOrder("installedon", OrderType.Ascending);
qx.Criteria.AddCondition("ismanaged", ConditionOperator.Equal, false);
qx.Criteria.AddCondition("isvisible", ConditionOperator.Equal, true);
var lePub = qx.AddLink("publisher", "publisherid", "publisherid");
lePub.EntityAlias = "P";
lePub.Columns.AddColumns("customizationprefix");
eventargs.Result = Service.RetrieveMultiple(qx);
})
{
PostWorkCallBack = (completedargs) =>
{
if (completedargs.Error != null)
{
MessageBox.Show(completedargs.Error.Message);
}
else
{
if (completedargs.Result is EntityCollection)
{
var solutions = (EntityCollection)completedargs.Result;
var proxiedsolutions = solutions.Entities.Select(s => new SolutionProxy(s)).OrderBy(s => s.ToString());
cmbSolution.Items.AddRange(proxiedsolutions.ToArray());
cmbSolution.Enabled = true;
}
}
EnableControls(true);
}
});
}
private void LoadUserSettings()
{
var qx = new QueryExpression("usersettings");
qx.ColumnSet.AddColumns("uilanguageid", "localeid");
qx.Criteria.AddCondition("systemuserid", ConditionOperator.EqualUserId);
var result = Service.RetrieveMultiple(qx);
if (result.Entities.Count > 0)
{
txtLanguageId.Text = result.Entities[0]["uilanguageid"].ToString();
}
}
private void LoadSettings()
{
// Loads or creates the settings for the plugin
if (!SettingsManager.Instance.TryLoad(GetType(), out settings))
{
settings = new Settings();
LogWarning("Settings not found => created");
}
else
{
LogInfo("Settings found and loaded");
}
var ass = Assembly.GetExecutingAssembly().GetName();
var version = ass.Version.ToString();
settings.Version = version;
}
private void NumberConditionsChanged()
{
txtHint.Text = string.Empty;
var seed = txtSeed.Enabled ? txtSeed.Text.Trim() : string.Empty;
if (!string.IsNullOrEmpty(seed) && !Int64.TryParse(seed, out Int64 max))
{
txtHint.Text = $"Seed '{seed}' is not a valid number.";
return;
}
if (!int.TryParse(txtMaxLen.Text, out int maxlen))
{
txtHint.Text = $"Max Length '{txtMaxLen.Text}' is not a valid number.";
return;
}
txtSample.Text = ParseNumberFormat(txtNumberFormat.Text, seed);
if (txtSample.Text.Length > maxlen)
{
txtHint.Text = "It looks like the maximum length of the attribute will be exceeded.\n\rCorrect this before saving the attribute.";
}
}
private void OpenFXB()
{
var entity = ((EntityMetadataProxy)cmbEntities.SelectedItem).Metadata;
var attributes = ((gridAttributes.DataSource as BindingSource)?.DataSource as BindingList<AttributeProxy>).Select(a => a.attributeMetadata.LogicalName);
var fetchxml = "<fetch top='10' ><entity name='" + entity.LogicalName + "' >" +
"<attribute name='" + entity.PrimaryNameAttribute + "' /><attribute name='createdon' />" +
string.Join("", attributes.Select(a => "<attribute name='" + a + "' />")) +
"<order attribute='createdon' descending='true' /></entity></fetch>";
var messageBusEventArgs = new MessageBusEventArgs("FetchXML Builder")
{
TargetArgument = fetchxml
};
OnOutgoingMessage(this, messageBusEventArgs);
}
private string ParseFormatDATETIMEUTC(string format)
{
while (format.Contains("{DATETIMEUTC:") && format.Contains("}"))
{
var formatstr = format.Split(new string[] { "{DATETIMEUTC:" }, StringSplitOptions.None)[1];
formatstr = formatstr.Split('}')[0];
var datestr = DateTime.Now.ToString(formatstr);
format = format.Replace("{DATETIMEUTC:" + formatstr + "}", datestr);
}
return format;
}
private string ParseFormatRANDSTRING(string format)
{
while (format.Contains("{RANDSTRING:") && format.Contains("}"))
{
var lenghtstr = format.Split(new string[] { "{RANDSTRING:" }, StringSplitOptions.None)[1];
lenghtstr = lenghtstr.Split('}')[0];
if (int.TryParse(lenghtstr, out int length))
{
if (length < 1 || length > 6)
{
throw new FormatException("RANDSTRING length must be between 1 and 6");
}
var randomstring = "X7C7D8EK3MR2L4".Substring(0, length);
format = format.Replace("{RANDSTRING:" + lenghtstr + "}", randomstring);
}
else
{
throw new FormatException("Invalid RANDSTRING format. Enter as {RANDSTRING:n} where n is length of sequence.");
}
}
return format;
}
private string ParseFormatSEQNUM(string format, string seed)
{
var validseqnum = false;
try
{
if (!format.Contains("{SEQNUM:") || !format.Contains("}"))
{
if (!chkAllowNoSeqNo.Checked)
{
throw new FormatException("Format string must contain a {SEQNUM:n} placeholder.");
}
else
{
return format;
}
}
var lenghtstr = format.Split(new string[] { "{SEQNUM:" }, StringSplitOptions.None)[1];
lenghtstr = lenghtstr.Split('}')[0];
if (int.TryParse(lenghtstr, out int length))
{
if (length < 1)
{
throw new FormatException("SEQNUM length must be 1 or higher.");
}
var seedno = string.IsNullOrEmpty(seed) ? 1 : Int64.Parse(seed);
var sequence = string.Format("{0:" + new string('0', length) + "}", seedno);
format = format.Replace("{SEQNUM:" + lenghtstr + "}", sequence);
validseqnum = true;
}
else
{
throw new FormatException("Invalid SEQNUM format. Enter as {SEQNUM:n} where n is length of sequence.");
}
if (format.Contains("{SEQNUM:"))
{
throw new FormatException("Format string must only contain one {SEQNUM:n} placeholder.");
}
}
finally
{
txtSeed.Enabled = validseqnum;
btnGuessSeed.Enabled = validseqnum && !txtLogicalName.Enabled;
}
return format;
}
private string ParseNumberFormat(string format, string seed)
{
txtHint.Text = string.Empty;
if (!string.IsNullOrWhiteSpace(format))
{
try
{
format = ParseFormatSEQNUM(format, seed);
format = ParseFormatRANDSTRING(format);
format = ParseFormatDATETIMEUTC(format);
txtHint.Text = "Format successfully parsed.";
btnCreateUpdate.Enabled = true;
}
catch (Exception ex)
{
txtHint.Text = ex.Message;
format = string.Empty;
btnCreateUpdate.Enabled = false;
}
}
return format;
}
private void WriteAttribute(bool update)
{
var langid = int.Parse(txtLanguageId.Text.Trim());
var solutionname = (cmbSolution.SelectedItem as SolutionProxy)?.UniqueName;
var entity = ((EntityMetadataProxy)cmbEntities.SelectedItem).Metadata;
var existingattribute = update ? (gridAttributes.SelectedRows[0].DataBoundItem as AttributeProxy).attributeMetadata : null;
var logicalname = lblPrefix.Text + txtLogicalName.Text.Trim();
var schemaname = update ? (gridAttributes.SelectedRows[0].DataBoundItem as AttributeProxy).attributeMetadata.SchemaName : logicalname;
var format = txtNumberFormat.Text.Trim();
if (!string.IsNullOrEmpty(format))
{
try
{
var seqnum = ParseFormatSEQNUM(format, string.Empty);
if (format.Equals(seqnum))
{
if (DialogResult.Cancel == MessageBox.Show("Creating number formats without SEQNUM placeholder can result in non-unique values.\n\nPlease confirm!", "No sequence number", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning))
{
return;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
var maxlen = int.Parse(txtMaxLen.Text.Trim());
var seed = txtSeed.Enabled ? txtSeed.Text.Trim() : string.Empty;
OrganizationRequest req = null;
if (update)
{
if (existingattribute.AutoNumberFormat != format ||
existingattribute.MaxLength != maxlen ||
existingattribute.DisplayName.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == langid)?.Label != txtDisplayName.Text ||
existingattribute.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == langid)?.Label != txtDescription.Text)
{
var attribute = ((RetrieveAttributeResponse)Service.Execute(new RetrieveAttributeRequest
{
EntityLogicalName = entity.LogicalName,
LogicalName = logicalname,
RetrieveAsIfPublished = true
})).AttributeMetadata;
attribute.AutoNumberFormat = format;
req = new UpdateAttributeRequest
{
EntityName = entity.LogicalName,
Attribute = attribute,
SolutionUniqueName = solutionname
};
}
if (!string.IsNullOrEmpty(seed))
{
if (DialogResult.Yes != MessageBox.Show("Setting the seed for an existing attribute MAY result in duplicate data!\nDo you really want to change the seed?", "Confirm seed", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation))
{
return;
}
}
}
else
{
var attribute = new StringAttributeMetadata
{
AutoNumberFormat = format,
LogicalName = logicalname,
SchemaName = schemaname,
MaxLength = maxlen,
DisplayName = new Microsoft.Xrm.Sdk.Label(txtDisplayName.Text, langid),
Description = new Microsoft.Xrm.Sdk.Label(txtDescription.Text, langid),
RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None)
};
req = new CreateAttributeRequest
{
EntityName = entity.LogicalName,
Attribute = attribute,
SolutionUniqueName = solutionname
};
}
WorkAsync(new WorkAsyncInfo("Saving attribute...",
(eventargs) =>
{
if (req != null)
{
Service.Execute(req);
}
if (!string.IsNullOrEmpty(seed))
{
LogUse("SetSeed");
Service.Execute(new SetAutoNumberSeedRequest
{
EntityName = entity.LogicalName,
AttributeName = logicalname,
Value = Int64.Parse(seed)
});
}
})
{
PostWorkCallBack = (completedargs) =>
{
if (completedargs.Error != null)
{
MessageBox.Show($"Save attribute failed:\n{completedargs.Error}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Attribute saved!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
UpdateUI(ForceLoadAttributes);
}
});
}
#endregion My Methods
}
}