-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainControl.cs
347 lines (302 loc) · 14.3 KB
/
MainControl.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
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
using ITLec.EmailTemplateManager.Forms;
using ITLec.EmailTemplateManager.Helpers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
using XrmToolBox.Extensibility;
using XrmToolBox.Extensibility.Interfaces;
namespace ITLec.EmailTemplateManager
{
public partial class MainControl : PluginControlBase, IHelpPlugin
{
private string currentFolder;
private ListViewItem[] listViewItemsCache;
public string HelpUrl => "";
#region Constructor
public MainControl()
{
InitializeComponent();
}
#endregion Constructor
#region Main ToolStrip Handlers
#region Fill Entities
public void LoadEntities()
{
txtSearchEntity.Text = string.Empty;
lvEntities.Items.Clear();
gbEntities.Enabled = false;
WorkAsync(new WorkAsyncInfo
{
Message = "Loading entities...",
Work = (bw, e) =>
{
e.Result = MetadataHelper.RetrieveEntities(Service);
},
PostWorkCallBack = e =>
{
if (e.Error != null)
{
MessageBox.Show(ParentForm, e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
lvEntities.Items.Clear();
var list = new List<ListViewItem>();
foreach (EntityMetadata emd in (List<EntityMetadata>)e.Result)
{
var item = new ListViewItem();//
item.Text = (emd.DisplayName.UserLocalizedLabel.Label == "User") ? "Global" : emd.DisplayName.UserLocalizedLabel.Label;
item.Tag = emd.LogicalName;
//{ Text = emd.DisplayName.UserLocalizedLabel.Label, Tag = emd.LogicalName };
item.SubItems.Add(emd.LogicalName);
list.Add(item);
}
listViewItemsCache = list.ToArray();
lvEntities.Items.AddRange(listViewItemsCache);
gbEntities.Enabled = true;
tsbImportEmailTemplates.Enabled = true;
tsbExportEmailTemplates.Enabled = true;
tsbEditEmailTemplate.Enabled = true;
toolStripButtonOpenCRMEditor.Enabled = true;
txtSearchEntity.Focus();
}
}
});
}
private void TsbLoadEntitiesClick(object sender, EventArgs e)
{
ExecuteMethod(LoadEntities);
}
#endregion Fill Entities
#endregion Main ToolStrip Handlers
#region ListViews Handlers
#region Fill Views
private void lvEntities_SelectedIndexChanged(object sender, EventArgs e)
{
if (lvEntities.SelectedItems.Count > 0)
{
string entityLogicalName = lvEntities.SelectedItems[0].Tag.ToString();
Cursor = Cursors.WaitCursor;
lvEmailTemplates.Items.Clear();
WorkAsync(new WorkAsyncInfo
{
Message = "Loading emailTemplates...",
AsyncArgument = entityLogicalName,
Work = (bw, evt) =>
{
evt.Result = EmailTemplateHelper.GetTemplatessByEntity(evt.Argument.ToString(), Service);
},
PostWorkCallBack = evt =>
{
if (evt.Error != null)
{
MessageBox.Show(this, "An error occured: " + evt.Error.Message, "Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else
{
Cursor = Cursors.Default;
var templates = (EntityCollection)evt.Result;
foreach(var entity in templates.Entities)
{
string isPersonalStr = "False";
if(entity.Attributes.Contains("IsPersonal"))
{
var ispersonal= (bool) entity.Attributes["IsPersonal"];
isPersonalStr = (ispersonal) ? "True" : "False";
}
ListViewItem lvi = new ListViewItem( );
lvi.Tag = entity;
lvi.SubItems.Add(entity.GetAttributeValue<string>("title"));
lvi.SubItems.Add(isPersonalStr);
lvi.SubItems.Add(entity.GetAttributeValue<string>("description"));
lvEmailTemplates.Items.Add(lvi);
}
}
}
});
}
}
#endregion Fill Views
#endregion ListViews Handlers
public void ProcessFiles(List<string> files)
{
WorkAsync(new WorkAsyncInfo
{
Message = "Analyzing file(s)...",
AsyncArgument = files,
Work = (bw, e) => { e.Result = EmailTemplateHelper.AnalyzeFiles((List<string>)e.Argument, Service); },
PostWorkCallBack = evt =>
{
var results = (List<EmailTemplateDefinition>)evt.Result;
if (results.Any(r => r.Errors.Count > 0))
{
// Display errors
var elForm = new ErrorsListForm(results);
elForm.ShowDialog(ParentForm);
}
else
{
if (results.Any(r => r.Exists))
{
// Display overwrite confirmation
var ocDialog = new OverwriteConfirmationDialog(results);
var result = ocDialog.ShowDialog(ParentForm);
if (result == DialogResult.Cancel)
return;
}
WorkAsync(new WorkAsyncInfo("Importing file(s)...", (w, evt2) =>
{
EmailTemplateHelper.ImportFiles((List<EmailTemplateDefinition>)evt2.Argument, Service);
w.ReportProgress(0, "Publishing entities...");
Service.Execute(new PublishXmlRequest
{
ParameterXml = string.Format("<importexportxml><entities>{0}</entities><nodes/><securityroles/><settings/><workflows/></importexportxml>", string.Join("", results.Select(r => string.Format("<entity>{0}</entity>", r.Entity.GetAttributeValue<string>("primaryentitytypecode")))))
});
})
{
AsyncArgument = results,
PostWorkCallBack = evt2 =>
{
if (evt2.Error != null)
{
MessageBox.Show(ParentForm, evt2.Error.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show(ParentForm, "EmailTemplate(s) imported!", "Information",
MessageBoxButtons.OK, MessageBoxIcon.Information);
lvEntities_SelectedIndexChanged(null, null);
}
},
ProgressChanged = evt2 =>
{
SetWorkingMessage(evt2.UserState.ToString());
}
});
}
}
});
}
private void importEmailTemplatesFromFileToolStripMenuItem_Click(object sender, EventArgs e)
{
using (var ofd = new OpenFileDialog { Filter = "XML file|*.xml", InitialDirectory = currentFolder })
{
if (ofd.ShowDialog(ParentForm) == DialogResult.OK)
{
ExecuteMethod(ProcessFiles, new List<string> { ofd.FileName });
}
}
}
private void importEmailTemplatesFromFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
var cfbDialog = new CustomFolderBrowserDialog(true) { FolderPath = currentFolder };
if (cfbDialog.ShowDialog(ParentForm) == DialogResult.OK)
{
currentFolder = cfbDialog.FolderPath;
ExecuteMethod(ProcessFiles, new DirectoryInfo(currentFolder).GetFiles("*.xml").Select(f => f.FullName).ToList());
}
}
private void ListViewColumnClick(object sender, ColumnClickEventArgs e)
{
var listView = (ListView)sender;
listView.Sorting = listView.Sorting == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
listView.ListViewItemSorter = new ListViewItemComparer(e.Column, listView.Sorting);
}
private void OnSearchKeyUp(object sender, KeyEventArgs e)
{
var entityName = txtSearchEntity.Text;
if (string.IsNullOrWhiteSpace(entityName))
{
lvEntities.BeginUpdate();
lvEntities.Items.Clear();
lvEntities.Items.AddRange(listViewItemsCache);
lvEntities.EndUpdate();
}
else
{
lvEntities.BeginUpdate();
lvEntities.Items.Clear();
var filteredItems = listViewItemsCache
.Where(item => item.Text.StartsWith(entityName, StringComparison.OrdinalIgnoreCase))
.ToArray();
lvEntities.Items.AddRange(filteredItems);
lvEntities.EndUpdate();
}
}
private void TsbCloseThisTabClick(object sender, EventArgs e)
{
CloseTool();
}
private void tsbEditEmailTemplate_Click(object sender, EventArgs e)
{
if (lvEmailTemplates.SelectedItems.Count == 0)
return;
var editor = new EmailTemplateEditor((Entity)lvEmailTemplates.SelectedItems[0].Tag, Service);
editor.ShowDialog(ParentForm);
if (editor.HasUpdatedContent)
{
lvEntities_SelectedIndexChanged(null, null);
}
}
private void tsbExportEmailTemplates_Click(object sender, EventArgs e)
{
var emailTemplatesToExport = lvEmailTemplates.CheckedItems.Cast<ListViewItem>().Select(c => (Entity)c.Tag).ToList();
if (emailTemplatesToExport.Count > 0)
{
try
{
var cfbDialog = new CustomFolderBrowserDialog(false) { FolderPath = currentFolder };
if (cfbDialog.ShowDialog(ParentForm) == DialogResult.OK)
{
currentFolder = cfbDialog.FolderPath;
foreach (var emailTemplate in emailTemplatesToExport)
{
var doc = new XDocument(
new XElement("visualization",
new XElement("visualizationid", emailTemplate.Id.ToString("B")),
new XElement("name", emailTemplate.GetAttributeValue<string>("name")),
new XElement("description", emailTemplate.GetAttributeValue<string>("description")),
new XElement("primaryentitytypecode", emailTemplate.GetAttributeValue<string>("primaryentitytypecode")),
new XElement("datadescription", XElement.Parse(emailTemplate.GetAttributeValue<string>("datadescription"))),
new XElement("presentationdescription", XElement.Parse(emailTemplate.GetAttributeValue<string>("presentationdescription"))),
new XElement("isdefault", emailTemplate.GetAttributeValue<bool>("isdefault"))
));
var filename = string.Format("{0}{1}.xml",
emailTemplate.GetAttributeValue<string>("name"),
emailTemplate.LogicalName == "savedqueryvisualization" ? "" : "_personal");
doc.Save(Path.Combine(cfbDialog.FolderPath, filename));
}
if (MessageBox.Show(ParentForm, "Would you like to open destination folder?", "Question",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Process.Start(cfbDialog.FolderPath);
}
}
}
catch (Exception error)
{
MessageBox.Show(ParentForm, error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void toolStripButtonOpenCRMEditor_Click(object sender, EventArgs e)
{
if (lvEmailTemplates.SelectedItems.Count == 0)
return;
var entity = (Entity)lvEmailTemplates.SelectedItems[0].Tag;
string url = ConnectionDetail.WebApplicationUrl + @"tools/emailtemplateeditor/emailtemplateeditor.aspx?id=" + entity.Id.ToString();
ProcessStartInfo sInfo = new ProcessStartInfo(url);
Process.Start(sInfo);
}
}
}