-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSSMSObjectExplorerMenu.cs
374 lines (316 loc) · 9.29 KB
/
SSMSObjectExplorerMenu.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
using EnvDTE;
using EnvDTE80;
using Microsoft.SqlServer.Management.UI.VSIntegration;
using Microsoft.SqlServer.Management.UI.VSIntegration.Editors;
using Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using SSMSObjectExplorerMenu.objects;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace SSMSObjectExplorerMenu
{
[ProvideAutoLoad("d114938f-591c-46cf-a785-500a82d97410")] //CommandGuids.ObjectExplorerToolWindowIDString
[ProvideOptionPage(typeof(OptionsDialogPage), "SQL Server Object Explorer", "SSMS Object Explorer Menu", 0, 0, true)]
public sealed class SSMSObjectExplorerMenu : Package
{
private OptionsDialogPage options;
private TreeView treeView;
private IObjectExplorerService objectExplorerService;
public SSMSObjectExplorerMenu()
{
}
protected override void Initialize()
{
base.Initialize();
//load settings from options dialog
(this as IVsPackage).GetAutomationObject("SQL Server Object Explorer.SSMS Object Explorer Menu", out object automationObject);
if (automationObject == null)
{
Error("Automation Object not found");
return;
}
options = (OptionsDialogPage)automationObject;
//find tree control in the Object Explorer window
objectExplorerService = (IObjectExplorerService)this.GetService(typeof(IObjectExplorerService));
if (objectExplorerService == null)
{
Error("Object Explorer Service not found");
return;
}
var treeProperty = objectExplorerService.GetType().GetProperty("Tree", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (treeProperty == null)
{
Error("Tree property not found");
return;
}
treeView = (TreeView)treeProperty.GetValue(objectExplorerService, null);
if (treeView == null)
{
Error("TreeView control not found");
return;
}
treeView.ContextMenuStripChanged += TreeView_ContextMenuStripChanged;
}
private void TreeView_ContextMenuStripChanged(object sender, EventArgs e)
{
//sanity check objects
if (treeView == null || options == null || objectExplorerService == null)
{
return;
}
if (treeView.SelectedNode == null || treeView.ContextMenuStrip == null)
{
return;
}
if (treeView.ContextMenuStrip.Items == null)
{
return;
}
//get the selected tree node
objectExplorerService.GetSelectedNodes(out int arraySize, out INodeInformation[] nodes);
if (arraySize == 0 || nodes.Length == 0)
{
return;
}
//get meta data from tree node
NodeInfo nodeInfo = nodes[0].GetInfo();
//build context menu
ToolStripMenuItem myScriptsMenu = new ToolStripMenuItem(options.Text);
if (options.ShowIcon)
{
myScriptsMenu.Image = Properties.Resources.plus;
}
if (options.MenuItems != null)
{
foreach (var menuItem in options.MenuItems)
{
if (!menuItem.Enabled || menuItem.Name == string.Empty)
{
continue;
}
if (menuItem.Context == "All" || menuItem.Context == nodes[0].UrnPath)
{
MenuItemInstance instance = new MenuItemInstance(menuItem, nodeInfo);
ToolStripMenuItem s = new ToolStripMenuItem(menuItem.Name)
{
Tag = instance
};
s.Click += Menu_Click;
myScriptsMenu.DropDownItems.Add(s);
}
}
}
if (myScriptsMenu.DropDownItems.Count > 0
&& (
options.ShowNewButton
|| options.ShowOptionsButton
|| options.ShowImportButton
|| options.ShowExportButton
))
{
myScriptsMenu.DropDownItems.Add(new ToolStripSeparator());
}
if (options.ShowNewButton)
{
ToolStripMenuItem add = new ToolStripMenuItem("New");
add.Click += Add_Click;
add.Tag = nodeInfo;
myScriptsMenu.DropDownItems.Add(add);
}
if (options.ShowImportButton)
{
ToolStripMenuItem imp = new ToolStripMenuItem("Import");
imp.Click += Import_Click;
imp.Tag = nodeInfo;
myScriptsMenu.DropDownItems.Add(imp);
}
if (options.ShowExportButton)
{
ToolStripMenuItem exp = new ToolStripMenuItem("Export");
exp.Click += Export_Click;
exp.Tag = nodeInfo;
myScriptsMenu.DropDownItems.Add(exp);
}
if (options.ShowOptionsButton)
{
ToolStripMenuItem opt = new ToolStripMenuItem("Options");
opt.Click += Options_Click;
opt.Tag = nodeInfo;
myScriptsMenu.DropDownItems.Add(opt);
}
if (myScriptsMenu.DropDownItems.Count == 0)
{
return;
}
treeView.ContextMenuStrip.Items.Add(myScriptsMenu);
treeView.ContextMenuStrip.Items.Add(new ToolStripSeparator());
}
private void Add_Click(object sender, EventArgs e)
{
NodeInfo nodeInfo = (NodeInfo)(sender as ToolStripMenuItem).Tag;
AddMenuItem add = new AddMenuItem(nodeInfo);
DialogResult d = add.ShowDialog();
if (d == DialogResult.OK)
{
options.MenuItems.Add(add.GetMenuItem());
options.SaveSettingsToStorage();
}
}
private void Options_Click(object sender, EventArgs e)
{
ShowOptionPage(typeof(OptionsDialogPage));
}
private void Export_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog
{
AddExtension = true,
Filter = "Xml (*.xml)|*.xml",
DefaultExt = "xml",
Title = "Export menu items as XML",
ValidateNames = true
};
if (save.ShowDialog() == DialogResult.OK)
{
try
{
File.WriteAllText(save.FileName, options.MenuItemsXml);
}
catch (Exception ex)
{
Error($"Error saving to {save.FileName}: {ex.Message}");
}
}
}
private void Import_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog
{
AddExtension = true,
CheckFileExists = true,
DefaultExt = "xml",
Filter = "Xml (*.xml)|*.xml",
Multiselect = false,
Title = "Import menu items from XML"
};
if (open.ShowDialog() == DialogResult.OK)
{
int count = 0;
try
{
List<objects.MenuItem> menuItems = File.ReadAllText(open.FileName).DeserializeObject<List<objects.MenuItem>>();
foreach (objects.MenuItem item in menuItems)
{
if (options.MenuItems.FindIndex(x => (x.Name == item.Name && x.Context == item.Context)) == -1)
{
options.MenuItems.Add(item);
count += 1;
}
}
options.SaveSettingsToStorage();
Show($"{count} menu item{ ((count == 1) ? "":"s") } imported", MessageBoxIcon.Information);
}
catch (Exception ex)
{
Error($"Error importing menu items from {open.FileName}: {ex.Message}");
}
}
}
private void Menu_Click(object sender, EventArgs e)
{
if (treeView == null || sender == null)
{
return;
}
if (treeView.SelectedNode == null)
{
return;
}
ToolStripMenuItem tool = (sender as ToolStripMenuItem);
if (tool.Tag == null)
{
return;
}
MenuItemInstance itemInstance = (MenuItemInstance)tool.Tag;
string script;
if (File.Exists(itemInstance.MenuItem.Script))
{
try
{
script = File.ReadAllText(itemInstance.MenuItem.Script);
script = $"-- File:\t\t{itemInstance.MenuItem.Script}{Environment.NewLine}" + script;
}
catch (Exception ex)
{
Error($"Error reading {itemInstance.MenuItem.Script}: {ex.Message}");
return;
}
}
else
{
script = itemInstance.MenuItem.Script;
}
script = script
.Replace("{SERVER}", itemInstance.NodeInfo.Server)
.Replace("{DATABASE}", itemInstance.NodeInfo.Database)
.Replace("{TABLE}", itemInstance.NodeInfo.Table)
.Replace("{VIEW}", itemInstance.NodeInfo.View)
.Replace("{STORED_PROCEDURE}", itemInstance.NodeInfo.StoredProcedure)
.Replace("{FUNCTION}", itemInstance.NodeInfo.Function)
.Replace("{SCHEMA}", itemInstance.NodeInfo.Schema)
.Replace("{JOB}", itemInstance.NodeInfo.Job)
.Replace("{YYYY-MM-DD}", DateTime.Now.ToString("yyyy-MM-dd"))
.Replace("{HH:mm:ss}", DateTime.Now.ToString("HH:mm:ss"))
.Replace("{YYYY-MM-DD HH:mm:ss}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
DTE2 dte = (DTE2)this.GetService(typeof(DTE));
if (dte == null)
{
return;
}
IScriptFactory scriptFactory = ServiceCache.ScriptFactory;
if (scriptFactory == null)
{
return;
}
scriptFactory.CreateNewBlankScript(ScriptType.Sql);
if (dte.ActiveDocument != null)
{
TextSelection ts = (TextSelection)dte.ActiveDocument.Selection;
ts.Insert(script, (int)vsInsertFlags.vsInsertFlagsInsertAtStart);
if (itemInstance.MenuItem.Execute)
{
if (itemInstance.MenuItem.Confirm)
{
Warning($"Execute \"{itemInstance.MenuItem.Name}\"?{Environment.NewLine}{Environment.NewLine}{itemInstance.NodeInfo}", () =>
{
dte.ActiveDocument.DTE.ExecuteCommand("Query.Execute");
});
}
else
{
dte.ActiveDocument.DTE.ExecuteCommand("Query.Execute");
}
}
}
}
private void Warning(string message, Action action)
{
Show(message, MessageBoxIcon.Warning, MessageBoxButtons.OKCancel, action);
}
private void Error(string message)
{
Show(message, MessageBoxIcon.Error);
}
private void Show(string message, MessageBoxIcon icon, MessageBoxButtons buttons = MessageBoxButtons.OK, Action action = null)
{
if (MessageBox.Show(message, "SSMS Object Explorer Menu", buttons, icon) == DialogResult.OK)
{
action?.Invoke();
}
}
}
}