-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBusinessRulesScriptViewer.cs
426 lines (342 loc) · 15.2 KB
/
BusinessRulesScriptViewer.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
using McTools.Xrm.Connection;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Configuration;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Logging;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Sdmsols.XTB.BusinessRulesScriptViewer.Helpers;
using XrmToolBox.Extensibility;
using XrmToolBox.Extensibility.Args;
using XrmToolBox.Extensibility.Interfaces;
namespace Sdmsols.XTB.BusinessRulesScriptViewer
{
public partial class BusinessRulesScriptViewer : PluginControlBase,IGitHubPlugin, IPayPalPlugin, IMessageBusHost, IHelpPlugin, IStatusBarMessenger, IAboutPlugin
{
#region Constructor and Class Variables
private Settings _mySettings;
private List<EntityMetadataProxy> _entities;
private EntityMetadataProxy _selectedEntity;
public event EventHandler<MessageBusEventArgs> OnOutgoingMessage;
public event EventHandler<StatusBarMessageEventArgs> SendMessageToStatusBar;
public BusinessRulesScriptViewer()
{
InitializeComponent();
}
#endregion Constructor and Class Variables
#region XrmToolBox Plug In Methods
private void BusinessRulesScriptViewer_Load(object sender, EventArgs e)
{
// ShowInfoNotification("This is a notification that can lead to XrmToolBox repository", new Uri("https://github.com/MscrmTools/XrmToolBox"));
// Loads or creates the settings for the plugin
if (!SettingsManager.Instance.TryLoad(GetType(), out _mySettings))
{
_mySettings = new Settings();
LogWarning("Settings not found => a new settings file has been created!");
}
else
{
LogInfo("Settings found and loaded");
}
}
private void tsbClose_Click(object sender, EventArgs e)
{
CloseTool();
}
/// <summary>
/// This event occurs when the connection has been updated in XrmToolBox
/// </summary>
public override void UpdateConnection(IOrganizationService newService, ConnectionDetail detail, string actionName, object parameter)
{
base.UpdateConnection(newService, detail, actionName, parameter);
if (_mySettings != null && detail != null)
{
_mySettings.LastUsedOrganizationWebappUrl = detail.WebApplicationUrl;
LogInfo("Connection has changed to: {0}", detail.WebApplicationUrl);
}
}
private void BusinessRulesScriptViewer_ConnectionUpdated(object sender, ConnectionUpdatedEventArgs e)
{
var orgver = new Version(e.ConnectionDetail.OrganizationVersion);
var orgok = orgver >= new Version(6, 0);
if (orgok)
{
LoadSolutions();
LoadEntities();
}
else
{
LogError("CRM version too old for Auto Number Manager");
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);
}
}
/// <summary>
/// This event occurs when the plugin is closed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BusinessRulesScriptViewer_OnCloseTool(object sender, System.EventArgs e)
{
// Before leaving, save the settings
SettingsManager.Instance.Save(GetType(), _mySettings);
}
#endregion XrmToolBox Plug In Methods
#region Control Events
private void cmbSolution_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbSolution.SelectedItem != null)
{
FilterEntities();
}
}
#endregion Control Events
#region Private Helper Methods
private void LoadSolutions()
{
cmbSolution.Items.Clear();
cmbSolution.Enabled = false;
WorkAsync(new WorkAsyncInfo("Loading solutions...",
(eventargs) =>
{
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;
}
}
}
});
}
private void LoadEntities()
{
_entities = new List<EntityMetadataProxy>();
WorkAsync(new WorkAsyncInfo("Loading entities...",
(eventargs) => { 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()));
}
}
}
});
}
private void FilterEntities()
{
cmbEntities.Items.Clear();
cmbEntities.Enabled = false;
var solution = cmbSolution.SelectedItem as SolutionProxy;
if (solution == null)
{
return;
}
WorkAsync(new WorkAsyncInfo("Filtering entities...",
(eventargs) =>
{
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());
}
}
cmbEntities.Enabled = true;
}
});
}
private void LoadBusinessRules()
{
WorkAsync(new WorkAsyncInfo("Loading BusinessRules...",
(eventargs) =>
{
var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> " +
" <entity name='workflow' > " +
" <attribute name='workflowid' /> " +
" <attribute name='name' /> " +
" <attribute name='category' /> " +
" <attribute name='clientdata' /> " +
" <attribute name='primaryentity' /> " +
" <attribute name='statecode' /> " +
" <attribute name='createdon' /> " +
" <attribute name='ownerid' /> " +
" <attribute name='owningbusinessunit' /> " +
" <attribute name='type' /> " +
" <order attribute='name' descending='false' /> " +
" <filter type='and'> " +
" <condition attribute='primaryentity' operator='eq' value='" + _selectedEntity.EntityTypeCode + "' /> " +
" <condition attribute='category' operator='eq' value='2' /> "+
" </filter> "+
" </entity> " +
"</fetch>";
eventargs.Result = Service.RetrieveMultiple(new FetchExpression(fetchXml));
})
{
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 BusinessRuleProxy(s))
.OrderBy(s => s.ToString()).ToList();
AddItemToChekListBox(proxiedsolutions);
}
}
}
});
}
protected void AddItemToChekListBox(List<BusinessRuleProxy> collection)
{
tvBusinessRule.Invoke((System.Windows.Forms.MethodInvoker)delegate ()
{
tvBusinessRule.Nodes.Clear();
foreach (var userView in collection)
{
tvBusinessRule.Nodes.Add(new BusinessRuleTreeNode(userView));
}
});
}
#endregion Private Helper Methods
#region Logging And ProgressBar Methods
delegate void SetStatusTextCallback(string text);
delegate void AddProgressStepCallback();
#endregion Logging And ProgressBar Methods
#region Interface Members
public void OnIncomingMessage(MessageBusEventArgs message)
{
//throw new NotImplementedException();
}
public string RepositoryName => "BusinessRulesScriptViewer";
public string UserName => "contactmayankp";
public string DonationDescription => "Auto Number Updater";
public string EmailAccount => "[email protected]";
public string HelpUrl => "https://mayankp.wordpress.com/2021/12/24/xrmtoolbox-new-tool-businessrulesscriptviewer/";
#endregion
public void ShowAboutDialog()
{
// throw new NotImplementedException();
}
private void tslAbout_Click(object sender, EventArgs e)
{
Process.Start(HelpUrl);
}
private void cmbEntities_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbEntities.SelectedItem != null)
{
_selectedEntity = (EntityMetadataProxy)cmbEntities.SelectedItem;
LoadBusinessRules();
}
}
private void tvBusinessRule_AfterSelect(object sender, TreeViewEventArgs e)
{
var myNode = (BusinessRuleTreeNode)e.Node;
rtBRScript.Text = myNode.BusinessRuleProxy.ClientCode;
}
private void btnSaveSelected_Click(object sender, EventArgs e)
{
if (tvBusinessRule.SelectedNode != null)
{
string path = SaveBusinessRuleScript(tvBusinessRule.SelectedNode);
MessageBox.Show("Script is Saved Successfully at " + path);
}
}
private string SaveBusinessRuleScript(TreeNode currentNode)
{
string currentPath = Directory.GetCurrentDirectory();
var currentDirectory = currentPath + @"\BusinessRulesScriptViewerGeneratedScripts";
if (!Directory.Exists(currentDirectory))
{
Directory.CreateDirectory(currentDirectory);
}
if (currentNode != null)
{
var myNode = (BusinessRuleTreeNode)currentNode;
var code = myNode.BusinessRuleProxy.ClientCode;
string fileName = myNode.BusinessRuleProxy.Name + ".js";
foreach (char c in System.IO.Path.GetInvalidFileNameChars())
{
fileName = fileName.Replace(c, '_');
}
string fullPath = currentDirectory + @"\" + fileName;
File.WriteAllLines(fullPath, new string[] { code });
}
return currentDirectory;
}
private void btnSaveAll_Click(object sender, EventArgs e)
{
var path = string.Empty;
foreach (var currentNode in tvBusinessRule.Nodes)
{
path = SaveBusinessRuleScript((TreeNode) currentNode);
}
MessageBox.Show("Scripts is Saved Successfully at " + path);
}
}
}